|
| 1 | +<!--Copyright 2024 The HuggingFace Team. All rights reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with |
| 4 | +the License. You may obtain a copy of the License at |
| 5 | +
|
| 6 | +http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +
|
| 8 | +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on |
| 9 | +an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 10 | +specific language governing permissions and limitations under the License. |
| 11 | +--> |
| 12 | + |
| 13 | +# Compile and offloading quantized models |
| 14 | + |
| 15 | +Optimizing models often involves trade-offs between [inference speed](./fp16) and [memory-usage](./memory). For instance, while [caching](./cache) can boost inference speed, it also increases memory consumption since it needs to store the outputs of intermediate attention layers. A more balanced optimization strategy combines quantizing a model, [torch.compile](./fp16#torchcompile) and various [offloading methods](./memory#offloading). |
| 16 | + |
| 17 | +For image generation, combining quantization and [model offloading](./memory#model-offloading) can often give the best trade-off between quality, speed, and memory. Group offloading is not as effective for image generation because it is usually not possible to *fully* overlap data transfer if the compute kernel finishes faster. This results in some communication overhead between the CPU and GPU. |
| 18 | + |
| 19 | +For video generation, combining quantization and [group-offloading](./memory#group-offloading) tends to be better because video models are more compute-bound. |
| 20 | + |
| 21 | +The table below provides a comparison of optimization strategy combinations and their impact on latency and memory-usage for Flux. |
| 22 | + |
| 23 | +| combination | latency (s) | memory-usage (GB) | |
| 24 | +|---|---|---| |
| 25 | +| quantization | 32.602 | 14.9453 | |
| 26 | +| quantization, torch.compile | 25.847 | 14.9448 | |
| 27 | +| quantization, torch.compile, model CPU offloading | 32.312 | 12.2369 | |
| 28 | +<small>These results are benchmarked on Flux with a RTX 4090. The transformer and text_encoder components are quantized. Refer to the <a href="https://gist.github.com/sayakpaul/0db9d8eeeb3d2a0e5ed7cf0d9ca19b7d" benchmarking script</a> if you're interested in evaluating your own model.</small> |
| 29 | + |
| 30 | +This guide will show you how to compile and offload a quantized model with [bitsandbytes](../quantization/bitsandbytes#torchcompile). Make sure you are using [PyTorch nightly](https://pytorch.org/get-started/locally/) and the latest version of bitsandbytes. |
| 31 | + |
| 32 | +```bash |
| 33 | +pip install -U bitsandbytes |
| 34 | +``` |
| 35 | + |
| 36 | +## Quantization and torch.compile |
| 37 | + |
| 38 | +Start by [quantizing](../quantization/overview) a model to reduce the memory required for storage and [compiling](./fp16#torchcompile) it to accelerate inference. |
| 39 | + |
| 40 | +Configure the [Dynamo](https://docs.pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) `capture_dynamic_output_shape_ops = True` to handle dynamic outputs when compiling bitsandbytes models. |
| 41 | + |
| 42 | +```py |
| 43 | +import torch |
| 44 | +from diffusers import DiffusionPipeline |
| 45 | +from diffusers.quantizers import PipelineQuantizationConfig |
| 46 | + |
| 47 | +torch._dynamo.config.capture_dynamic_output_shape_ops = True |
| 48 | + |
| 49 | +# quantize |
| 50 | +pipeline_quant_config = PipelineQuantizationConfig( |
| 51 | + quant_backend="bitsandbytes_4bit", |
| 52 | + quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16}, |
| 53 | + components_to_quantize=["transformer", "text_encoder_2"], |
| 54 | +) |
| 55 | +pipeline = DiffusionPipeline.from_pretrained( |
| 56 | + "black-forest-labs/FLUX.1-dev", |
| 57 | + quantization_config=pipeline_quant_config, |
| 58 | + torch_dtype=torch.bfloat16, |
| 59 | +).to("cuda") |
| 60 | + |
| 61 | +# compile |
| 62 | +pipeline.transformer.to(memory_format=torch.channels_last) |
| 63 | +pipeline.transformer.compile(mode="max-autotune", fullgraph=True) |
| 64 | +pipeline(""" |
| 65 | + cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California |
| 66 | + highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain |
| 67 | +""" |
| 68 | +).images[0] |
| 69 | +``` |
| 70 | + |
| 71 | +## Quantization, torch.compile, and offloading |
| 72 | + |
| 73 | +In addition to quantization and torch.compile, try offloading if you need to reduce memory-usage further. Offloading moves various layers or model components from the CPU to the GPU as needed for computations. |
| 74 | + |
| 75 | +Configure the [Dynamo](https://docs.pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) `cache_size_limit` during offloading to avoid excessive recompilation and set `capture_dynamic_output_shape_ops = True` to handle dynamic outputs when compiling bitsandbytes models. |
| 76 | + |
| 77 | +<hfoptions id="offloading"> |
| 78 | +<hfoption id="model CPU offloading"> |
| 79 | + |
| 80 | +[Model CPU offloading](./memory#model-offloading) moves an individual pipeline component, like the transformer model, to the GPU when it is needed for computation. Otherwise, it is offloaded to the CPU. |
| 81 | + |
| 82 | +```py |
| 83 | +import torch |
| 84 | +from diffusers import DiffusionPipeline |
| 85 | +from diffusers.quantizers import PipelineQuantizationConfig |
| 86 | + |
| 87 | +torch._dynamo.config.cache_size_limit = 1000 |
| 88 | +torch._dynamo.config.capture_dynamic_output_shape_ops = True |
| 89 | + |
| 90 | +# quantize |
| 91 | +pipeline_quant_config = PipelineQuantizationConfig( |
| 92 | + quant_backend="bitsandbytes_4bit", |
| 93 | + quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16}, |
| 94 | + components_to_quantize=["transformer", "text_encoder_2"], |
| 95 | +) |
| 96 | +pipeline = DiffusionPipeline.from_pretrained( |
| 97 | + "black-forest-labs/FLUX.1-dev", |
| 98 | + quantization_config=pipeline_quant_config, |
| 99 | + torch_dtype=torch.bfloat16, |
| 100 | +).to("cuda") |
| 101 | + |
| 102 | +# model CPU offloading |
| 103 | +pipeline.enable_model_cpu_offload() |
| 104 | + |
| 105 | +# compile |
| 106 | +pipeline.transformer.compile() |
| 107 | +pipeline( |
| 108 | + "cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California, highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain" |
| 109 | +).images[0] |
| 110 | +``` |
| 111 | + |
| 112 | +</hfoption> |
| 113 | +<hfoption id="group offloading"> |
| 114 | + |
| 115 | +[Group offloading](./memory#group-offloading) moves the internal layers of an individual pipeline component, like the transformer model, to the GPU for computation and offloads it when it's not required. At the same time, it uses the [CUDA stream](./memory#cuda-stream) feature to prefetch the next layer for execution. |
| 116 | + |
| 117 | +By overlapping computation and data transfer, it is faster than model CPU offloading while also saving memory. |
| 118 | + |
| 119 | +```py |
| 120 | +# pip install ftfy |
| 121 | +import torch |
| 122 | +from diffusers import AutoModel, DiffusionPipeline |
| 123 | +from diffusers.hooks import apply_group_offloading |
| 124 | +from diffusers.utils import export_to_video |
| 125 | +from diffusers.quantizers import PipelineQuantizationConfig |
| 126 | +from transformers import UMT5EncoderModel |
| 127 | + |
| 128 | +torch._dynamo.config.cache_size_limit = 1000 |
| 129 | +torch._dynamo.config.capture_dynamic_output_shape_ops = True |
| 130 | + |
| 131 | +# quantize |
| 132 | +pipeline_quant_config = PipelineQuantizationConfig( |
| 133 | + quant_backend="bitsandbytes_4bit", |
| 134 | + quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16}, |
| 135 | + components_to_quantize=["transformer", "text_encoder"], |
| 136 | +) |
| 137 | + |
| 138 | +text_encoder = UMT5EncoderModel.from_pretrained( |
| 139 | + "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16 |
| 140 | +) |
| 141 | +pipeline = DiffusionPipeline.from_pretrained( |
| 142 | + "Wan-AI/Wan2.1-T2V-14B-Diffusers", |
| 143 | + quantization_config=pipeline_quant_config, |
| 144 | + torch_dtype=torch.bfloat16, |
| 145 | +).to("cuda") |
| 146 | + |
| 147 | +# group offloading |
| 148 | +onload_device = torch.device("cuda") |
| 149 | +offload_device = torch.device("cpu") |
| 150 | + |
| 151 | +pipeline.transformer.enable_group_offload( |
| 152 | + onload_device=onload_device, |
| 153 | + offload_device=offload_device, |
| 154 | + offload_type="leaf_level", |
| 155 | + use_stream=True, |
| 156 | + non_blocking=True |
| 157 | +) |
| 158 | +pipeline.vae.enable_group_offload( |
| 159 | + onload_device=onload_device, |
| 160 | + offload_device=offload_device, |
| 161 | + offload_type="leaf_level", |
| 162 | + use_stream=True, |
| 163 | + non_blocking=True |
| 164 | +) |
| 165 | +apply_group_offloading( |
| 166 | + pipeline.text_encoder, |
| 167 | + onload_device=onload_device, |
| 168 | + offload_type="leaf_level", |
| 169 | + use_stream=True, |
| 170 | + non_blocking=True |
| 171 | +) |
| 172 | + |
| 173 | +# compile |
| 174 | +pipeline.transformer.compile() |
| 175 | + |
| 176 | +prompt = """ |
| 177 | +The camera rushes from far to near in a low-angle shot, |
| 178 | +revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in |
| 179 | +for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. |
| 180 | +Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic |
| 181 | +shadows and warm highlights. Medium composition, front view, low angle, with depth of field. |
| 182 | +""" |
| 183 | +negative_prompt = """ |
| 184 | +Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, |
| 185 | +low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, |
| 186 | +misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards |
| 187 | +""" |
| 188 | + |
| 189 | +output = pipeline( |
| 190 | + prompt=prompt, |
| 191 | + negative_prompt=negative_prompt, |
| 192 | + num_frames=81, |
| 193 | + guidance_scale=5.0, |
| 194 | +).frames[0] |
| 195 | +export_to_video(output, "output.mp4", fps=16) |
| 196 | +``` |
| 197 | + |
| 198 | +</hfoption> |
| 199 | +</hfoptions> |
0 commit comments