|
| 1 | +# %% |
| 2 | +# Import the following libraries |
| 3 | +# ----------------------------- |
| 4 | +# Load the ModelOpt-modified model architecture and weights using Huggingface APIs |
| 5 | +# Add argument parsing for dtype selection |
| 6 | +import argparse |
| 7 | +import re |
| 8 | + |
| 9 | +import modelopt.torch.opt as mto |
| 10 | +import modelopt.torch.quantization as mtq |
| 11 | +import torch |
| 12 | +import torch_tensorrt |
| 13 | +from diffusers import FluxPipeline |
| 14 | +from diffusers.models.attention_processor import Attention |
| 15 | +from diffusers.models.transformers.transformer_flux import FluxTransformer2DModel |
| 16 | +from modelopt.torch.quantization.utils import export_torch_mode |
| 17 | +from torch.export._trace import _export |
| 18 | +from transformers import AutoModelForCausalLM |
| 19 | + |
| 20 | +parser = argparse.ArgumentParser( |
| 21 | + description="Run Flux quantization with different dtypes" |
| 22 | +) |
| 23 | +parser.add_argument( |
| 24 | + "--dtype", |
| 25 | + choices=["fp8", "int8"], |
| 26 | + default="int8", |
| 27 | + help="Quantization data type to use (fp8 or int8)", |
| 28 | +) |
| 29 | + |
| 30 | +args = parser.parse_args() |
| 31 | + |
| 32 | +# Update enabled precisions based on dtype argument |
| 33 | +if args.dtype == "fp8": |
| 34 | + enabled_precisions = {torch.float8_e4m3fn, torch.float16} |
| 35 | + ptq_config = mtq.FP8_DEFAULT_CFG |
| 36 | +else: # int8 |
| 37 | + enabled_precisions = {torch.int8, torch.float16} |
| 38 | + ptq_config = mtq.INT8_DEFAULT_CFG |
| 39 | +print(f"\nUsing {args.dtype} quantization") |
| 40 | +# %% |
| 41 | +DEVICE = "cuda:0" |
| 42 | +pipe = FluxPipeline.from_pretrained( |
| 43 | + "black-forest-labs/FLUX.1-dev", |
| 44 | + torch_dtype=torch.float16, |
| 45 | +) |
| 46 | +pipe.transformer = FluxTransformer2DModel( |
| 47 | + num_layers=1, num_single_layers=1, guidance_embeds=True |
| 48 | +) |
| 49 | + |
| 50 | +pipe.to(DEVICE).to(torch.float16) |
| 51 | +# Store the config and transformer backbone |
| 52 | +config = pipe.transformer.config |
| 53 | +# global backbone |
| 54 | +backbone = pipe.transformer |
| 55 | +backbone.eval() |
| 56 | + |
| 57 | + |
| 58 | +def filter_func(name): |
| 59 | + pattern = re.compile( |
| 60 | + r".*(time_emb_proj|time_embedding|conv_in|conv_out|conv_shortcut|add_embedding|pos_embed|time_text_embed|context_embedder|norm_out|x_embedder).*" |
| 61 | + ) |
| 62 | + return pattern.match(name) is not None |
| 63 | + |
| 64 | + |
| 65 | +def generate_image(pipe, prompt, image_name): |
| 66 | + seed = 42 |
| 67 | + image = pipe( |
| 68 | + prompt, |
| 69 | + output_type="pil", |
| 70 | + num_inference_steps=20, |
| 71 | + generator=torch.Generator("cuda").manual_seed(seed), |
| 72 | + ).images[0] |
| 73 | + image.save(f"{image_name}.png") |
| 74 | + print(f"Image generated using {image_name} model saved as {image_name}.png") |
| 75 | + |
| 76 | + |
| 77 | +generate_image(pipe, ["A golden retriever holding a sign to code"], "dog_code") |
| 78 | + |
| 79 | +# %% |
| 80 | +# Quantization |
| 81 | + |
| 82 | + |
| 83 | +def do_calibrate( |
| 84 | + pipe, |
| 85 | + prompt: str, |
| 86 | +) -> None: |
| 87 | + """ |
| 88 | + Run calibration steps on the pipeline using the given prompts. |
| 89 | + """ |
| 90 | + image = pipe( |
| 91 | + prompt, |
| 92 | + output_type="pil", |
| 93 | + num_inference_steps=20, |
| 94 | + generator=torch.Generator("cuda").manual_seed(0), |
| 95 | + ).images[0] |
| 96 | + |
| 97 | + |
| 98 | +def forward_loop(mod): |
| 99 | + # Switch the pipeline's backbone, run calibration |
| 100 | + pipe.transformer = mod |
| 101 | + do_calibrate( |
| 102 | + pipe=pipe, |
| 103 | + prompt="test", |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +backbone = mtq.quantize(backbone, ptq_config, forward_loop) |
| 108 | +mtq.disable_quantizer(backbone, filter_func) |
| 109 | + |
| 110 | +batch_size = 2 |
| 111 | +BATCH = torch.export.Dim("batch", min=1, max=2) |
| 112 | +SEQ_LEN = torch.export.Dim("seq_len", min=1, max=512) |
| 113 | +# This particular min, max values for img_id input are recommended by torch dynamo during the export of the model. |
| 114 | +# To see this recommendation, you can try exporting using min=1, max=4096 |
| 115 | +IMG_ID = torch.export.Dim("img_id", min=3586, max=4096) |
| 116 | +dynamic_shapes = { |
| 117 | + "hidden_states": {0: BATCH}, |
| 118 | + "encoder_hidden_states": {0: BATCH, 1: SEQ_LEN}, |
| 119 | + "pooled_projections": {0: BATCH}, |
| 120 | + "timestep": {0: BATCH}, |
| 121 | + "txt_ids": {0: SEQ_LEN}, |
| 122 | + "img_ids": {0: IMG_ID}, |
| 123 | + "guidance": {0: BATCH}, |
| 124 | + "joint_attention_kwargs": {}, |
| 125 | + "return_dict": None, |
| 126 | +} |
| 127 | +# The guidance factor is of type torch.float32 |
| 128 | +dummy_inputs = { |
| 129 | + "hidden_states": torch.randn((batch_size, 4096, 64), dtype=torch.float16).to( |
| 130 | + DEVICE |
| 131 | + ), |
| 132 | + "encoder_hidden_states": torch.randn( |
| 133 | + (batch_size, 512, 4096), dtype=torch.float16 |
| 134 | + ).to(DEVICE), |
| 135 | + "pooled_projections": torch.randn((batch_size, 768), dtype=torch.float16).to( |
| 136 | + DEVICE |
| 137 | + ), |
| 138 | + "timestep": torch.tensor([1.0] * batch_size, dtype=torch.float16).to(DEVICE), |
| 139 | + "txt_ids": torch.randn((512, 3), dtype=torch.float16).to(DEVICE), |
| 140 | + "img_ids": torch.randn((4096, 3), dtype=torch.float16).to(DEVICE), |
| 141 | + "guidance": torch.tensor([1.0] * batch_size, dtype=torch.float32).to(DEVICE), |
| 142 | + "joint_attention_kwargs": {}, |
| 143 | + "return_dict": False, |
| 144 | +} |
| 145 | + |
| 146 | +# This will create an exported program which is going to be compiled with Torch-TensorRT |
| 147 | +with export_torch_mode(): |
| 148 | + ep = _export( |
| 149 | + backbone, |
| 150 | + args=(), |
| 151 | + kwargs=dummy_inputs, |
| 152 | + dynamic_shapes=dynamic_shapes, |
| 153 | + strict=False, |
| 154 | + allow_complex_guards_as_runtime_asserts=True, |
| 155 | + ) |
| 156 | + |
| 157 | +with torch_tensorrt.logging.debug(): |
| 158 | + trt_gm = torch_tensorrt.dynamo.compile( |
| 159 | + ep, |
| 160 | + inputs=dummy_inputs, |
| 161 | + enabled_precisions=enabled_precisions, |
| 162 | + truncate_double=True, |
| 163 | + min_block_size=1, |
| 164 | + debug=False, |
| 165 | + use_python_runtime=True, |
| 166 | + immutable_weights=True, |
| 167 | + offload_module_to_cpu=True, |
| 168 | + ) |
| 169 | + |
| 170 | + |
| 171 | +del ep |
| 172 | +pipe.transformer = trt_gm |
| 173 | +pipe.transformer.config = config |
| 174 | + |
| 175 | + |
| 176 | +# %% |
| 177 | +trt_gm.device = torch.device(DEVICE) |
| 178 | +# Function which generates images from the flux pipeline |
| 179 | +generate_image(pipe, ["A golden retriever"], "dog_code2") |
| 180 | + |
| 181 | + |
| 182 | +def benchmark(prompt, inference_step, batch_size=2, iterations=1): |
| 183 | + from time import time |
| 184 | + |
| 185 | + start = time() |
| 186 | + for i in range(iterations): |
| 187 | + image = pipe( |
| 188 | + prompt, |
| 189 | + output_type="pil", |
| 190 | + num_inference_steps=inference_step, |
| 191 | + num_images_per_prompt=batch_size, |
| 192 | + ).images |
| 193 | + end = time() |
| 194 | + print("Time Elapse for", iterations, "iterations:", end - start) |
| 195 | + print("Average Latency Per Step:", (end - start) / inference_step / iterations) |
| 196 | + return image |
| 197 | + |
| 198 | + |
| 199 | +print("Benchmark Original PyTorch Module Latency (int8)") |
| 200 | +benchmark(["Test"], 50, iterations=3) |
| 201 | + |
| 202 | +# For this dummy model, the fp16 engine size is around 1GB, fp32 engine size is around 2GB |
0 commit comments