camenduru commited on
Commit
857af3d
·
1 Parent(s): 8d1582a
.gitattributes CHANGED
@@ -32,3 +32,6 @@ 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
+ engine/clip.plan filter=lfs diff=lfs merge=lfs -text
36
+ engine/unet_fp16.plan filter=lfs diff=lfs merge=lfs -text
37
+ engine/vae.plan filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ onnx/*.onnx
3
+ engine/*.plan
4
+ output/*.png
README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Introduction
2
+
3
+ This demo application ("demoDiffusion") showcases the acceleration of [Stable Diffusion](https://huggingface.co/CompVis/stable-diffusion-v1-4) pipeline using TensorRT plugins.
4
+
5
+ # Setup
6
+
7
+ ### Clone the TensorRT OSS repository
8
+
9
+ ```bash
10
+ git clone git@github.com:NVIDIA/TensorRT.git -b release/8.5 --single-branch
11
+ cd TensorRT
12
+ git submodule update --init --recursive
13
+ ```
14
+
15
+ ### Launch TensorRT NGC container
16
+
17
+ Install nvidia-docker using [these intructions](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker).
18
+
19
+ ```bash
20
+ docker run --rm -it --gpus all -v $PWD:/workspace nvcr.io/nvidia/tensorrt:22.10-py3 /bin/bash
21
+ ```
22
+
23
+ ### (Optional) Install latest TensorRT release
24
+
25
+ ```bash
26
+ python3 -m pip install --upgrade pip
27
+ python3 -m pip install --upgrade tensorrt
28
+ ```
29
+ > NOTE: Alternatively, you can download and install TensorRT packages from [NVIDIA TensorRT Developer Zone](https://developer.nvidia.com/tensorrt).
30
+
31
+ ### Build TensorRT plugins library
32
+
33
+ Build TensorRT Plugins library using the [TensorRT OSS build instructions](https://github.com/NVIDIA/TensorRT/blob/main/README.md#building-tensorrt-oss).
34
+
35
+ ```bash
36
+ export TRT_OSSPATH=/workspace
37
+
38
+ cd $TRT_OSSPATH
39
+ mkdir -p build && cd build
40
+ cmake .. -DTRT_OUT_DIR=$PWD/out
41
+ cd plugin
42
+ make -j$(nproc)
43
+
44
+ export PLUGIN_LIBS="$TRT_OSSPATH/build/out/libnvinfer_plugin.so"
45
+ ```
46
+
47
+ ### Install required packages
48
+
49
+ ```bash
50
+ cd $TRT_OSSPATH/demo/Diffusion
51
+ pip3 install -r requirements.txt
52
+
53
+ # Create output directories
54
+ mkdir -p onnx engine output
55
+ ```
56
+
57
+ > NOTE: demoDiffusion has been tested on systems with NVIDIA A100, RTX3090, and RTX4090 GPUs, and the following software configuration.
58
+ ```
59
+ cuda-python 11.8.1
60
+ diffusers 0.7.2
61
+ onnx 1.12.0
62
+ onnx-graphsurgeon 0.3.25
63
+ onnxruntime 1.13.1
64
+ polygraphy 0.43.1
65
+ tensorrt 8.5.1.7
66
+ tokenizers 0.13.2
67
+ torch 1.12.0+cu116
68
+ transformers 4.24.0
69
+ ```
70
+
71
+ > NOTE: optionally install HuggingFace [accelerate](https://pypi.org/project/accelerate/) package for faster and less memory-intense model loading.
72
+
73
+
74
+ # Running demoDiffusion
75
+
76
+ ### Review usage instructions
77
+
78
+ ```bash
79
+ python3 demo-diffusion.py --help
80
+ ```
81
+
82
+ ### HuggingFace user access token
83
+
84
+ To download the model checkpoints for the Stable Diffusion pipeline, you will need a `read` access token. See [instructions](https://huggingface.co/docs/hub/security-tokens).
85
+
86
+ ```bash
87
+ export HF_TOKEN=<your access token>
88
+ ```
89
+
90
+ ### Generate an image guided by a single text prompt
91
+
92
+ ```bash
93
+ LD_PRELOAD=${PLUGIN_LIBS} python3 demo-diffusion.py "a beautiful photograph of Mt. Fuji during cherry blossom" --hf-token=$HF_TOKEN -v
94
+ ```
95
+
96
+ # Restrictions
97
+ - Upto 16 simultaneous prompts (maximum batch size) per inference.
98
+ - For generating images of dynamic shapes without rebuilding the engines, use `--force-dynamic-shape`.
99
+ - Supports images sizes between 256x256 and 1024x1024.
__pycache__/models.cpython-38.pyc ADDED
Binary file (29.3 kB). View file
 
__pycache__/utilities.cpython-38.pyc ADDED
Binary file (16.1 kB). View file
 
demo-diffusion.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ import argparse
19
+ from cuda import cudart
20
+ from models import CLIP, UNet, VAE
21
+ import numpy as np
22
+ import nvtx
23
+ import os
24
+ import onnx
25
+ from polygraphy import cuda
26
+ import time
27
+ import torch
28
+ from transformers import CLIPTokenizer
29
+ import tensorrt as trt
30
+ from utilities import Engine, DPMScheduler, LMSDiscreteScheduler, save_image, TRT_LOGGER
31
+
32
+ def parseArgs():
33
+ parser = argparse.ArgumentParser(description="Options for Stable Diffusion Demo")
34
+ # Stable Diffusion configuration
35
+ parser.add_argument('prompt', nargs = '*', help="Text prompt(s) to guide image generation")
36
+ parser.add_argument('--negative-prompt', nargs = '*', default=[''], help="The negative prompt(s) to guide the image generation.")
37
+ parser.add_argument('--repeat-prompt', type=int, default=1, choices=[1, 2, 4, 8, 16], help="Number of times to repeat the prompt (batch size multiplier)")
38
+ parser.add_argument('--height', type=int, default=512, help="Height of image to generate (must be multiple of 8)")
39
+ parser.add_argument('--width', type=int, default=512, help="Height of image to generate (must be multiple of 8)")
40
+ parser.add_argument('--num-images', type=int, default=1, help="Number of images to generate per prompt")
41
+ parser.add_argument('--denoising-steps', type=int, default=50, help="Number of denoising steps")
42
+ parser.add_argument('--denoising-prec', type=str, default='fp16', choices=['fp32', 'fp16'], help="Denoiser model precision")
43
+ parser.add_argument('--scheduler', type=str, default="LMSD", choices=["LMSD", "DPM"], help="Scheduler for diffusion process")
44
+
45
+ # ONNX export
46
+ parser.add_argument('--onnx-opset', type=int, default=16, choices=range(7,18), help="Select ONNX opset version to target for exported models")
47
+ parser.add_argument('--onnx-dir', default='onnx', help="Output directory for ONNX export")
48
+ parser.add_argument('--force-onnx-export', action='store_true', help="Force ONNX export of CLIP, UNET, and VAE models")
49
+ parser.add_argument('--force-onnx-optimize', action='store_true', help="Force ONNX optimizations for CLIP, UNET, and VAE models")
50
+ parser.add_argument('--onnx-minimal-optimization', action='store_true', help="Restrict ONNX optimization to const folding and shape inference.")
51
+
52
+ # TensorRT engine build
53
+ parser.add_argument('--engine-dir', default='engine', help="Output directory for TensorRT engines")
54
+ parser.add_argument('--force-engine-build', action='store_true', help="Force rebuilding the TensorRT engine")
55
+ parser.add_argument('--build-static-batch', action='store_true', help="Build TensorRT engines with fixed batch size.")
56
+ parser.add_argument('--build-dynamic-shape', action='store_true', help="Build TensorRT engines with dynamic image shapes.")
57
+ parser.add_argument('--build-preview-features', action='store_true', help="Build TensorRT engines with preview features.")
58
+
59
+ # TensorRT inference
60
+ parser.add_argument('--num-warmup-runs', type=int, default=5, help="Number of warmup runs before benchmarking performance")
61
+ parser.add_argument('--nvtx-profile', action='store_true', help="Enable NVTX markers for performance profiling")
62
+ parser.add_argument('--seed', type=int, default=None, help="Seed for random generator to get consistent results")
63
+
64
+ parser.add_argument('--output-dir', default='output', help="Output directory for logs and image artifacts")
65
+ parser.add_argument('--hf-token', type=str, help="HuggingFace API access token for downloading model checkpoints")
66
+ parser.add_argument('-v', '--verbose', action='store_true', help="Show verbose output")
67
+ return parser.parse_args()
68
+
69
+ class DemoDiffusion:
70
+ """
71
+ Application showcasing the acceleration of Stable Diffusion v1.4 pipeline using NVidia TensorRT w/ Plugins.
72
+ """
73
+ def __init__(
74
+ self,
75
+ denoising_steps,
76
+ denoising_fp16=True,
77
+ scheduler="LMSD",
78
+ guidance_scale=7.5,
79
+ device='cuda',
80
+ output_dir='.',
81
+ hf_token=None,
82
+ verbose=False,
83
+ nvtx_profile=False,
84
+ max_batch_size=16
85
+ ):
86
+ """
87
+ Initializes the Diffusion pipeline.
88
+
89
+ Args:
90
+ denoising_steps (int):
91
+ The number of denoising steps.
92
+ More denoising steps usually lead to a higher quality image at the expense of slower inference.
93
+ denoising_fp16 (bool):
94
+ Run the denoising loop (UNet) in fp16 precision.
95
+ When enabled image quality will be lower but generally results in higher throughput.
96
+ guidance_scale (float):
97
+ Guidance scale is enabled by setting as > 1.
98
+ Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality.
99
+ device (str):
100
+ PyTorch device to run inference. Default: 'cuda'
101
+ output_dir (str):
102
+ Output directory for log files and image artifacts
103
+ hf_token (str):
104
+ HuggingFace User Access Token to use for downloading Stable Diffusion model checkpoints.
105
+ verbose (bool):
106
+ Enable verbose logging.
107
+ nvtx_profile (bool):
108
+ Insert NVTX profiling markers.
109
+ max_batch_size (int):
110
+ Max batch size for dynamic batch engines.
111
+ """
112
+ # Only supports single image per prompt.
113
+ self.num_images = 1
114
+
115
+ self.denoising_steps = denoising_steps
116
+ self.denoising_fp16 = denoising_fp16
117
+ assert guidance_scale > 1.0
118
+ self.guidance_scale = guidance_scale
119
+
120
+ self.output_dir = output_dir
121
+ self.hf_token = hf_token
122
+ self.device = device
123
+ self.verbose = verbose
124
+ self.nvtx_profile = nvtx_profile
125
+
126
+ # A scheduler to be used in combination with unet to denoise the encoded image latens.
127
+ # This demo uses an adaptation of LMSDiscreteScheduler or DPMScheduler:
128
+ sched_opts = {'num_train_timesteps': 1000, 'beta_start': 0.00085, 'beta_end': 0.012}
129
+ if scheduler == "DPM":
130
+ self.scheduler = DPMScheduler(device=self.device, **sched_opts)
131
+ elif scheduler == "LMSD":
132
+ self.scheduler = LMSDiscreteScheduler(device=self.device, **sched_opts)
133
+ else:
134
+ raise ValueError(f"Scheduler should be either DPM or LMSD")
135
+
136
+ self.tokenizer = None
137
+
138
+ self.unet_model_key = 'unet_fp16' if denoising_fp16 else 'unet'
139
+ self.models = {
140
+ 'clip': CLIP(hf_token=hf_token, device=device, verbose=verbose, max_batch_size=max_batch_size),
141
+ self.unet_model_key: UNet(hf_token=hf_token, fp16=denoising_fp16, device=device, verbose=verbose, max_batch_size=max_batch_size),
142
+ 'vae': VAE(hf_token=hf_token, device=device, verbose=verbose, max_batch_size=max_batch_size)
143
+ }
144
+
145
+ self.engine = {}
146
+ self.stream = cuda.Stream()
147
+
148
+ def teardown(self):
149
+ for engine in self.engine.values():
150
+ del engine
151
+ self.stream.free()
152
+ del self.stream
153
+
154
+ def getModelPath(self, name, onnx_dir, opt=True):
155
+ return os.path.join(onnx_dir, name+('.opt' if opt else '')+'.onnx')
156
+
157
+ def loadEngines(
158
+ self,
159
+ engine_dir,
160
+ onnx_dir,
161
+ onnx_opset,
162
+ opt_batch_size,
163
+ opt_image_height,
164
+ opt_image_width,
165
+ force_export=False,
166
+ force_optimize=False,
167
+ force_build=False,
168
+ minimal_optimization=False,
169
+ static_batch=False,
170
+ static_shape=True,
171
+ enable_preview=False,
172
+ ):
173
+ """
174
+ Build and load engines for TensorRT accelerated inference.
175
+ Export ONNX models first, if applicable.
176
+
177
+ Args:
178
+ engine_dir (str):
179
+ Directory to write the TensorRT engines.
180
+ onnx_dir (str):
181
+ Directory to write the ONNX models.
182
+ onnx_opset (int):
183
+ ONNX opset version to export the models.
184
+ opt_batch_size (int):
185
+ Batch size to optimize for during engine building.
186
+ opt_image_height (int):
187
+ Image height to optimize for during engine building. Must be a multiple of 8.
188
+ opt_image_width (int):
189
+ Image width to optimize for during engine building. Must be a multiple of 8.
190
+ force_export (bool):
191
+ Force re-exporting the ONNX models.
192
+ force_optimize (bool):
193
+ Force re-optimizing the ONNX models.
194
+ force_build (bool):
195
+ Force re-building the TensorRT engine.
196
+ minimal_optimization (bool):
197
+ Apply minimal optimizations during build (no plugins).
198
+ static_batch (bool):
199
+ Build engine only for specified opt_batch_size.
200
+ static_shape (bool):
201
+ Build engine only for specified opt_image_height & opt_image_width. Default = True.
202
+ enable_preview (bool):
203
+ Enable TensorRT preview features.
204
+ """
205
+
206
+ # Build engines
207
+ for model_name, obj in self.models.items():
208
+ engine = Engine(model_name, engine_dir)
209
+ if force_build or not os.path.exists(engine.engine_path):
210
+ onnx_path = self.getModelPath(model_name, onnx_dir, opt=False)
211
+ onnx_opt_path = self.getModelPath(model_name, onnx_dir)
212
+ if not os.path.exists(onnx_opt_path):
213
+ # Export onnx
214
+ if force_export or not os.path.exists(onnx_path):
215
+ print(f"Exporting model: {onnx_path}")
216
+ model = obj.get_model()
217
+ with torch.inference_mode(), torch.autocast("cuda"):
218
+ inputs = obj.get_sample_input(opt_batch_size, opt_image_height, opt_image_width)
219
+ torch.onnx.export(model,
220
+ inputs,
221
+ onnx_path,
222
+ export_params=True,
223
+ opset_version=onnx_opset,
224
+ do_constant_folding=True,
225
+ input_names = obj.get_input_names(),
226
+ output_names = obj.get_output_names(),
227
+ dynamic_axes=obj.get_dynamic_axes(),
228
+ )
229
+ else:
230
+ print(f"Found cached model: {onnx_path}")
231
+
232
+ # Optimize onnx
233
+ if force_optimize or not os.path.exists(onnx_opt_path):
234
+ print(f"Generating optimizing model: {onnx_opt_path}")
235
+ onnx_opt_graph = obj.optimize(onnx.load(onnx_path), minimal_optimization=minimal_optimization)
236
+ onnx.save(onnx_opt_graph, onnx_opt_path)
237
+ else:
238
+ print(f"Found cached optimized model: {onnx_opt_path} ")
239
+
240
+ # Build engine
241
+ engine.build(onnx_opt_path, fp16=True, \
242
+ input_profile=obj.get_input_profile(opt_batch_size, opt_image_height, opt_image_width, \
243
+ static_batch=static_batch, static_shape=static_shape), \
244
+ enable_preview=enable_preview)
245
+ self.engine[model_name] = engine
246
+
247
+ # Separate iteration to activate engines
248
+ for model_name, obj in self.models.items():
249
+ self.engine[model_name].activate()
250
+
251
+ def loadModules(
252
+ self,
253
+ ):
254
+ self.tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
255
+ self.scheduler.set_timesteps(self.denoising_steps)
256
+ # Pre-compute latent input scales and linear multistep coefficients
257
+ self.scheduler.configure()
258
+
259
+ def runEngine(self, model_name, feed_dict):
260
+ engine = self.engine[model_name]
261
+ return engine.infer(feed_dict, self.stream)
262
+
263
+ def infer(
264
+ self,
265
+ prompt,
266
+ negative_prompt,
267
+ image_height,
268
+ image_width,
269
+ warmup = False,
270
+ verbose = False,
271
+ ):
272
+ """
273
+ Run the diffusion pipeline.
274
+
275
+ Args:
276
+ prompt (str):
277
+ The text prompt to guide image generation.
278
+ negative_prompt (str):
279
+ The prompt not to guide the image generation.
280
+ image_height (int):
281
+ Height (in pixels) of the image to be generated. Must be a multiple of 8.
282
+ image_width (int):
283
+ Width (in pixels) of the image to be generated. Must be a multiple of 8.
284
+ warmup (bool):
285
+ Indicate if this is a warmup run.
286
+ verbose (bool):
287
+ Enable verbose logging.
288
+ """
289
+ # Process inputs
290
+ batch_size = len(prompt)
291
+ assert len(prompt) == len(negative_prompt)
292
+
293
+ # Spatial dimensions of latent tensor
294
+ latent_height = image_height // 8
295
+ latent_width = image_width // 8
296
+
297
+ # Create profiling events
298
+ events = {}
299
+ for stage in ['clip', 'denoise', 'vae']:
300
+ for marker in ['start', 'stop']:
301
+ events[stage+'-'+marker] = cudart.cudaEventCreate()[1]
302
+
303
+ # Allocate buffers for TensorRT engine bindings
304
+ for model_name, obj in self.models.items():
305
+ self.engine[model_name].allocate_buffers(shape_dict=obj.get_shape_dict(batch_size, image_height, image_width), device=self.device)
306
+
307
+ generator = None
308
+ if args.seed is not None:
309
+ generator = torch.Generator(device="cuda").manual_seed(args.seed)
310
+
311
+ # Run Stable Diffusion pipeline
312
+ with torch.inference_mode(), torch.autocast("cuda"), trt.Runtime(TRT_LOGGER) as runtime:
313
+ # latents need to be generated on the target device
314
+ unet_channels = 4 # unet.in_channels
315
+ latents_shape = (batch_size * self.num_images, unet_channels, latent_height, latent_width)
316
+ latents_dtype = torch.float32 # text_embeddings.dtype
317
+ latents = torch.randn(latents_shape, device=self.device, dtype=latents_dtype, generator=generator)
318
+
319
+ # Scale the initial noise by the standard deviation required by the scheduler
320
+ latents = latents * self.scheduler.init_noise_sigma
321
+
322
+ torch.cuda.synchronize()
323
+ e2e_tic = time.perf_counter()
324
+
325
+ if self.nvtx_profile:
326
+ nvtx_clip = nvtx.start_range(message='clip', color='green')
327
+ cudart.cudaEventRecord(events['clip-start'], 0)
328
+ # Tokenize input
329
+ text_input_ids = self.tokenizer(
330
+ prompt,
331
+ padding="max_length",
332
+ max_length=self.tokenizer.model_max_length,
333
+ return_tensors="pt",
334
+ ).input_ids.type(torch.int32).to(self.device)
335
+
336
+ # CLIP text encoder
337
+ text_input_ids_inp = cuda.DeviceView(ptr=text_input_ids.data_ptr(), shape=text_input_ids.shape, dtype=np.int32)
338
+ text_embeddings = self.runEngine('clip', {"input_ids": text_input_ids_inp})['text_embeddings']
339
+
340
+ # Duplicate text embeddings for each generation per prompt
341
+ bs_embed, seq_len, _ = text_embeddings.shape
342
+ text_embeddings = text_embeddings.repeat(1, self.num_images, 1)
343
+ text_embeddings = text_embeddings.view(bs_embed * self.num_images, seq_len, -1)
344
+
345
+ max_length = text_input_ids.shape[-1]
346
+ uncond_input_ids = self.tokenizer(
347
+ negative_prompt,
348
+ padding="max_length",
349
+ max_length=max_length,
350
+ truncation=True,
351
+ return_tensors="pt",
352
+ ).input_ids.type(torch.int32).to(self.device)
353
+ uncond_input_ids_inp = cuda.DeviceView(ptr=uncond_input_ids.data_ptr(), shape=uncond_input_ids.shape, dtype=np.int32)
354
+ uncond_embeddings = self.runEngine('clip', {"input_ids": uncond_input_ids_inp})['text_embeddings']
355
+
356
+ # Duplicate unconditional embeddings for each generation per prompt
357
+ seq_len = uncond_embeddings.shape[1]
358
+ uncond_embeddings = uncond_embeddings.repeat(1, self.num_images, 1)
359
+ uncond_embeddings = uncond_embeddings.view(batch_size * self.num_images, seq_len, -1)
360
+
361
+ # Concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes for classifier free guidance
362
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
363
+
364
+ if self.denoising_fp16:
365
+ text_embeddings = text_embeddings.to(dtype=torch.float16)
366
+
367
+ cudart.cudaEventRecord(events['clip-stop'], 0)
368
+ if self.nvtx_profile:
369
+ nvtx.end_range(nvtx_clip)
370
+
371
+ cudart.cudaEventRecord(events['denoise-start'], 0)
372
+ for step_index, timestep in enumerate(self.scheduler.timesteps):
373
+ if self.nvtx_profile:
374
+ nvtx_latent_scale = nvtx.start_range(message='latent_scale', color='pink')
375
+ # expand the latents if we are doing classifier free guidance
376
+ latent_model_input = torch.cat([latents] * 2)
377
+ # LMSDiscreteScheduler.scale_model_input()
378
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, step_index)
379
+ if self.nvtx_profile:
380
+ nvtx.end_range(nvtx_latent_scale)
381
+
382
+ # predict the noise residual
383
+ if self.nvtx_profile:
384
+ nvtx_unet = nvtx.start_range(message='unet', color='blue')
385
+ dtype = np.float16 if self.denoising_fp16 else np.float32
386
+ if timestep.dtype != torch.float32:
387
+ timestep_float = timestep.float()
388
+ else:
389
+ timestep_float = timestep
390
+ sample_inp = cuda.DeviceView(ptr=latent_model_input.data_ptr(), shape=latent_model_input.shape, dtype=np.float32)
391
+ timestep_inp = cuda.DeviceView(ptr=timestep_float.data_ptr(), shape=timestep_float.shape, dtype=np.float32)
392
+ embeddings_inp = cuda.DeviceView(ptr=text_embeddings.data_ptr(), shape=text_embeddings.shape, dtype=dtype)
393
+ noise_pred = self.runEngine(self.unet_model_key, {"sample": sample_inp, "timestep": timestep_inp, "encoder_hidden_states": embeddings_inp})['latent']
394
+ if self.nvtx_profile:
395
+ nvtx.end_range(nvtx_unet)
396
+
397
+ if self.nvtx_profile:
398
+ nvtx_latent_step = nvtx.start_range(message='latent_step', color='pink')
399
+ # Perform guidance
400
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
401
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
402
+
403
+ latents = self.scheduler.step(noise_pred, latents, step_index, timestep)
404
+
405
+ if self.nvtx_profile:
406
+ nvtx.end_range(nvtx_latent_step)
407
+
408
+ latents = 1. / 0.18215 * latents
409
+ cudart.cudaEventRecord(events['denoise-stop'], 0)
410
+
411
+ if self.nvtx_profile:
412
+ nvtx_vae = nvtx.start_range(message='vae', color='red')
413
+ cudart.cudaEventRecord(events['vae-start'], 0)
414
+ sample_inp = cuda.DeviceView(ptr=latents.data_ptr(), shape=latents.shape, dtype=np.float32)
415
+ images = self.runEngine('vae', {"latent": sample_inp})['images']
416
+ cudart.cudaEventRecord(events['vae-stop'], 0)
417
+ if self.nvtx_profile:
418
+ nvtx.end_range(nvtx_vae)
419
+
420
+ torch.cuda.synchronize()
421
+ e2e_toc = time.perf_counter()
422
+ if not warmup:
423
+ print('|------------|--------------|')
424
+ print('| {:^10} | {:^12} |'.format('Module', 'Latency'))
425
+ print('|------------|--------------|')
426
+ print('| {:^10} | {:>9.2f} ms |'.format('CLIP', cudart.cudaEventElapsedTime(events['clip-start'], events['clip-stop'])[1]))
427
+ print('| {:^10} | {:>9.2f} ms |'.format('UNet x '+str(self.denoising_steps), cudart.cudaEventElapsedTime(events['denoise-start'], events['denoise-stop'])[1]))
428
+ print('| {:^10} | {:>9.2f} ms |'.format('VAE', cudart.cudaEventElapsedTime(events['vae-start'], events['vae-stop'])[1]))
429
+ print('|------------|--------------|')
430
+ print('| {:^10} | {:>9.2f} ms |'.format('Pipeline', (e2e_toc - e2e_tic)*1000.))
431
+ print('|------------|--------------|')
432
+
433
+ # Save image
434
+ image_name_prefix = 'sd-'+('fp16' if self.denoising_fp16 else 'fp32')+''.join(set(['-'+prompt[i].replace(' ','_')[:10] for i in range(batch_size)]))+'-'
435
+ save_image(images, self.output_dir, image_name_prefix)
436
+
437
+ if __name__ == "__main__":
438
+
439
+ print("[I] Initializing StableDiffusion demo with TensorRT Plugins")
440
+ args = parseArgs()
441
+
442
+ # Process prompt
443
+ if not isinstance(args.prompt, list):
444
+ raise ValueError(f"`prompt` must be of type `str` or `str` list, but is {type(args.prompt)}")
445
+ prompt = args.prompt * args.repeat_prompt
446
+
447
+ if not isinstance(args.negative_prompt, list):
448
+ raise ValueError(f"`--negative-prompt` must be of type `str` or `str` list, but is {type(args.negative_prompt)}")
449
+ if len(args.negative_prompt) == 1:
450
+ negative_prompt = args.negative_prompt * len(prompt)
451
+ else:
452
+ negative_prompt = args.negative_prompt
453
+
454
+ max_batch_size = 16
455
+ if args.build_dynamic_shape:
456
+ max_batch_size = 4
457
+
458
+ if len(prompt) > max_batch_size:
459
+ raise ValueError(f"Batch size {len(prompt)} is larger than allowed {max_batch_size}. If dynamic shape is used, then maximum batch size is 4")
460
+
461
+ # Validate image dimensions
462
+ image_height = args.height
463
+ image_width = args.width
464
+ if image_height % 8 != 0 or image_width % 8 != 0:
465
+ raise ValueError(f"Image height and width have to be divisible by 8 but specified as: {image_height} and {image_width}.")
466
+
467
+ # Register TensorRT plugins
468
+ trt.init_libnvinfer_plugins(TRT_LOGGER, '')
469
+
470
+ # Initialize demo
471
+ demo = DemoDiffusion(
472
+ denoising_steps=args.denoising_steps,
473
+ denoising_fp16=(args.denoising_prec == 'fp16'),
474
+ output_dir=args.output_dir,
475
+ scheduler=args.scheduler,
476
+ hf_token=args.hf_token,
477
+ verbose=args.verbose,
478
+ nvtx_profile=args.nvtx_profile,
479
+ max_batch_size=max_batch_size)
480
+
481
+ # Load TensorRT engines and pytorch modules
482
+ demo.loadEngines(args.engine_dir, args.onnx_dir, args.onnx_opset,
483
+ opt_batch_size=len(prompt), opt_image_height=image_height, opt_image_width=image_width, \
484
+ force_export=args.force_onnx_export, force_optimize=args.force_onnx_optimize, \
485
+ force_build=args.force_engine_build, minimal_optimization=args.onnx_minimal_optimization, \
486
+ static_batch=args.build_static_batch, static_shape=not args.build_dynamic_shape, \
487
+ enable_preview=args.build_preview_features)
488
+ demo.loadModules()
489
+
490
+ print("[I] Warming up ..")
491
+ for _ in range(args.num_warmup_runs):
492
+ images = demo.infer(prompt, negative_prompt, image_height, image_width, warmup=True, verbose=False)
493
+
494
+ print("[I] Running StableDiffusion pipeline")
495
+ if args.nvtx_profile:
496
+ cudart.cudaProfilerStart()
497
+ images = demo.infer(prompt, negative_prompt, image_height, image_width, verbose=args.verbose)
498
+ if args.nvtx_profile:
499
+ cudart.cudaProfilerStop()
500
+
501
+ demo.teardown()
engine/clip.plan ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:924b8fe294a4b892377f2088dbf05077b7b4ec39b81772adc83bf25e91b21ab0
3
+ size 247775035
engine/unet_fp16.plan ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a86c92b493e73d8ce6630cd426a56fb9ed3b49136cbdbd706b3b5814b7b90c9b
3
+ size 1722051918
engine/vae.plan ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ddc71137cdd256dcc5b82c21b856ed25575168881782595e87a7b003534a4711
3
+ size 99632486
models.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ from collections import OrderedDict
19
+ from copy import deepcopy
20
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
21
+ import numpy as np
22
+ from onnx import shape_inference
23
+ import onnx_graphsurgeon as gs
24
+ from polygraphy.backend.onnx.loader import fold_constants
25
+ import torch
26
+ from transformers import CLIPTextModel
27
+ from cuda import cudart
28
+
29
+ class Optimizer():
30
+ def __init__(
31
+ self,
32
+ onnx_graph,
33
+ verbose=False
34
+ ):
35
+ self.graph = gs.import_onnx(onnx_graph)
36
+ self.verbose = verbose
37
+
38
+ def info(self, prefix=''):
39
+ if self.verbose:
40
+ print(f"{prefix} .. {len(self.graph.nodes)} nodes, {len(self.graph.tensors().keys())} tensors, {len(self.graph.inputs)} inputs, {len(self.graph.outputs)} outputs")
41
+
42
+ def cleanup(self, return_onnx=False):
43
+ self.graph.cleanup().toposort()
44
+ if return_onnx:
45
+ return gs.export_onnx(self.graph)
46
+
47
+ def select_outputs(self, keep, names=None):
48
+ self.graph.outputs = [self.graph.outputs[o] for o in keep]
49
+ if names:
50
+ for i, name in enumerate(names):
51
+ self.graph.outputs[i].name = name
52
+
53
+ def fold_constants(self, return_onnx=False):
54
+ onnx_graph = fold_constants(gs.export_onnx(self.graph), allow_onnxruntime_shape_inference=True)
55
+ self.graph = gs.import_onnx(onnx_graph)
56
+ if return_onnx:
57
+ return onnx_graph
58
+
59
+ def infer_shapes(self, return_onnx=False):
60
+ onnx_graph = gs.export_onnx(self.graph)
61
+ if onnx_graph.ByteSize() > 2147483648:
62
+ raise TypeError("ERROR: model size exceeds supported 2GB limit")
63
+ else:
64
+ onnx_graph = shape_inference.infer_shapes(onnx_graph)
65
+
66
+ self.graph = gs.import_onnx(onnx_graph)
67
+ if return_onnx:
68
+ return onnx_graph
69
+
70
+ def remove_casts(self):
71
+ nRemoveCastNode = 0
72
+ for node in self.graph.nodes:
73
+ # Remove Cast nodes before qkv gemm
74
+ if node.op in ["Add", "Transpose"] and len(node.outputs[0].outputs) == 3 and node.o().op == "Cast" and node.o(1).op == "Cast" and node.o(2).op == "Cast":
75
+ for i in range(len(node.outputs[0].outputs)):
76
+ matMulNode = node.o(i, 0).o()
77
+ matMulNode.inputs[0] = node.outputs[0]
78
+ nRemoveCastNode += 1
79
+
80
+ # Remove double cast nodes after Softmax Node
81
+ if node.op == "Softmax" and node.o().op == "Cast" and node.o().o().op == "Cast":
82
+ node.o().o().o().inputs[0] = node.outputs[0]
83
+ nRemoveCastNode += 1
84
+
85
+ self.cleanup()
86
+ return nRemoveCastNode
87
+
88
+ def remove_parallel_swish(self):
89
+ mRemoveSwishNode = 0
90
+ for node in self.graph.nodes:
91
+ if node.op == "Gemm" and len(node.outputs[0].outputs) > 6:
92
+ swishOutputTensor = None
93
+ for nextNode in node.outputs[0].outputs:
94
+ if nextNode.op == "Mul":
95
+ if swishOutputTensor is None:
96
+ swishOutputTensor = nextNode.outputs[0]
97
+ else:
98
+ nextGemmNode = nextNode.o(0)
99
+ assert nextGemmNode.op == "Gemm", "Unexpected node type for nextGemmNode {}".format(nextGemmNode.name)
100
+ nextGemmNode.inputs = [swishOutputTensor, nextGemmNode.inputs[1], nextGemmNode.inputs[2]]
101
+ nextNode.outputs.clear()
102
+ mRemoveSwishNode += 1
103
+
104
+ self.cleanup()
105
+ return mRemoveSwishNode
106
+
107
+ def resize_fix(self):
108
+ '''
109
+ This function loops through the graph looking for Resize nodes that uses scales for resize (has 3 inputs).
110
+ It substitutes found Resize with Resize that takes the size of the output tensor instead of scales.
111
+ It adds Shape->Slice->Concat
112
+ Shape->Slice----^ subgraph to the graph to extract the shape of the output tensor.
113
+ This fix is required for the dynamic shape support.
114
+ '''
115
+ mResizeNodes = 0
116
+ for node in self.graph.nodes:
117
+ if node.op == "Resize" and len(node.inputs) == 3:
118
+ name = node.name + "/"
119
+
120
+ add_node = node.o().o().i(1)
121
+ div_node = node.i()
122
+
123
+ shape_hw_out = gs.Variable(name=name + "shape_hw_out", dtype=np.int64, shape=[4])
124
+ shape_hw = gs.Node(op="Shape", name=name+"shape_hw", inputs=[add_node.outputs[0]], outputs=[shape_hw_out])
125
+
126
+ const_zero = gs.Constant(name=name + "const_zero", values=np.array([0], dtype=np.int64))
127
+ const_two = gs.Constant(name=name + "const_two", values=np.array([2], dtype=np.int64))
128
+ const_four = gs.Constant(name=name + "const_four", values=np.array([4], dtype=np.int64))
129
+
130
+ slice_hw_out = gs.Variable(name=name + "slice_hw_out", dtype=np.int64, shape=[2])
131
+ slice_hw = gs.Node(op="Slice", name=name+"slice_hw", inputs=[shape_hw_out, const_two, const_four, const_zero], outputs=[slice_hw_out])
132
+
133
+ shape_bc_out = gs.Variable(name=name + "shape_bc_out", dtype=np.int64, shape=[2])
134
+ shape_bc = gs.Node(op="Shape", name=name+"shape_bc", inputs=[div_node.outputs[0]], outputs=[shape_bc_out])
135
+
136
+ slice_bc_out = gs.Variable(name=name + "slice_bc_out", dtype=np.int64, shape=[2])
137
+ slice_bc = gs.Node(op="Slice", name=name+"slice_bc", inputs=[shape_bc_out, const_zero, const_two, const_zero], outputs=[slice_bc_out])
138
+
139
+ concat_bchw_out = gs.Variable(name=name + "concat_bchw_out", dtype=np.int64, shape=[4])
140
+ concat_bchw = gs.Node(op="Concat", name=name+"concat_bchw", attrs={"axis": 0}, inputs=[slice_bc_out, slice_hw_out], outputs=[concat_bchw_out])
141
+
142
+ none_var = gs.Variable.empty()
143
+
144
+ resize_bchw = gs.Node(op="Resize", name=name+"resize_bchw", attrs=node.attrs, inputs=[node.inputs[0], none_var, none_var, concat_bchw_out], outputs=[node.outputs[0]])
145
+
146
+ self.graph.nodes.extend([shape_hw, slice_hw, shape_bc, slice_bc, concat_bchw, resize_bchw])
147
+
148
+ node.inputs = []
149
+ node.outputs = []
150
+
151
+ mResizeNodes += 1
152
+
153
+ self.cleanup()
154
+ return mResizeNodes
155
+
156
+
157
+ def adjustAddNode(self):
158
+ nAdjustAddNode = 0
159
+ for node in self.graph.nodes:
160
+ # Change the bias const to the second input to allow Gemm+BiasAdd fusion in TRT.
161
+ if node.op in ["Add"] and isinstance(node.inputs[0], gs.ir.tensor.Constant):
162
+ tensor = node.inputs[1]
163
+ bias = node.inputs[0]
164
+ node.inputs = [tensor, bias]
165
+ nAdjustAddNode += 1
166
+
167
+ self.cleanup()
168
+ return nAdjustAddNode
169
+
170
+ def decompose_instancenorms(self):
171
+ nRemoveInstanceNorm = 0
172
+ for node in self.graph.nodes:
173
+ if node.op == "InstanceNormalization":
174
+ name = node.name + "/"
175
+ input_tensor = node.inputs[0]
176
+ output_tensor = node.outputs[0]
177
+ mean_out = gs.Variable(name=name + "mean_out")
178
+ mean_node = gs.Node(op="ReduceMean", name=name + "mean_node", attrs={"axes": [-1]}, inputs=[input_tensor], outputs=[mean_out])
179
+ sub_out = gs.Variable(name=name + "sub_out")
180
+ sub_node = gs.Node(op="Sub", name=name + "sub_node", attrs={}, inputs=[input_tensor, mean_out], outputs=[sub_out])
181
+ pow_out = gs.Variable(name=name + "pow_out")
182
+ pow_const = gs.Constant(name=name + "pow_const", values=np.array([2.0], dtype=np.float32))
183
+ pow_node = gs.Node(op="Pow", name=name + "pow_node", attrs={}, inputs=[sub_out, pow_const], outputs=[pow_out])
184
+ mean2_out = gs.Variable(name=name + "mean2_out")
185
+ mean2_node = gs.Node(op="ReduceMean", name=name + "mean2_node", attrs={"axes": [-1]}, inputs=[pow_out], outputs=[mean2_out])
186
+ epsilon_out = gs.Variable(name=name + "epsilon_out")
187
+ epsilon_const = gs.Constant(name=name + "epsilon_const", values=np.array([node.attrs["epsilon"]], dtype=np.float32))
188
+ epsilon_node = gs.Node(op="Add", name=name + "epsilon_node", attrs={}, inputs=[mean2_out, epsilon_const], outputs=[epsilon_out])
189
+ sqrt_out = gs.Variable(name=name + "sqrt_out")
190
+ sqrt_node = gs.Node(op="Sqrt", name=name + "sqrt_node", attrs={}, inputs=[epsilon_out], outputs=[sqrt_out])
191
+ div_out = gs.Variable(name=name + "div_out")
192
+ div_node = gs.Node(op="Div", name=name + "div_node", attrs={}, inputs=[sub_out, sqrt_out], outputs=[div_out])
193
+ constantScale = gs.Constant("InstanceNormScaleV-" + str(nRemoveInstanceNorm), np.ascontiguousarray(node.inputs[1].inputs[0].attrs["value"].values.reshape(1, 32, 1)))
194
+ constantBias = gs.Constant("InstanceBiasV-" + str(nRemoveInstanceNorm), np.ascontiguousarray(node.inputs[2].inputs[0].attrs["value"].values.reshape(1, 32, 1)))
195
+ mul_out = gs.Variable(name=name + "mul_out")
196
+ mul_node = gs.Node(op="Mul", name=name + "mul_node", attrs={}, inputs=[div_out, constantScale], outputs=[mul_out])
197
+ add_node = gs.Node(op="Add", name=name + "add_node", attrs={}, inputs=[mul_out, constantBias], outputs=[output_tensor])
198
+ self.graph.nodes.extend([mean_node, sub_node, pow_node, mean2_node, epsilon_node, sqrt_node, div_node, mul_node, add_node])
199
+ node.inputs = []
200
+ node.outputs = []
201
+ nRemoveInstanceNorm += 1
202
+
203
+ self.cleanup()
204
+ return nRemoveInstanceNorm
205
+
206
+ def insert_groupnorm_plugin(self):
207
+ nGroupNormPlugin = 0
208
+ for node in self.graph.nodes:
209
+ if node.op == "Reshape" and node.outputs != [] and \
210
+ node.o().op == "ReduceMean" and node.o(1).op == "Sub" and node.o().o() == node.o(1) and \
211
+ node.o().o().o().o().o().o().o().o().o().o().o().op == "Mul" and \
212
+ node.o().o().o().o().o().o().o().o().o().o().o().o().op == "Add" and \
213
+ len(node.o().o().o().o().o().o().o().o().inputs[1].values.shape) == 3:
214
+ # "node.outputs != []" is added for VAE
215
+
216
+ inputTensor = node.i().inputs[0]
217
+
218
+ gammaNode = node.o().o().o().o().o().o().o().o().o().o().o()
219
+ index = [type(i) == gs.ir.tensor.Constant for i in gammaNode.inputs].index(True)
220
+ gamma = np.array(deepcopy(gammaNode.inputs[index].values.tolist()), dtype=np.float32)
221
+ constantGamma = gs.Constant("groupNormGamma-" + str(nGroupNormPlugin), np.ascontiguousarray(gamma.reshape(-1))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
222
+
223
+ betaNode = gammaNode.o()
224
+ index = [type(i) == gs.ir.tensor.Constant for i in betaNode.inputs].index(True)
225
+ beta = np.array(deepcopy(betaNode.inputs[index].values.tolist()), dtype=np.float32)
226
+ constantBeta = gs.Constant("groupNormBeta-" + str(nGroupNormPlugin), np.ascontiguousarray(beta.reshape(-1)))
227
+
228
+ epsilon = node.o().o().o().o().o().inputs[1].values.tolist()[0]
229
+
230
+ if betaNode.o().op == "Sigmoid": # need Swish
231
+ bSwish = True
232
+ lastNode = betaNode.o().o() # Mul node of Swish
233
+ else:
234
+ bSwish = False
235
+ lastNode = betaNode # Cast node after Group Norm
236
+
237
+ if lastNode.o().op == "Cast":
238
+ lastNode = lastNode.o()
239
+ inputList = [inputTensor, constantGamma, constantBeta]
240
+ groupNormV = gs.Variable("GroupNormV-" + str(nGroupNormPlugin), np.dtype(np.float16), inputTensor.shape)
241
+ groupNormN = gs.Node("GroupNorm", "GroupNormN-" + str(nGroupNormPlugin), inputs=inputList, outputs=[groupNormV], attrs=OrderedDict([('epsilon', epsilon), ('bSwish', int(bSwish))]))
242
+ self.graph.nodes.append(groupNormN)
243
+
244
+ for subNode in self.graph.nodes:
245
+ if lastNode.outputs[0] in subNode.inputs:
246
+ index = subNode.inputs.index(lastNode.outputs[0])
247
+ subNode.inputs[index] = groupNormV
248
+ node.i().inputs = []
249
+ lastNode.outputs = []
250
+ nGroupNormPlugin += 1
251
+
252
+ self.cleanup()
253
+ return nGroupNormPlugin
254
+
255
+ def insert_layernorm_plugin(self):
256
+ nLayerNormPlugin = 0
257
+ for node in self.graph.nodes:
258
+ if node.op == 'ReduceMean' and \
259
+ node.o().op == 'Sub' and node.o().inputs[0] == node.inputs[0] and \
260
+ node.o().o(0).op =='Pow' and node.o().o(1).op =='Div' and \
261
+ node.o().o(0).o().op == 'ReduceMean' and \
262
+ node.o().o(0).o().o().op == 'Add' and \
263
+ node.o().o(0).o().o().o().op == 'Sqrt' and \
264
+ node.o().o(0).o().o().o().o().op == 'Div' and node.o().o(0).o().o().o().o() == node.o().o(1) and \
265
+ node.o().o(0).o().o().o().o().o().op == 'Mul' and \
266
+ node.o().o(0).o().o().o().o().o().o().op == 'Add' and \
267
+ len(node.o().o(0).o().o().o().o().o().inputs[1].values.shape) == 1:
268
+
269
+ if node.i().op == "Add":
270
+ inputTensor = node.inputs[0] # CLIP
271
+ else:
272
+ inputTensor = node.i().inputs[0] # UNet and VAE
273
+
274
+ gammaNode = node.o().o().o().o().o().o().o()
275
+ index = [type(i) == gs.ir.tensor.Constant for i in gammaNode.inputs].index(True)
276
+ gamma = np.array(deepcopy(gammaNode.inputs[index].values.tolist()), dtype=np.float32)
277
+ constantGamma = gs.Constant("LayerNormGamma-" + str(nLayerNormPlugin), np.ascontiguousarray(gamma.reshape(-1))) # MUST use np.ascontiguousarray, or TRT will regard the shape of this Constant as (0) !!!
278
+
279
+ betaNode = gammaNode.o()
280
+ index = [type(i) == gs.ir.tensor.Constant for i in betaNode.inputs].index(True)
281
+ beta = np.array(deepcopy(betaNode.inputs[index].values.tolist()), dtype=np.float32)
282
+ constantBeta = gs.Constant("LayerNormBeta-" + str(nLayerNormPlugin), np.ascontiguousarray(beta.reshape(-1)))
283
+
284
+ inputList = [inputTensor, constantGamma, constantBeta]
285
+ layerNormV = gs.Variable("LayerNormV-" + str(nLayerNormPlugin), np.dtype(np.float32), inputTensor.shape)
286
+ layerNormN = gs.Node("LayerNorm", "LayerNormN-" + str(nLayerNormPlugin), inputs=inputList, attrs=OrderedDict([('epsilon', 1.e-5)]), outputs=[layerNormV])
287
+ self.graph.nodes.append(layerNormN)
288
+ nLayerNormPlugin += 1
289
+
290
+ if betaNode.outputs[0] in self.graph.outputs:
291
+ index = self.graph.outputs.index(betaNode.outputs[0])
292
+ self.graph.outputs[index] = layerNormV
293
+ else:
294
+ if betaNode.o().op == "Cast":
295
+ lastNode = betaNode.o()
296
+ else:
297
+ lastNode = betaNode
298
+ for subNode in self.graph.nodes:
299
+ if lastNode.outputs[0] in subNode.inputs:
300
+ index = subNode.inputs.index(lastNode.outputs[0])
301
+ subNode.inputs[index] = layerNormV
302
+ lastNode.outputs = []
303
+
304
+ self.cleanup()
305
+ return nLayerNormPlugin
306
+
307
+ def insert_splitgelu_plugin(self):
308
+ nSplitGeLUPlugin = 0
309
+ for node in self.graph.nodes:
310
+ if node.op == "Erf":
311
+ inputTensor = node.i().i().i().outputs[0]
312
+ lastNode = node.o().o().o().o()
313
+ outputShape = inputTensor.shape
314
+ outputShape[2] = outputShape[2] // 2
315
+
316
+ splitGeLUV = gs.Variable("splitGeLUV-" + str(nSplitGeLUPlugin), np.dtype(np.float32), outputShape)
317
+ splitGeLUN = gs.Node("SplitGeLU", "splitGeLUN-" + str(nSplitGeLUPlugin), inputs=[inputTensor], outputs=[splitGeLUV])
318
+ self.graph.nodes.append(splitGeLUN)
319
+
320
+ for subNode in self.graph.nodes:
321
+ if lastNode.outputs[0] in subNode.inputs:
322
+ index = subNode.inputs.index(lastNode.outputs[0])
323
+ subNode.inputs[index] = splitGeLUV
324
+ lastNode.outputs = []
325
+ nSplitGeLUPlugin += 1
326
+
327
+ self.cleanup()
328
+ return nSplitGeLUPlugin
329
+
330
+ def insert_seq2spatial_plugin(self):
331
+ nSeqLen2SpatialPlugin = 0
332
+ for node in self.graph.nodes:
333
+ if node.op == "Transpose" and node.o().op == "Conv":
334
+ transposeNode = node
335
+ reshapeNode = node.i()
336
+ assert reshapeNode.op == "Reshape", "Unexpected node type for reshapeNode {}".format(reshapeNode.name)
337
+ residualNode = reshapeNode.i(0)
338
+ assert residualNode.op == "Add", "Unexpected node type for residualNode {}".format(residualNode.name)
339
+ biasNode = residualNode.i(0)
340
+ assert biasNode.op == "Add", "Unexpected node type for biasNode {}".format(biasNode.name)
341
+ biasIndex = [type(i) == gs.ir.tensor.Constant for i in biasNode.inputs].index(True)
342
+ bias = np.array(deepcopy(biasNode.inputs[biasIndex].values.tolist()), dtype=np.float32)
343
+ biasInput = gs.Constant("AddAddSeqLen2SpatialBias-" + str(nSeqLen2SpatialPlugin), np.ascontiguousarray(bias.reshape(-1)))
344
+ inputIndex = 1 - biasIndex
345
+ inputTensor = biasNode.inputs[inputIndex]
346
+ residualInput = residualNode.inputs[1]
347
+ outputTensor = transposeNode.outputs[0]
348
+ outputShapeTensor = transposeNode.i().i().i(1).i(1).i(1).i().inputs[0]
349
+ seqLen2SpatialNode = gs.Node("SeqLen2Spatial", "AddAddSeqLen2Spatial-" + str(nSeqLen2SpatialPlugin),
350
+ inputs=[inputTensor, biasInput, residualInput, outputShapeTensor], outputs=[outputTensor])
351
+ self.graph.nodes.append(seqLen2SpatialNode)
352
+ biasNode.inputs.clear()
353
+ transposeNode.outputs.clear()
354
+ nSeqLen2SpatialPlugin += 1
355
+
356
+ self.cleanup()
357
+ return nSeqLen2SpatialPlugin
358
+
359
+ def fuse_kv(self, node_k, node_v, fused_kv_idx, heads, num_dynamic=0):
360
+ # Get weights of K
361
+ weights_k = node_k.inputs[1].values
362
+ # Get weights of V
363
+ weights_v = node_v.inputs[1].values
364
+ # Input number of channels to K and V
365
+ C = weights_k.shape[0]
366
+ # Number of heads
367
+ H = heads
368
+ # Dimension per head
369
+ D = weights_k.shape[1] // H
370
+
371
+ # Concat and interleave weights such that the output of fused KV GEMM has [b, s_kv, h, 2, d] shape
372
+ weights_kv = np.dstack([weights_k.reshape(C, H, D), weights_v.reshape(C, H, D)]).reshape(C, 2 * H * D)
373
+
374
+ # K and V have the same input
375
+ input_tensor = node_k.inputs[0]
376
+ # K and V must have the same output which we feed into fmha plugin
377
+ output_tensor_k = node_k.outputs[0]
378
+ # Create tensor
379
+ constant_weights_kv = gs.Constant("Weights_KV_{}".format(fused_kv_idx), np.ascontiguousarray(weights_kv))
380
+
381
+ # Create fused KV node
382
+ fused_kv_node = gs.Node(op="MatMul", name="MatMul_KV_{}".format(fused_kv_idx), inputs=[input_tensor, constant_weights_kv], outputs=[output_tensor_k])
383
+ self.graph.nodes.append(fused_kv_node)
384
+
385
+ # Connect the output of fused node to the inputs of the nodes after K and V
386
+ node_v.o(num_dynamic).inputs[0] = output_tensor_k
387
+ node_k.o(num_dynamic).inputs[0] = output_tensor_k
388
+ for i in range(0,num_dynamic):
389
+ node_v.o().inputs.clear()
390
+ node_k.o().inputs.clear()
391
+
392
+ # Clear inputs and outputs of K and V to ge these nodes cleared
393
+ node_k.outputs.clear()
394
+ node_v.outputs.clear()
395
+ node_k.inputs.clear()
396
+ node_v.inputs.clear()
397
+
398
+ self.cleanup()
399
+ return fused_kv_node
400
+
401
+ def insert_fmhca(self, node_q, node_kv, final_tranpose, mhca_idx, heads, num_dynamic=0):
402
+ # Get inputs and outputs for the fMHCA plugin
403
+ # We take an output of reshape that follows the Q GEMM
404
+ output_q = node_q.o(num_dynamic).o().inputs[0]
405
+ output_kv = node_kv.o().inputs[0]
406
+ output_final_tranpose = final_tranpose.outputs[0]
407
+
408
+ # Clear the inputs of the nodes that follow the Q and KV GEMM
409
+ # to delete these subgraphs (it will be substituted by fMHCA plugin)
410
+ node_kv.outputs[0].outputs[0].inputs.clear()
411
+ node_kv.outputs[0].outputs[0].inputs.clear()
412
+ node_q.o(num_dynamic).o().inputs.clear()
413
+ for i in range(0,num_dynamic):
414
+ node_q.o(i).o().o(1).inputs.clear()
415
+
416
+ weights_kv = node_kv.inputs[1].values
417
+ dims_per_head = weights_kv.shape[1] // (heads * 2)
418
+
419
+ # Reshape dims
420
+ shape = gs.Constant("Shape_KV_{}".format(mhca_idx), np.ascontiguousarray(np.array([0, 0, heads, 2, dims_per_head], dtype=np.int64)))
421
+
422
+ # Reshape output tensor
423
+ output_reshape = gs.Variable("ReshapeKV_{}".format(mhca_idx), np.dtype(np.float16), None)
424
+ # Create fMHA plugin
425
+ reshape = gs.Node(op="Reshape", name="Reshape_{}".format(mhca_idx), inputs=[output_kv, shape], outputs=[output_reshape])
426
+ # Insert node
427
+ self.graph.nodes.append(reshape)
428
+
429
+ # Create fMHCA plugin
430
+ fmhca = gs.Node(op="fMHCA", name="fMHCA_{}".format(mhca_idx), inputs=[output_q, output_reshape], outputs=[output_final_tranpose])
431
+ # Insert node
432
+ self.graph.nodes.append(fmhca)
433
+
434
+ # Connect input of fMHCA to output of Q GEMM
435
+ node_q.o(num_dynamic).outputs[0] = output_q
436
+
437
+ if num_dynamic > 0:
438
+ reshape2_input1_out = gs.Variable("Reshape2_fmhca{}_out".format(mhca_idx), np.dtype(np.int64), None)
439
+ reshape2_input1_shape = gs.Node("Shape", "Reshape2_fmhca{}_shape".format(mhca_idx), inputs=[node_q.inputs[0]], outputs=[reshape2_input1_out])
440
+ self.graph.nodes.append(reshape2_input1_shape)
441
+ final_tranpose.o().inputs[1] = reshape2_input1_out
442
+
443
+ # Clear outputs of transpose to get this subgraph cleared
444
+ final_tranpose.outputs.clear()
445
+
446
+ self.cleanup()
447
+
448
+ def fuse_qkv(self, node_q, node_k, node_v, fused_qkv_idx, heads, num_dynamic=0):
449
+ # Get weights of Q
450
+ weights_q = node_q.inputs[1].values
451
+ # Get weights of K
452
+ weights_k = node_k.inputs[1].values
453
+ # Get weights of V
454
+ weights_v = node_v.inputs[1].values
455
+
456
+ # Input number of channels to Q, K and V
457
+ C = weights_k.shape[0]
458
+ # Number of heads
459
+ H = heads
460
+ # Hidden dimension per head
461
+ D = weights_k.shape[1] // H
462
+
463
+ # Concat and interleave weights such that the output of fused QKV GEMM has [b, s, h, 3, d] shape
464
+ weights_qkv = np.dstack([weights_q.reshape(C, H, D), weights_k.reshape(C, H, D), weights_v.reshape(C, H, D)]).reshape(C, 3 * H * D)
465
+
466
+ input_tensor = node_k.inputs[0] # K and V have the same input
467
+ # Q, K and V must have the same output which we feed into fmha plugin
468
+ output_tensor_k = node_k.outputs[0]
469
+ # Concat and interleave weights such that the output of fused QKV GEMM has [b, s, h, 3, d] shape
470
+ constant_weights_qkv = gs.Constant("Weights_QKV_{}".format(fused_qkv_idx), np.ascontiguousarray(weights_qkv))
471
+
472
+ # Created a fused node
473
+ fused_qkv_node = gs.Node(op="MatMul", name="MatMul_QKV_{}".format(fused_qkv_idx), inputs=[input_tensor, constant_weights_qkv], outputs=[output_tensor_k])
474
+ self.graph.nodes.append(fused_qkv_node)
475
+
476
+ # Connect the output of the fused node to the inputs of the nodes after Q, K and V
477
+ node_q.o(num_dynamic).inputs[0] = output_tensor_k
478
+ node_k.o(num_dynamic).inputs[0] = output_tensor_k
479
+ node_v.o(num_dynamic).inputs[0] = output_tensor_k
480
+ for i in range(0,num_dynamic):
481
+ node_q.o().inputs.clear()
482
+ node_k.o().inputs.clear()
483
+ node_v.o().inputs.clear()
484
+
485
+ # Clear inputs and outputs of Q, K and V to ge these nodes cleared
486
+ node_q.outputs.clear()
487
+ node_k.outputs.clear()
488
+ node_v.outputs.clear()
489
+
490
+ node_q.inputs.clear()
491
+ node_k.inputs.clear()
492
+ node_v.inputs.clear()
493
+
494
+ self.cleanup()
495
+ return fused_qkv_node
496
+
497
+ def insert_fmha(self, node_qkv, final_tranpose, mha_idx, heads, num_dynamic=0):
498
+ # Get inputs and outputs for the fMHA plugin
499
+ output_qkv = node_qkv.o().inputs[0]
500
+ output_final_tranpose = final_tranpose.outputs[0]
501
+
502
+ # Clear the inputs of the nodes that follow the QKV GEMM
503
+ # to delete these subgraphs (it will be substituted by fMHA plugin)
504
+ node_qkv.outputs[0].outputs[2].inputs.clear()
505
+ node_qkv.outputs[0].outputs[1].inputs.clear()
506
+ node_qkv.outputs[0].outputs[0].inputs.clear()
507
+
508
+ weights_qkv = node_qkv.inputs[1].values
509
+ dims_per_head = weights_qkv.shape[1] // (heads * 3)
510
+
511
+ # Reshape dims
512
+ shape = gs.Constant("Shape_QKV_{}".format(mha_idx), np.ascontiguousarray(np.array([0, 0, heads, 3, dims_per_head], dtype=np.int64)))
513
+
514
+ # Reshape output tensor
515
+ output_shape = gs.Variable("ReshapeQKV_{}".format(mha_idx), np.dtype(np.float16), None)
516
+ # Create fMHA plugin
517
+ reshape = gs.Node(op="Reshape", name="Reshape_{}".format(mha_idx), inputs=[output_qkv, shape], outputs=[output_shape])
518
+ # Insert node
519
+ self.graph.nodes.append(reshape)
520
+
521
+ # Create fMHA plugin
522
+ fmha = gs.Node(op="fMHA_V2", name="fMHA_{}".format(mha_idx), inputs=[output_shape], outputs=[output_final_tranpose])
523
+ # Insert node
524
+ self.graph.nodes.append(fmha)
525
+
526
+ if num_dynamic > 0:
527
+ reshape2_input1_out = gs.Variable("Reshape2_{}_out".format(mha_idx), np.dtype(np.int64), None)
528
+ reshape2_input1_shape = gs.Node("Shape", "Reshape2_{}_shape".format(mha_idx), inputs=[node_qkv.inputs[0]], outputs=[reshape2_input1_out])
529
+ self.graph.nodes.append(reshape2_input1_shape)
530
+ final_tranpose.o().inputs[1] = reshape2_input1_out
531
+
532
+ # Clear outputs of transpose to get this subgraph cleared
533
+ final_tranpose.outputs.clear()
534
+
535
+ self.cleanup()
536
+
537
+ def mha_mhca_detected(self, node, mha):
538
+ # Go from V GEMM down to the S*V MatMul and all way up to K GEMM
539
+ # If we are looking for MHCA inputs of two matmuls (K and V) must be equal.
540
+ # If we are looking for MHA inputs (K and V) must be not equal.
541
+ if node.op == "MatMul" and len(node.outputs) == 1 and \
542
+ ((mha and len(node.inputs[0].inputs) > 0 and node.i().op == "Add") or \
543
+ (not mha and len(node.inputs[0].inputs) == 0)):
544
+
545
+ if node.o().op == 'Shape':
546
+ if node.o(1).op == 'Shape':
547
+ num_dynamic_kv = 3 if node.o(2).op == 'Shape' else 2
548
+ else:
549
+ num_dynamic_kv = 1
550
+ # For Cross-Attention, if batch axis is dynamic (in QKV), assume H*W (in Q) is dynamic as well
551
+ num_dynamic_q = num_dynamic_kv if mha else num_dynamic_kv + 1
552
+ else:
553
+ num_dynamic_kv = 0
554
+ num_dynamic_q = 0
555
+
556
+ o = node.o(num_dynamic_kv)
557
+ if o.op == "Reshape" and \
558
+ o.o().op == "Transpose" and \
559
+ o.o().o().op == "Reshape" and \
560
+ o.o().o().o().op == "MatMul" and \
561
+ o.o().o().o().i(0).op == "Softmax" and \
562
+ o.o().o().o().i(1).op == "Reshape" and \
563
+ o.o().o().o().i(0).i().op == "Mul" and \
564
+ o.o().o().o().i(0).i().i().op == "MatMul" and \
565
+ o.o().o().o().i(0).i().i().i(0).op == "Reshape" and \
566
+ o.o().o().o().i(0).i().i().i(1).op == "Transpose" and \
567
+ o.o().o().o().i(0).i().i().i(1).i().op == "Reshape" and \
568
+ o.o().o().o().i(0).i().i().i(1).i().i().op == "Transpose" and \
569
+ o.o().o().o().i(0).i().i().i(1).i().i().i().op == "Reshape" and \
570
+ o.o().o().o().i(0).i().i().i(1).i().i().i().i().op == "MatMul" and \
571
+ node.name != o.o().o().o().i(0).i().i().i(1).i().i().i().i().name:
572
+ # "len(node.outputs) == 1" to make sure we are not in the already fused node
573
+ node_q = o.o().o().o().i(0).i().i().i(0).i().i().i()
574
+ node_k = o.o().o().o().i(0).i().i().i(1).i().i().i().i()
575
+ node_v = node
576
+ final_tranpose = o.o().o().o().o(num_dynamic_q).o()
577
+ # Sanity check to make sure that the graph looks like expected
578
+ if node_q.op == "MatMul" and final_tranpose.op == "Transpose":
579
+ return True, num_dynamic_q, num_dynamic_kv, node_q, node_k, node_v, final_tranpose
580
+ return False, 0, 0, None, None, None, None
581
+
582
+ def fuse_kv_insert_fmhca(self, heads, mhca_index, sm):
583
+ nodes = self.graph.nodes
584
+ # Iterate over graph and search for MHCA pattern
585
+ for idx, _ in enumerate(nodes):
586
+ # fMHCA can't be at the 2 last layers of the network. It is a guard from OOB
587
+ if idx + 1 > len(nodes) or idx + 2 > len(nodes):
588
+ continue
589
+
590
+ # Get anchor nodes for fusion and fMHCA plugin insertion if the MHCA is detected
591
+ detected, num_dynamic_q, num_dynamic_kv, node_q, node_k, node_v, final_tranpose = \
592
+ self.mha_mhca_detected(nodes[idx], mha=False)
593
+ if detected:
594
+ assert num_dynamic_q == 0 or num_dynamic_q == num_dynamic_kv + 1
595
+ # Skip the FMHCA plugin for SM75 except for when the dim per head is 40.
596
+ if sm == 75 and node_q.inputs[1].shape[1] // heads == 160:
597
+ continue
598
+ # Fuse K and V GEMMS
599
+ node_kv = self.fuse_kv(node_k, node_v, mhca_index, heads, num_dynamic_kv)
600
+ # Insert fMHCA plugin
601
+ self.insert_fmhca(node_q, node_kv, final_tranpose, mhca_index, heads, num_dynamic_q)
602
+ return True
603
+ return False
604
+
605
+ def fuse_qkv_insert_fmha(self, heads, mha_index):
606
+ nodes = self.graph.nodes
607
+ # Iterate over graph and search for MHA pattern
608
+ for idx, _ in enumerate(nodes):
609
+ # fMHA can't be at the 2 last layers of the network. It is a guard from OOB
610
+ if idx + 1 > len(nodes) or idx + 2 > len(nodes):
611
+ continue
612
+
613
+ # Get anchor nodes for fusion and fMHA plugin insertion if the MHA is detected
614
+ detected, num_dynamic_q, num_dynamic_kv, node_q, node_k, node_v, final_tranpose = \
615
+ self.mha_mhca_detected(nodes[idx], mha=True)
616
+ if detected:
617
+ assert num_dynamic_q == num_dynamic_kv
618
+ # Fuse Q, K and V GEMMS
619
+ node_qkv = self.fuse_qkv(node_q, node_k, node_v, mha_index, heads, num_dynamic_kv)
620
+ # Insert fMHA plugin
621
+ self.insert_fmha(node_qkv, final_tranpose, mha_index, heads, num_dynamic_kv)
622
+ return True
623
+ return False
624
+
625
+ def insert_fmhca_plugin(self, num_heads, sm):
626
+ mhca_index = 0
627
+ while self.fuse_kv_insert_fmhca(num_heads, mhca_index, sm):
628
+ mhca_index += 1
629
+ return mhca_index
630
+
631
+ def insert_fmha_plugin(self, num_heads):
632
+ mha_index = 0
633
+ while self.fuse_qkv_insert_fmha(num_heads, mha_index):
634
+ mha_index += 1
635
+ return mha_index
636
+
637
+ class BaseModel():
638
+ def __init__(
639
+ self,
640
+ hf_token,
641
+ text_maxlen=77,
642
+ embedding_dim=768,
643
+ fp16=False,
644
+ device='cuda',
645
+ verbose=True,
646
+ max_batch_size=16
647
+ ):
648
+ self.fp16 = fp16
649
+ self.device = device
650
+ self.verbose = verbose
651
+ self.hf_token = hf_token
652
+
653
+ # Defaults
654
+ self.text_maxlen = text_maxlen
655
+ self.embedding_dim = embedding_dim
656
+ self.min_batch = 1
657
+ self.max_batch = max_batch_size
658
+ self.min_latent_shape = 256 // 8 # min image resolution: 256x256
659
+ self.max_latent_shape = 1024 // 8 # max image resolution: 1024x1024
660
+
661
+ def get_model(self):
662
+ pass
663
+
664
+ def get_input_names(self):
665
+ pass
666
+
667
+ def get_output_names(self):
668
+ pass
669
+
670
+ def get_dynamic_axes(self):
671
+ return None
672
+
673
+ def get_sample_input(self, batch_size, image_height, image_width):
674
+ pass
675
+
676
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
677
+ return None
678
+
679
+ def get_shape_dict(self, batch_size, image_height, image_width):
680
+ return None
681
+
682
+ def optimize(self, onnx_graph, minimal_optimization=False):
683
+ return onnx_graph
684
+
685
+ def check_dims(self, batch_size, image_height, image_width):
686
+ assert batch_size >= self.min_batch and batch_size <= self.max_batch
687
+ assert image_height % 8 == 0 or image_width % 8 == 0
688
+ latent_height = image_height // 8
689
+ latent_width = image_width // 8
690
+ assert latent_height >= self.min_latent_shape and latent_height <= self.max_latent_shape
691
+ assert latent_width >= self.min_latent_shape and latent_width <= self.max_latent_shape
692
+ return (latent_height, latent_width)
693
+
694
+ def get_minmax_dims(self, batch_size, image_height, image_width, static_batch, static_shape):
695
+ min_batch = batch_size if static_batch else self.min_batch
696
+ max_batch = batch_size if static_batch else self.max_batch
697
+ latent_height = image_height // 8
698
+ latent_width = image_width // 8
699
+ min_latent_height = latent_height if static_shape else self.min_latent_shape
700
+ max_latent_height = latent_height if static_shape else self.max_latent_shape
701
+ min_latent_width = latent_width if static_shape else self.min_latent_shape
702
+ max_latent_width = latent_width if static_shape else self.max_latent_shape
703
+ return (min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width)
704
+
705
+ class CLIP(BaseModel):
706
+ def get_model(self):
707
+ return CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").to(self.device)
708
+
709
+ def get_input_names(self):
710
+ return ['input_ids']
711
+
712
+ def get_output_names(self):
713
+ return ['text_embeddings', 'pooler_output']
714
+
715
+ def get_dynamic_axes(self):
716
+ return {
717
+ 'input_ids': {0: 'B'},
718
+ 'text_embeddings': {0: 'B'}
719
+ }
720
+
721
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
722
+ self.check_dims(batch_size, image_height, image_width)
723
+ min_batch, max_batch, _, _, _, _ = self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
724
+ return {
725
+ 'input_ids': [(min_batch, self.text_maxlen), (batch_size, self.text_maxlen), (max_batch, self.text_maxlen)]
726
+ }
727
+
728
+ def get_shape_dict(self, batch_size, image_height, image_width):
729
+ self.check_dims(batch_size, image_height, image_width)
730
+ return {
731
+ 'input_ids': (batch_size, self.text_maxlen),
732
+ 'text_embeddings': (batch_size, self.text_maxlen, self.embedding_dim)
733
+ }
734
+
735
+ def get_sample_input(self, batch_size, image_height, image_width):
736
+ self.check_dims(batch_size, image_height, image_width)
737
+ return torch.zeros(batch_size, self.text_maxlen, dtype=torch.int32, device=self.device)
738
+
739
+ def optimize(self, onnx_graph, minimal_optimization=False):
740
+ enable_optimization = not minimal_optimization
741
+
742
+ # Remove Cast Node to optimize Attention block
743
+ bRemoveCastNode = enable_optimization
744
+ # Insert LayerNormalization Plugin
745
+ bLayerNormPlugin = enable_optimization
746
+
747
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
748
+ opt.info('CLIP: original')
749
+ opt.select_outputs([0]) # delete graph output#1
750
+ opt.cleanup()
751
+ opt.info('CLIP: remove output[1]')
752
+ opt.fold_constants()
753
+ opt.info('CLIP: fold constants')
754
+ opt.infer_shapes()
755
+ opt.info('CLIP: shape inference')
756
+
757
+ if bRemoveCastNode:
758
+ num_casts_removed = opt.remove_casts()
759
+ opt.info('CLIP: removed '+str(num_casts_removed)+' casts')
760
+
761
+ if bLayerNormPlugin:
762
+ num_layernorm_inserted = opt.insert_layernorm_plugin()
763
+ opt.info('CLIP: inserted '+str(num_layernorm_inserted)+' LayerNorm plugins')
764
+
765
+ opt.select_outputs([0], names=['text_embeddings']) # rename network output
766
+ opt_onnx_graph = opt.cleanup(return_onnx=True)
767
+ opt.info('CLIP: final')
768
+ return opt_onnx_graph
769
+
770
+ class UNet(BaseModel):
771
+ def get_model(self):
772
+ model_opts = {'revision': 'fp16', 'torch_dtype': torch.float16} if self.fp16 else {}
773
+ return UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4",
774
+ subfolder="unet",
775
+ use_auth_token=self.hf_token,
776
+ **model_opts).to(self.device)
777
+
778
+ def get_input_names(self):
779
+ return ['sample', 'timestep', 'encoder_hidden_states']
780
+
781
+ def get_output_names(self):
782
+ return ['latent']
783
+
784
+ def get_dynamic_axes(self):
785
+ return {
786
+ 'sample': {0: '2B', 2: 'H', 3: 'W'},
787
+ 'encoder_hidden_states': {0: '2B'},
788
+ 'latent': {0: '2B', 2: 'H', 3: 'W'}
789
+ }
790
+
791
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
792
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
793
+ min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width = \
794
+ self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
795
+ return {
796
+ '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)],
797
+ '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)]
798
+ }
799
+
800
+ def get_shape_dict(self, batch_size, image_height, image_width):
801
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
802
+ return {
803
+ 'sample': (2*batch_size, 4, latent_height, latent_width),
804
+ 'encoder_hidden_states': (2*batch_size, self.text_maxlen, self.embedding_dim),
805
+ 'latent': (2*batch_size, 4, latent_height, latent_width)
806
+ }
807
+
808
+ def get_sample_input(self, batch_size, image_height, image_width):
809
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
810
+ dtype = torch.float16 if self.fp16 else torch.float32
811
+ return (
812
+ torch.randn(2*batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device),
813
+ torch.tensor([1.], dtype=torch.float32, device=self.device),
814
+ torch.randn(2*batch_size, self.text_maxlen, self.embedding_dim, dtype=dtype, device=self.device)
815
+ )
816
+
817
+ def optimize(self, onnx_graph, minimal_optimization=False):
818
+ enable_optimization = not minimal_optimization
819
+
820
+ # Decompose InstanceNormalization into primitive Ops
821
+ bRemoveInstanceNorm = enable_optimization
822
+ # Remove Cast Node to optimize Attention block
823
+ bRemoveCastNode = enable_optimization
824
+ # Remove parallel Swish ops
825
+ bRemoveParallelSwish = enable_optimization
826
+ # Adjust the bias to be the second input to the Add ops
827
+ bAdjustAddNode = enable_optimization
828
+ # Change Resize node to take size instead of scale
829
+ bResizeFix = enable_optimization
830
+
831
+ # Common override for disabling all plugins below
832
+ bDisablePlugins = minimal_optimization
833
+ # Use multi-head attention Plugin
834
+ bMHAPlugin = True
835
+ # Use multi-head cross attention Plugin
836
+ bMHCAPlugin = True
837
+ # Insert GroupNormalization Plugin
838
+ bGroupNormPlugin = True
839
+ # Insert LayerNormalization Plugin
840
+ bLayerNormPlugin = True
841
+ # Insert Split+GeLU Plugin
842
+ bSplitGeLUPlugin = True
843
+ # Replace BiasAdd+ResidualAdd+SeqLen2Spatial with plugin
844
+ bSeqLen2SpatialPlugin = True
845
+
846
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
847
+ opt.info('UNet: original')
848
+
849
+ if bRemoveInstanceNorm:
850
+ num_instancenorm_replaced = opt.decompose_instancenorms()
851
+ opt.info('UNet: replaced '+str(num_instancenorm_replaced)+' InstanceNorms')
852
+
853
+ if bRemoveCastNode:
854
+ num_casts_removed = opt.remove_casts()
855
+ opt.info('UNet: removed '+str(num_casts_removed)+' casts')
856
+
857
+ if bRemoveParallelSwish:
858
+ num_parallel_swish_removed = opt.remove_parallel_swish()
859
+ opt.info('UNet: removed '+str(num_parallel_swish_removed)+' parallel swish ops')
860
+
861
+ if bAdjustAddNode:
862
+ num_adjust_add = opt.adjustAddNode()
863
+ opt.info('UNet: adjusted '+str(num_adjust_add)+' adds')
864
+
865
+ if bResizeFix:
866
+ num_resize_fix = opt.resize_fix()
867
+ opt.info('UNet: fixed '+str(num_resize_fix)+' resizes')
868
+
869
+ opt.cleanup()
870
+ opt.info('UNet: cleanup')
871
+ opt.fold_constants()
872
+ opt.info('UNet: fold constants')
873
+ opt.infer_shapes()
874
+ opt.info('UNet: shape inference')
875
+
876
+ num_heads = 8
877
+ if bMHAPlugin and not bDisablePlugins:
878
+ num_fmha_inserted = opt.insert_fmha_plugin(num_heads)
879
+ opt.info('UNet: inserted '+str(num_fmha_inserted)+' fMHA plugins')
880
+
881
+ if bMHCAPlugin and not bDisablePlugins:
882
+ props = cudart.cudaGetDeviceProperties(0)[1]
883
+ sm = props.major * 10 + props.minor
884
+ num_fmhca_inserted = opt.insert_fmhca_plugin(num_heads, sm)
885
+ opt.info('UNet: inserted '+str(num_fmhca_inserted)+' fMHCA plugins')
886
+
887
+ if bGroupNormPlugin and not bDisablePlugins:
888
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
889
+ opt.info('UNet: inserted '+str(num_groupnorm_inserted)+' GroupNorm plugins')
890
+
891
+ if bLayerNormPlugin and not bDisablePlugins:
892
+ num_layernorm_inserted = opt.insert_layernorm_plugin()
893
+ opt.info('UNet: inserted '+str(num_layernorm_inserted)+' LayerNorm plugins')
894
+
895
+ if bSplitGeLUPlugin and not bDisablePlugins:
896
+ num_splitgelu_inserted = opt.insert_splitgelu_plugin()
897
+ opt.info('UNet: inserted '+str(num_splitgelu_inserted)+' SplitGeLU plugins')
898
+
899
+ if bSeqLen2SpatialPlugin and not bDisablePlugins:
900
+ num_seq2spatial_inserted = opt.insert_seq2spatial_plugin()
901
+ opt.info('UNet: inserted '+str(num_seq2spatial_inserted)+' SeqLen2Spatial plugins')
902
+
903
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
904
+ opt.info('UNet: final')
905
+ return onnx_opt_graph
906
+
907
+ class VAE(BaseModel):
908
+ def get_model(self):
909
+ vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4",
910
+ subfolder="vae",
911
+ use_auth_token=self.hf_token).to(self.device)
912
+ vae.forward = vae.decode
913
+ return vae
914
+
915
+ def get_input_names(self):
916
+ return ['latent']
917
+
918
+ def get_output_names(self):
919
+ return ['images']
920
+
921
+ def get_dynamic_axes(self):
922
+ return {
923
+ 'latent': {0: 'B', 2: 'H', 3: 'W'},
924
+ 'images': {0: 'B', 2: '8H', 3: '8W'}
925
+ }
926
+
927
+ def get_input_profile(self, batch_size, image_height, image_width, static_batch, static_shape):
928
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
929
+ min_batch, max_batch, min_latent_height, max_latent_height, min_latent_width, max_latent_width = \
930
+ self.get_minmax_dims(batch_size, image_height, image_width, static_batch, static_shape)
931
+ return {
932
+ '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)]
933
+ }
934
+
935
+ def get_shape_dict(self, batch_size, image_height, image_width):
936
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
937
+ return {
938
+ 'latent': (batch_size, 4, latent_height, latent_width),
939
+ 'images': (batch_size, 3, image_height, image_width)
940
+ }
941
+
942
+ def get_sample_input(self, batch_size, image_height, image_width):
943
+ latent_height, latent_width = self.check_dims(batch_size, image_height, image_width)
944
+ return torch.randn(batch_size, 4, latent_height, latent_width, dtype=torch.float32, device=self.device)
945
+
946
+ def optimize(self, onnx_graph, minimal_optimization=False):
947
+ enable_optimization = not minimal_optimization
948
+
949
+ # Decompose InstanceNormalization into primitive Ops
950
+ bRemoveInstanceNorm = enable_optimization
951
+ # Remove Cast Node to optimize Attention block
952
+ bRemoveCastNode = enable_optimization
953
+ # Insert GroupNormalization Plugin
954
+ bGroupNormPlugin = enable_optimization
955
+
956
+ opt = Optimizer(onnx_graph, verbose=self.verbose)
957
+ opt.info('VAE: original')
958
+
959
+ if bRemoveInstanceNorm:
960
+ num_instancenorm_replaced = opt.decompose_instancenorms()
961
+ opt.info('VAE: replaced '+str(num_instancenorm_replaced)+' InstanceNorms')
962
+
963
+ if bRemoveCastNode:
964
+ num_casts_removed = opt.remove_casts()
965
+ opt.info('VAE: removed '+str(num_casts_removed)+' casts')
966
+
967
+ opt.cleanup()
968
+ opt.info('VAE: cleanup')
969
+ opt.fold_constants()
970
+ opt.info('VAE: fold constants')
971
+ opt.infer_shapes()
972
+ opt.info('VAE: shape inference')
973
+
974
+ if bGroupNormPlugin:
975
+ num_groupnorm_inserted = opt.insert_groupnorm_plugin()
976
+ opt.info('VAE: inserted '+str(num_groupnorm_inserted)+' GroupNorm plugins')
977
+
978
+ onnx_opt_graph = opt.cleanup(return_onnx=True)
979
+ opt.info('VAE: final')
980
+ return onnx_opt_graph
onnx/clip.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f07f42f288698f966fb8f35f42cab2f2e2454bcbb68baee9e57280b7686e3ace
3
+ size 322361500
onnx/clip.opt.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa2c5bb7df8c93150f9c962d9af8fd992fba3d3302697f1eee7bb442472be3f5
3
+ size 322335606
onnx/unet_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01773c0d9f04889be77e7165388a72fce12033d019150cb036f1e5d8b21c91ba
3
+ size 1720130667
onnx/unet_fp16.opt.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b541324a30e9b8f25c777f315aedac2ef3078dc782287e3df8bf074ba822cb21
3
+ size 1719727102
onnx/vae.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:706de829e4ead501ec0357d98e42fdd515abaf10b6a9e985f498d88e5657b573
3
+ size 99088306
onnx/vae.opt.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c0a60a41554cf0fde832dd7494c8fb7b4485e8fecda8656c3678d5d57b97aa2
3
+ size 99061557
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ colored
2
+ cuda-python
3
+ diffusers==0.7.2
4
+ ftfy
5
+ matplotlib
6
+ nvtx
7
+ onnx==1.12.0
8
+ --extra-index-url https://pypi.ngc.nvidia.com
9
+ onnx-graphsurgeon==0.3.25
10
+ onnxruntime==1.13.1
11
+ polygraphy==0.43.1
12
+ scipy
13
+ --extra-index-url https://download.pytorch.org/whl/cu116
14
+ torch==1.12.0+cu116
15
+ transformers==4.24.0
utilities.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Copyright 2022 The HuggingFace Inc. team.
3
+ # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ from collections import OrderedDict
20
+ from copy import copy
21
+ import numpy as np
22
+ import os
23
+ import math
24
+ from PIL import Image
25
+ from polygraphy.backend.common import bytes_from_path
26
+ from polygraphy.backend.trt import CreateConfig, Profile
27
+ from polygraphy.backend.trt import engine_from_bytes, engine_from_network, network_from_onnx_path, save_engine
28
+ from polygraphy.backend.trt import util as trt_util
29
+ from polygraphy import cuda
30
+ import random
31
+ from scipy import integrate
32
+ import tensorrt as trt
33
+ import torch
34
+
35
+ TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
36
+
37
+ class Engine():
38
+ def __init__(
39
+ self,
40
+ model_name,
41
+ engine_dir,
42
+ ):
43
+ self.engine_path = os.path.join(engine_dir, model_name+'.plan')
44
+ self.engine = None
45
+ self.context = None
46
+ self.buffers = OrderedDict()
47
+ self.tensors = OrderedDict()
48
+
49
+ def __del__(self):
50
+ [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray) ]
51
+ del self.engine
52
+ del self.context
53
+ del self.buffers
54
+ del self.tensors
55
+
56
+ def build(self, onnx_path, fp16, input_profile=None, enable_preview=False):
57
+ print(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
58
+ p = Profile()
59
+ if input_profile:
60
+ for name, dims in input_profile.items():
61
+ assert len(dims) == 3
62
+ p.add(name, min=dims[0], opt=dims[1], max=dims[2])
63
+
64
+ preview_features = []
65
+ if enable_preview:
66
+ trt_version = [int(i) for i in trt.__version__.split(".")]
67
+ # FASTER_DYNAMIC_SHAPES_0805 should only be used for TRT 8.5.1 or above.
68
+ if trt_version[0] > 8 or \
69
+ (trt_version[0] == 8 and (trt_version[1] > 5 or (trt_version[1] == 5 and trt_version[2] >= 1))):
70
+ preview_features = [trt.PreviewFeature.FASTER_DYNAMIC_SHAPES_0805]
71
+
72
+ engine = engine_from_network(network_from_onnx_path(onnx_path), config=CreateConfig(fp16=fp16, profiles=[p],
73
+ preview_features=preview_features))
74
+ save_engine(engine, path=self.engine_path)
75
+
76
+ def activate(self):
77
+ print(f"Loading TensorRT engine: {self.engine_path}")
78
+ self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
79
+ self.context = self.engine.create_execution_context()
80
+
81
+ def allocate_buffers(self, shape_dict=None, device='cuda'):
82
+ for idx in range(trt_util.get_bindings_per_profile(self.engine)):
83
+ binding = self.engine[idx]
84
+ if shape_dict and binding in shape_dict:
85
+ shape = shape_dict[binding]
86
+ else:
87
+ shape = self.engine.get_binding_shape(binding)
88
+ dtype = trt_util.np_dtype_from_trt(self.engine.get_binding_dtype(binding))
89
+ if self.engine.binding_is_input(binding):
90
+ self.context.set_binding_shape(idx, shape)
91
+ # Workaround to convert np dtype to torch
92
+ np_type_tensor = np.empty(shape=[], dtype=dtype)
93
+ torch_type_tensor = torch.from_numpy(np_type_tensor)
94
+ tensor = torch.empty(tuple(shape), dtype=torch_type_tensor.dtype).to(device=device)
95
+ self.tensors[binding] = tensor
96
+ self.buffers[binding] = cuda.DeviceView(ptr=tensor.data_ptr(), shape=shape, dtype=dtype)
97
+
98
+ def infer(self, feed_dict, stream):
99
+ start_binding, end_binding = trt_util.get_active_profile_bindings(self.context)
100
+ # shallow copy of ordered dict
101
+ device_buffers = copy(self.buffers)
102
+ for name, buf in feed_dict.items():
103
+ assert isinstance(buf, cuda.DeviceView)
104
+ device_buffers[name] = buf
105
+ bindings = [0] * start_binding + [buf.ptr for buf in device_buffers.values()]
106
+ noerror = self.context.execute_async_v2(bindings=bindings, stream_handle=stream.ptr)
107
+ if not noerror:
108
+ raise ValueError(f"ERROR: inference failed.")
109
+
110
+ return self.tensors
111
+
112
+ class LMSDiscreteScheduler():
113
+ def __init__(
114
+ self,
115
+ device = 'cuda',
116
+ beta_start = 0.00085,
117
+ beta_end = 0.012,
118
+ num_train_timesteps = 1000,
119
+ ):
120
+ self.num_train_timesteps = num_train_timesteps
121
+ self.order = 4
122
+
123
+ self.beta_start = beta_start
124
+ self.beta_end = beta_end
125
+ betas = (torch.linspace(beta_start**0.5, beta_end**0.5, self.num_train_timesteps, dtype=torch.float32) ** 2)
126
+ alphas = 1.0 - betas
127
+ self.alphas_cumprod = torch.cumprod(alphas, dim=0)
128
+
129
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
130
+ sigmas = np.concatenate([sigmas[::-1], [0.0]]).astype(np.float32)
131
+ self.sigmas = torch.from_numpy(sigmas)
132
+
133
+ # standard deviation of the initial noise distribution
134
+ self.init_noise_sigma = self.sigmas.max()
135
+
136
+ self.device = device
137
+
138
+ def set_timesteps(self, steps):
139
+ self.num_inference_steps = steps
140
+
141
+ timesteps = np.linspace(0, self.num_train_timesteps - 1, steps, dtype=float)[::-1].copy()
142
+ sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
143
+ sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
144
+ sigmas = np.concatenate([sigmas, [0.0]]).astype(np.float32)
145
+ self.sigmas = torch.from_numpy(sigmas).to(device=self.device)
146
+
147
+ # Move all timesteps to correct device beforehand
148
+ self.timesteps = torch.from_numpy(timesteps).to(device=self.device).float()
149
+ self.derivatives = []
150
+
151
+ def scale_model_input(self, sample: torch.FloatTensor, idx, *args, **kwargs) -> torch.FloatTensor:
152
+ return sample * self.latent_scales[idx]
153
+
154
+ def configure(self):
155
+ order = self.order
156
+ self.lms_coeffs = []
157
+ self.latent_scales = [1./((sigma**2 + 1) ** 0.5) for sigma in self.sigmas]
158
+
159
+ def get_lms_coefficient(order, t, current_order):
160
+ """
161
+ Compute a linear multistep coefficient.
162
+ """
163
+ def lms_derivative(tau):
164
+ prod = 1.0
165
+ for k in range(order):
166
+ if current_order == k:
167
+ continue
168
+ prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
169
+ return prod
170
+ integrated_coeff = integrate.quad(lms_derivative, self.sigmas[t], self.sigmas[t + 1], epsrel=1e-4)[0]
171
+ return integrated_coeff
172
+
173
+ for step_index in range(self.num_inference_steps):
174
+ order = min(step_index + 1, order)
175
+ self.lms_coeffs.append([get_lms_coefficient(order, step_index, curr_order) for curr_order in range(order)])
176
+
177
+ def step(self, output, latents, idx, timestep):
178
+ # compute the previous noisy sample x_t -> x_t-1
179
+ # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
180
+ sigma = self.sigmas[idx]
181
+ pred_original_sample = latents - sigma * output
182
+ # 2. Convert to an ODE derivative
183
+ derivative = (latents - pred_original_sample) / sigma
184
+ self.derivatives.append(derivative)
185
+ if len(self.derivatives) > self.order:
186
+ self.derivatives.pop(0)
187
+ # 3. Compute previous sample based on the derivatives path
188
+ prev_sample = latents + sum(
189
+ coeff * derivative for coeff, derivative in zip(self.lms_coeffs[idx], reversed(self.derivatives))
190
+ )
191
+
192
+ return prev_sample
193
+
194
+ class DPMScheduler():
195
+ def __init__(
196
+ self,
197
+ beta_start = 0.00085,
198
+ beta_end = 0.012,
199
+ num_train_timesteps = 1000,
200
+ solver_order = 2,
201
+ predict_epsilon = True,
202
+ thresholding = False,
203
+ dynamic_thresholding_ratio = 0.995,
204
+ sample_max_value = 1.0,
205
+ algorithm_type = "dpmsolver++",
206
+ solver_type = "midpoint",
207
+ lower_order_final = True,
208
+ device = 'cuda',
209
+ ):
210
+ # this schedule is very specific to the latent diffusion model.
211
+ self.betas = (
212
+ torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
213
+ )
214
+
215
+ self.device = device
216
+ self.alphas = 1.0 - self.betas
217
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
218
+ # Currently we only support VP-type noise schedule
219
+ self.alpha_t = torch.sqrt(self.alphas_cumprod)
220
+ self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
221
+ self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t)
222
+
223
+ # standard deviation of the initial noise distribution
224
+ self.init_noise_sigma = 1.0
225
+
226
+ self.algorithm_type = algorithm_type
227
+ self.predict_epsilon = predict_epsilon
228
+ self.thresholding = thresholding
229
+ self.dynamic_thresholding_ratio = dynamic_thresholding_ratio
230
+ self.sample_max_value = sample_max_value
231
+ self.lower_order_final = lower_order_final
232
+
233
+ # settings for DPM-Solver
234
+ if algorithm_type not in ["dpmsolver", "dpmsolver++"]:
235
+ raise NotImplementedError(f"{algorithm_type} does is not implemented for {self.__class__}")
236
+ if solver_type not in ["midpoint", "heun"]:
237
+ raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}")
238
+
239
+ # setable values
240
+ self.num_inference_steps = None
241
+ self.solver_order = solver_order
242
+ self.num_train_timesteps = num_train_timesteps
243
+ self.solver_type = solver_type
244
+
245
+ self.first_order_first_coef = []
246
+ self.first_order_second_coef = []
247
+
248
+ self.second_order_first_coef = []
249
+ self.second_order_second_coef = []
250
+ self.second_order_third_coef = []
251
+
252
+ self.third_order_first_coef = []
253
+ self.third_order_second_coef = []
254
+ self.third_order_third_coef = []
255
+ self.third_order_fourth_coef = []
256
+
257
+ def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
258
+ return sample
259
+
260
+ def configure(self):
261
+ lower_order_nums = 0
262
+ for step_index in range(self.num_inference_steps):
263
+ step_idx = step_index
264
+ timestep = self.timesteps[step_idx]
265
+
266
+ prev_timestep = 0 if step_idx == len(self.timesteps) - 1 else self.timesteps[step_idx + 1]
267
+
268
+ self.dpm_solver_first_order_coefs_precompute(timestep, prev_timestep)
269
+
270
+ timestep_list = [self.timesteps[step_index - 1], timestep]
271
+ self.multistep_dpm_solver_second_order_coefs_precompute(timestep_list, prev_timestep)
272
+
273
+ timestep_list = [self.timesteps[step_index - 2], self.timesteps[step_index - 1], timestep]
274
+ self.multistep_dpm_solver_third_order_coefs_precompute(timestep_list, prev_timestep)
275
+
276
+ if lower_order_nums < self.solver_order:
277
+ lower_order_nums += 1
278
+
279
+ def dpm_solver_first_order_coefs_precompute(self, timestep, prev_timestep):
280
+ lambda_t, lambda_s = self.lambda_t[prev_timestep], self.lambda_t[timestep]
281
+ alpha_t, alpha_s = self.alpha_t[prev_timestep], self.alpha_t[timestep]
282
+ sigma_t, sigma_s = self.sigma_t[prev_timestep], self.sigma_t[timestep]
283
+ h = lambda_t - lambda_s
284
+ if self.algorithm_type == "dpmsolver++":
285
+ self.first_order_first_coef.append(sigma_t / sigma_s)
286
+ self.first_order_second_coef.append(alpha_t * (torch.exp(-h) - 1.0))
287
+ elif self.algorithm_type == "dpmsolver":
288
+ self.first_order_first_coef.append(alpha_t / alpha_s)
289
+ self.first_order_second_coef.append(sigma_t * (torch.exp(h) - 1.0))
290
+
291
+ def multistep_dpm_solver_second_order_coefs_precompute(self, timestep_list, prev_timestep):
292
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
293
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
294
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
295
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
296
+ h = lambda_t - lambda_s0
297
+ if self.algorithm_type == "dpmsolver++":
298
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
299
+ if self.solver_type == "midpoint":
300
+ self.second_order_first_coef.append(sigma_t / sigma_s0)
301
+ self.second_order_second_coef.append((alpha_t * (torch.exp(-h) - 1.0)))
302
+ self.second_order_third_coef.append(0.5 * (alpha_t * (torch.exp(-h) - 1.0)))
303
+ elif self.solver_type == "heun":
304
+ self.second_order_first_coef.append(sigma_t / sigma_s0)
305
+ self.second_order_second_coef.append((alpha_t * (torch.exp(-h) - 1.0)))
306
+ self.second_order_third_coef.append(alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0))
307
+ elif self.algorithm_type == "dpmsolver":
308
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
309
+ if self.solver_type == "midpoint":
310
+ self.second_order_first_coef.append(alpha_t / alpha_s0)
311
+ self.second_order_second_coef.append((sigma_t * (torch.exp(h) - 1.0)))
312
+ self.second_order_third_coef.append(0.5 * (sigma_t * (torch.exp(h) - 1.0)))
313
+ elif self.solver_type == "heun":
314
+ self.second_order_first_coef.append(alpha_t / alpha_s0)
315
+ self.second_order_second_coef.append((sigma_t * (torch.exp(h) - 1.0)))
316
+ self.second_order_third_coef.append((sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)))
317
+
318
+ def multistep_dpm_solver_third_order_coefs_precompute(self, timestep_list, prev_timestep):
319
+ t, s0 = prev_timestep, timestep_list[-1]
320
+ lambda_t, lambda_s0 = (
321
+ self.lambda_t[t],
322
+ self.lambda_t[s0]
323
+ )
324
+ alpha_t, alpha_s0 = self.alpha_t[t], self.alpha_t[s0]
325
+ sigma_t, sigma_s0 = self.sigma_t[t], self.sigma_t[s0]
326
+ h = lambda_t - lambda_s0
327
+ if self.algorithm_type == "dpmsolver++":
328
+ self.third_order_first_coef.append(sigma_t / sigma_s0)
329
+ self.third_order_second_coef.append(alpha_t * (torch.exp(-h) - 1.0))
330
+ self.third_order_third_coef.append(alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0))
331
+ self.third_order_fourth_coef.append(alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5))
332
+ elif self.algorithm_type == "dpmsolver":
333
+ self.third_order_first_coef.append(alpha_t / alpha_s0)
334
+ self.third_order_second_coef.append(sigma_t * (torch.exp(h) - 1.0))
335
+ self.third_order_third_coef.append(sigma_t * ((torch.exp(h) - 1.0) / h - 1.0))
336
+ self.third_order_fourth_coef.append(sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5))
337
+
338
+ def set_timesteps(self, num_inference_steps):
339
+ self.num_inference_steps = num_inference_steps
340
+ timesteps = (
341
+ np.linspace(0, self.num_train_timesteps - 1, num_inference_steps + 1)
342
+ .round()[::-1][:-1]
343
+ .copy()
344
+ .astype(np.int32)
345
+ )
346
+ self.timesteps = torch.from_numpy(timesteps).to(self.device)
347
+ self.model_outputs = [
348
+ None,
349
+ ] * self.solver_order
350
+ self.lower_order_nums = 0
351
+
352
+ def convert_model_output(
353
+ self, model_output, timestep, sample
354
+ ):
355
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
356
+ if self.algorithm_type == "dpmsolver++":
357
+ if self.predict_epsilon:
358
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
359
+ x0_pred = (sample - sigma_t * model_output) / alpha_t
360
+ else:
361
+ x0_pred = model_output
362
+ if self.thresholding:
363
+ # Dynamic thresholding in https://arxiv.org/abs/2205.11487
364
+ dynamic_max_val = torch.quantile(
365
+ torch.abs(x0_pred).reshape((x0_pred.shape[0], -1)), self.dynamic_thresholding_ratio, dim=1
366
+ )
367
+ dynamic_max_val = torch.maximum(
368
+ dynamic_max_val,
369
+ self.sample_max_value * torch.ones_like(dynamic_max_val).to(dynamic_max_val.device),
370
+ )[(...,) + (None,) * (x0_pred.ndim - 1)]
371
+ x0_pred = torch.clamp(x0_pred, -dynamic_max_val, dynamic_max_val) / dynamic_max_val
372
+ return x0_pred
373
+ # DPM-Solver needs to solve an integral of the noise prediction model.
374
+ elif self.algorithm_type == "dpmsolver":
375
+ if self.predict_epsilon:
376
+ return model_output
377
+ else:
378
+ alpha_t, sigma_t = self.alpha_t[timestep], self.sigma_t[timestep]
379
+ epsilon = (sample - alpha_t * model_output) / sigma_t
380
+ return epsilon
381
+
382
+ def dpm_solver_first_order_update(
383
+ self,
384
+ idx,
385
+ model_output,
386
+ sample
387
+ ):
388
+ first_coef = self.first_order_first_coef[idx]
389
+ second_coef = self.first_order_second_coef[idx]
390
+
391
+ if self.algorithm_type == "dpmsolver++":
392
+ x_t = first_coef * sample - second_coef * model_output
393
+ elif self.algorithm_type == "dpmsolver":
394
+ x_t = first_coef * sample - second_coef * model_output
395
+ return x_t
396
+
397
+ def multistep_dpm_solver_second_order_update(
398
+ self,
399
+ idx,
400
+ model_output_list,
401
+ timestep_list,
402
+ prev_timestep,
403
+ sample
404
+ ):
405
+ t, s0, s1 = prev_timestep, timestep_list[-1], timestep_list[-2]
406
+ m0, m1 = model_output_list[-1], model_output_list[-2]
407
+ lambda_t, lambda_s0, lambda_s1 = self.lambda_t[t], self.lambda_t[s0], self.lambda_t[s1]
408
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
409
+ r0 = h_0 / h
410
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
411
+
412
+ first_coef = self.second_order_first_coef[idx]
413
+ second_coef = self.second_order_second_coef[idx]
414
+ third_coef = self.second_order_third_coef[idx]
415
+
416
+ if self.algorithm_type == "dpmsolver++":
417
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
418
+ if self.solver_type == "midpoint":
419
+ x_t = (
420
+ first_coef * sample
421
+ - second_coef * D0
422
+ - third_coef * D1
423
+ )
424
+ elif self.solver_type == "heun":
425
+ x_t = (
426
+ first_coef * sample
427
+ - second_coef * D0
428
+ + third_coef * D1
429
+ )
430
+ elif self.algorithm_type == "dpmsolver":
431
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
432
+ if self.solver_type == "midpoint":
433
+ x_t = (
434
+ first_coef * sample
435
+ - second_coef * D0
436
+ - third_coef * D1
437
+ )
438
+ elif self.solver_type == "heun":
439
+ x_t = (
440
+ first_coef * sample
441
+ - second_coef * D0
442
+ - third_coef * D1
443
+ )
444
+ return x_t
445
+
446
+ def multistep_dpm_solver_third_order_update(
447
+ self,
448
+ idx,
449
+ model_output_list,
450
+ timestep_list,
451
+ prev_timestep,
452
+ sample
453
+ ):
454
+ t, s0, s1, s2 = prev_timestep, timestep_list[-1], timestep_list[-2], timestep_list[-3]
455
+ m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3]
456
+ lambda_t, lambda_s0, lambda_s1, lambda_s2 = (
457
+ self.lambda_t[t],
458
+ self.lambda_t[s0],
459
+ self.lambda_t[s1],
460
+ self.lambda_t[s2],
461
+ )
462
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
463
+ r0, r1 = h_0 / h, h_1 / h
464
+ D0 = m0
465
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
466
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
467
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
468
+
469
+ first_coef = self.third_order_first_coef[idx]
470
+ second_coef = self.third_order_second_coef[idx]
471
+ third_coef = self.third_order_third_coef[idx]
472
+ fourth_coef = self.third_order_fourth_coef[idx]
473
+
474
+ if self.algorithm_type == "dpmsolver++":
475
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
476
+ x_t = (
477
+ first_coef * sample
478
+ - second_coef * D0
479
+ + third_coef * D1
480
+ - fourth_coef * D2
481
+ )
482
+ elif self.algorithm_type == "dpmsolver":
483
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
484
+ x_t = (
485
+ first_coef * sample
486
+ - second_coef * D0
487
+ - third_coef * D1
488
+ - fourth_coef * D2
489
+ )
490
+ return x_t
491
+
492
+ def step(self, output, latents, step_index, timestep):
493
+ if self.num_inference_steps is None:
494
+ raise ValueError(
495
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
496
+ )
497
+
498
+ prev_timestep = 0 if step_index == len(self.timesteps) - 1 else self.timesteps[step_index + 1]
499
+ lower_order_final = (
500
+ (step_index == len(self.timesteps) - 1) and self.lower_order_final and len(self.timesteps) < 15
501
+ )
502
+ lower_order_second = (
503
+ (step_index == len(self.timesteps) - 2) and self.lower_order_final and len(self.timesteps) < 15
504
+ )
505
+
506
+ output = self.convert_model_output(output, timestep, latents)
507
+ for i in range(self.solver_order - 1):
508
+ self.model_outputs[i] = self.model_outputs[i + 1]
509
+ self.model_outputs[-1] = output
510
+
511
+ if self.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
512
+ prev_sample = self.dpm_solver_first_order_update(step_index, output, latents)
513
+ elif self.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
514
+ timestep_list = [self.timesteps[step_index - 1], timestep]
515
+ prev_sample = self.multistep_dpm_solver_second_order_update(
516
+ step_index, self.model_outputs, timestep_list, prev_timestep, latents
517
+ )
518
+ else:
519
+ timestep_list = [self.timesteps[step_index - 2], self.timesteps[step_index - 1], timestep]
520
+ prev_sample = self.multistep_dpm_solver_third_order_update(
521
+ step_index, self.model_outputs, timestep_list, prev_timestep, latents
522
+ )
523
+
524
+ if self.lower_order_nums < self.solver_order:
525
+ self.lower_order_nums += 1
526
+
527
+ return prev_sample
528
+
529
+ def save_image(images, image_path_dir, image_name_prefix):
530
+ """
531
+ Save the generated images to png files.
532
+ """
533
+ images = ((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy()
534
+ for i in range(images.shape[0]):
535
+ image_path = os.path.join(image_path_dir, image_name_prefix+str(i+1)+'-'+str(random.randint(1000,9999))+'.png')
536
+ print(f"Saving image {i+1} / {images.shape[0]} to: {image_path}")
537
+ Image.fromarray(images[i]).save(image_path)