|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. 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, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +# pylint:disable=redefined-outer-name,logging-format-interpolation |
| 18 | +import argparse |
| 19 | +import inspect |
| 20 | +import logging |
| 21 | +import os |
| 22 | +import time |
| 23 | +from typing import List |
| 24 | + |
| 25 | +import numpy as np |
| 26 | +import onnx |
| 27 | +import onnxruntime as ort |
| 28 | +import torch |
| 29 | +from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline |
| 30 | + |
| 31 | +from onnx_neural_compressor import data_reader |
| 32 | +from onnx_neural_compressor.quantization import QuantType, config, quantize |
| 33 | + |
| 34 | +logging.basicConfig( |
| 35 | + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.WARN |
| 36 | +) |
| 37 | + |
| 38 | +parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 39 | +parser.add_argument( |
| 40 | + "--model_path", |
| 41 | + type=str, |
| 42 | + help="Folder path of ONNX Stable-diffusion model, it contains model_index.json and sub-model folders.", |
| 43 | +) |
| 44 | +parser.add_argument("--quantized_unet_path", type=str, default=None, help="Path of the quantized unet model.") |
| 45 | +parser.add_argument("--benchmark", action="store_true", default=False) |
| 46 | +parser.add_argument("--tune", action="store_true", default=False, help="whether quantize the model") |
| 47 | +parser.add_argument("--output_model", type=str, default=None, help="output model path") |
| 48 | +parser.add_argument("--image_path", type=str, default="image.png", help="generated image path") |
| 49 | +parser.add_argument( |
| 50 | + "--batch_size", |
| 51 | + default=1, |
| 52 | + type=int, |
| 53 | +) |
| 54 | +parser.add_argument("--prompt", type=str, default="a photo of an astronaut riding a horse on mars") |
| 55 | +parser.add_argument("--alpha", type=float, default=0.7) |
| 56 | +parser.add_argument("--seed", type=int, default=1234, help="random seed for generation") |
| 57 | +parser.add_argument("--provider", type=str, default="CPUExecutionProvider") |
| 58 | +args = parser.parse_args() |
| 59 | + |
| 60 | +ORT_TO_NP_TYPE = { |
| 61 | + "tensor(bool)": np.bool_, |
| 62 | + "tensor(int8)": np.int8, |
| 63 | + "tensor(uint8)": np.uint8, |
| 64 | + "tensor(int16)": np.int16, |
| 65 | + "tensor(uint16)": np.uint16, |
| 66 | + "tensor(int32)": np.int32, |
| 67 | + "tensor(uint32)": np.uint32, |
| 68 | + "tensor(int64)": np.int64, |
| 69 | + "tensor(uint64)": np.uint64, |
| 70 | + "tensor(float16)": np.float16, |
| 71 | + "tensor(float)": np.float32, |
| 72 | + "tensor(double)": np.float64, |
| 73 | +} |
| 74 | + |
| 75 | +np.random.seed(args.seed) |
| 76 | + |
| 77 | + |
| 78 | +def benchmark(model): |
| 79 | + generator = None if args.seed is None else np.random.RandomState(args.seed) |
| 80 | + |
| 81 | + pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model_path, provider=args.provider) |
| 82 | + if args.quantized_unet_path is not None: |
| 83 | + unet = OnnxRuntimeModel(model=ort.InferenceSession(args.quantized_unet_path, providers=[args.provider])) |
| 84 | + pipe.unet = unet |
| 85 | + |
| 86 | + image = None |
| 87 | + |
| 88 | + tic = time.time() |
| 89 | + image = pipe(prompt=args.prompt, generator=generator).images[0] |
| 90 | + toc = time.time() |
| 91 | + |
| 92 | + if image is not None: |
| 93 | + image.save(args.image_path) |
| 94 | + print("Generated image is saved as " + args.image_path) |
| 95 | + |
| 96 | + print("\n", "-" * 10, "Summary:", "-" * 10) |
| 97 | + throughput = 1 / (toc - tic) |
| 98 | + print("Throughput: {} samples/s".format(throughput)) |
| 99 | + |
| 100 | + |
| 101 | +class DataReader(data_reader.CalibrationDataReader): |
| 102 | + |
| 103 | + def __init__(self, model_path, batch_size=1): |
| 104 | + self.encoded_list = [] |
| 105 | + self.batch_size = batch_size |
| 106 | + |
| 107 | + model = onnx.load(os.path.join(model_path, "unet/model.onnx"), load_external_data=False) |
| 108 | + inputs_names = [input.name for input in model.graph.input] |
| 109 | + |
| 110 | + generator = np.random |
| 111 | + pipe = OnnxStableDiffusionPipeline.from_pretrained(model_path, provider="CPUExecutionProvider") |
| 112 | + prompt = "A cat holding a sign that says hello world" |
| 113 | + self.batch_size = batch_size |
| 114 | + guidance_scale = 7.5 |
| 115 | + do_classifier_free_guidance = guidance_scale > 1.0 |
| 116 | + num_images_per_prompt = 1 |
| 117 | + negative_prompt_embeds = None |
| 118 | + negative_prompt = None |
| 119 | + callback = None |
| 120 | + eta = 0.0 |
| 121 | + latents = None |
| 122 | + prompt_embeds = None |
| 123 | + if prompt_embeds is None: |
| 124 | + # get prompt text embeddings |
| 125 | + text_inputs = pipe.tokenizer( |
| 126 | + prompt, |
| 127 | + padding="max_length", |
| 128 | + max_length=pipe.tokenizer.model_max_length, |
| 129 | + truncation=True, |
| 130 | + return_tensors="np", |
| 131 | + ) |
| 132 | + text_input_ids = text_inputs.input_ids |
| 133 | + prompt_embeds = pipe.text_encoder(input_ids=text_input_ids.astype(np.int32))[0] |
| 134 | + |
| 135 | + prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0) |
| 136 | + |
| 137 | + # get unconditional embeddings for classifier free guidance |
| 138 | + if do_classifier_free_guidance and negative_prompt_embeds is None: |
| 139 | + uncond_tokens: List[str] |
| 140 | + if negative_prompt is None: |
| 141 | + uncond_tokens = [""] * batch_size |
| 142 | + elif type(prompt) is not type(negative_prompt): |
| 143 | + raise TypeError( |
| 144 | + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" |
| 145 | + f" {type(prompt)}." |
| 146 | + ) |
| 147 | + elif isinstance(negative_prompt, str): |
| 148 | + uncond_tokens = [negative_prompt] * batch_size |
| 149 | + elif batch_size != len(negative_prompt): |
| 150 | + raise ValueError( |
| 151 | + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" |
| 152 | + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" |
| 153 | + " the batch size of `prompt`." |
| 154 | + ) |
| 155 | + else: |
| 156 | + uncond_tokens = negative_prompt |
| 157 | + |
| 158 | + max_length = prompt_embeds.shape[1] |
| 159 | + uncond_input = pipe.tokenizer( |
| 160 | + uncond_tokens, |
| 161 | + padding="max_length", |
| 162 | + max_length=max_length, |
| 163 | + truncation=True, |
| 164 | + return_tensors="np", |
| 165 | + ) |
| 166 | + negative_prompt_embeds = pipe.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0] |
| 167 | + |
| 168 | + if do_classifier_free_guidance: |
| 169 | + negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0) |
| 170 | + |
| 171 | + # For classifier free guidance, we need to do two forward passes. |
| 172 | + # Here we concatenate the unconditional and text embeddings into a single batch |
| 173 | + # to avoid doing two forward passes |
| 174 | + prompt_embeds = np.concatenate([negative_prompt_embeds, prompt_embeds]) |
| 175 | + |
| 176 | + # get the initial random noise unless the user supplied it |
| 177 | + latents_dtype = prompt_embeds.dtype |
| 178 | + latents_shape = (batch_size * num_images_per_prompt, 4, 512 // 8, 512 // 8) |
| 179 | + if latents is None: |
| 180 | + latents = generator.randn(*latents_shape).astype(latents_dtype) |
| 181 | + elif latents.shape != latents_shape: |
| 182 | + raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") |
| 183 | + |
| 184 | + # set timesteps |
| 185 | + pipe.scheduler.set_timesteps(50) |
| 186 | + |
| 187 | + latents = latents * np.float64(pipe.scheduler.init_noise_sigma) |
| 188 | + |
| 189 | + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature |
| 190 | + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. |
| 191 | + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 |
| 192 | + # and should be between [0, 1] |
| 193 | + accepts_eta = "eta" in set(inspect.signature(pipe.scheduler.step).parameters.keys()) |
| 194 | + extra_step_kwargs = {} |
| 195 | + if accepts_eta: |
| 196 | + extra_step_kwargs["eta"] = eta |
| 197 | + |
| 198 | + timestep_dtype = next( |
| 199 | + (input.type for input in pipe.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)" |
| 200 | + ) |
| 201 | + timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype] |
| 202 | + for i, t in enumerate(pipe.scheduler.timesteps): |
| 203 | + # expand the latents if we are doing classifier free guidance |
| 204 | + latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents |
| 205 | + latent_model_input = pipe.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t) |
| 206 | + latent_model_input = latent_model_input.cpu().numpy() |
| 207 | + |
| 208 | + # predict the noise residual |
| 209 | + timestep = np.array([t], dtype=timestep_dtype) |
| 210 | + ort_input = {} |
| 211 | + for name, inp in zip(inputs_names, [latent_model_input, timestep, prompt_embeds]): |
| 212 | + ort_input[name] = inp |
| 213 | + self.encoded_list.append(ort_input) |
| 214 | + noise_pred = pipe.unet(sample=latent_model_input, timestep=timestep, encoder_hidden_states=prompt_embeds) |
| 215 | + noise_pred = noise_pred[0] |
| 216 | + |
| 217 | + # perform guidance |
| 218 | + if do_classifier_free_guidance: |
| 219 | + noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2) |
| 220 | + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) |
| 221 | + |
| 222 | + # compute the previous noisy sample x_t -> x_t-1 |
| 223 | + scheduler_output = pipe.scheduler.step( |
| 224 | + torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs |
| 225 | + ) |
| 226 | + latents = scheduler_output.prev_sample.numpy() |
| 227 | + |
| 228 | + # call the callback, if provided |
| 229 | + if callback is not None and i % 1 == 0: |
| 230 | + step_idx = i // getattr(pipe.scheduler, "order", 1) |
| 231 | + callback(step_idx, t, latents) |
| 232 | + |
| 233 | + self.iter_next = iter(self.encoded_list) |
| 234 | + |
| 235 | + def get_next(self): |
| 236 | + return next(self.iter_next, None) |
| 237 | + |
| 238 | + def rewind(self): |
| 239 | + self.iter_next = iter(self.encoded_list) |
| 240 | + |
| 241 | + |
| 242 | +if __name__ == "__main__": |
| 243 | + if args.benchmark: |
| 244 | + benchmark(args.model_path) |
| 245 | + |
| 246 | + if args.tune: |
| 247 | + data_reader = DataReader(args.model_path) |
| 248 | + cfg = config.StaticQuantConfig( |
| 249 | + data_reader, |
| 250 | + weight_type=QuantType.QInt8, |
| 251 | + activation_type=QuantType.QUInt8, |
| 252 | + op_types_to_quantize=["MatMul", "Gemm"], |
| 253 | + per_channel=True, |
| 254 | + extra_options={ |
| 255 | + "SmoothQuant": True, |
| 256 | + "SmoothQuantAlpha": args.alpha, |
| 257 | + "WeightSymmetric": True, |
| 258 | + "ActivationSymmetric": False, |
| 259 | + "OpTypesToExcludeOutputQuantization": ["MatMul", "Gemm"], |
| 260 | + }, |
| 261 | + ) |
| 262 | + input_path = os.path.join(args.model_path, "unet/model.onnx") |
| 263 | + quantize(input_path, args.output_model, cfg, optimization_level=ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED) |
0 commit comments