|
| 1 | +import cache_dit |
| 2 | +import torch |
| 3 | +from cache_dit import DBCacheConfig |
| 4 | +from diffusers import QwenImagePipeline |
| 5 | + |
| 6 | +from nunchaku.models.transformers.transformer_qwenimage import NunchakuQwenImageTransformer2DModel |
| 7 | +from nunchaku.utils import get_gpu_memory, get_precision |
| 8 | + |
| 9 | +rank = 32 # you can also use rank=128 model to improve the quality |
| 10 | + |
| 11 | +# Load the model |
| 12 | +transformer = NunchakuQwenImageTransformer2DModel.from_pretrained( |
| 13 | + f"nunchaku-tech/nunchaku-qwen-image/svdq-{get_precision()}_r{rank}-qwen-image.safetensors" |
| 14 | +) |
| 15 | + |
| 16 | +# currently, you need to use this pipeline to offload the model to CPU |
| 17 | +pipe = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", transformer=transformer, torch_dtype=torch.bfloat16) |
| 18 | + |
| 19 | +# Please check https://github.com/vipshop/cache-dit for more details about the parameters. |
| 20 | + |
| 21 | +cache_dit.enable_cache( |
| 22 | + pipe, |
| 23 | + cache_config=DBCacheConfig( |
| 24 | + Fn_compute_blocks=8, |
| 25 | + Bn_compute_blocks=0, |
| 26 | + residual_diff_threshold=0.12, |
| 27 | + ), |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +if get_gpu_memory() > 18: |
| 32 | + pipe.enable_model_cpu_offload() |
| 33 | +else: |
| 34 | + # use per-layer offloading for low VRAM. This only requires 3-4GB of VRAM. |
| 35 | + transformer.set_offload( |
| 36 | + True, use_pin_memory=False, num_blocks_on_gpu=1 |
| 37 | + ) # increase num_blocks_on_gpu if you have more VRAM |
| 38 | + pipe._exclude_from_cpu_offload.append("transformer") |
| 39 | + pipe.enable_sequential_cpu_offload() |
| 40 | + |
| 41 | +positive_magic = { |
| 42 | + "en": "Ultra HD, 4K, cinematic composition.", # for english prompt, |
| 43 | + "zh": "超清,4K,电影级构图", # for chinese prompt, |
| 44 | +} |
| 45 | + |
| 46 | +# Generate image |
| 47 | +prompt = """Bookstore window display. A sign displays “New Arrivals This Week”. Below, a shelf tag with the text “Best-Selling Novels Here”. To the side, a colorful poster advertises “Author Meet And Greet on Saturday” with a central portrait of the author. There are four books on the bookshelf, namely “The light between worlds” “When stars are scattered” “The slient patient” “The night circus”""" |
| 48 | +negative_prompt = " " # using an empty string if you do not have specific concept to remove |
| 49 | + |
| 50 | +image = pipe( |
| 51 | + prompt=prompt + positive_magic["en"], |
| 52 | + negative_prompt=negative_prompt, |
| 53 | + width=1664, |
| 54 | + height=928, |
| 55 | + num_inference_steps=50, |
| 56 | + true_cfg_scale=4.0, |
| 57 | +).images[0] |
| 58 | + |
| 59 | +image.save(f"qwen-image-cache-dit-r{rank}.png") |
0 commit comments