Created
September 21, 2026 07:36
-
-
Save conoro/36d7db2e30cbf1df4dac615ed1d072cd to your computer and use it in GitHub Desktop.
Qwen-Image-2.1 running in BF16 on 2× RTX 3060 12GB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """Unquantized Qwen-Image-2.1 for two 12GB CUDA GPUs and 32GB system RAM. | |
| Run in the SAME environment as the working 4-bit script; no new packages: | |
| python test02_bf16_staged.py --width 512 --height 512 --steps 10 | |
| python test02_bf16_staged.py | |
| Default: 768x768, 40 steps, seed 42; saves t2i_bf16.png and a timings JSON. | |
| Stages: BF16 prompt encoder on both GPUs -> unload -> BF16 transformer on | |
| both GPUs -> unload -> tiled BF16 VAE decoding on GPU 0. Only small embeddings | |
| and latents are retained on CPU between stages. No per-step weight offload. | |
| This is a text-to-image script. Checked against upstream code on 2026-09-21; | |
| end-to-end validation on the target dual-RTX-3060 machine is still required. | |
| """ | |
| import os | |
| import sys | |
| # Keep the cuDNN workaround local to this process. A fresh interpreter is | |
| # required to clear preloaded libraries and the dynamic linker's search path. | |
| if any(key in os.environ for key in ("LD_LIBRARY_PATH", "LD_PRELOAD")): | |
| clean_env = os.environ.copy() | |
| clean_env.pop("LD_LIBRARY_PATH", None) | |
| clean_env.pop("LD_PRELOAD", None) | |
| os.execve(sys.executable, [sys.executable, *sys.argv], clean_env) | |
| def transformer_device_map(num_layers, gpu0_blocks): | |
| """Keep outer tensor operations on GPU 0 and split contiguous whole blocks.""" | |
| if not 0 < gpu0_blocks < num_layers: | |
| raise ValueError(f"--gpu0-blocks must be between 1 and {num_layers - 1}.") | |
| mapping = { | |
| "pos_embed": 0, | |
| "time_text_embed": 0, | |
| "txt_in": 0, | |
| "img_in": 0, | |
| "modulation": 0, | |
| "norm_out": 0, | |
| "proj_out": 0, | |
| } | |
| mapping.update({ | |
| f"transformer_blocks.{index}": 0 if index < gpu0_blocks else 1 | |
| for index in range(num_layers) | |
| }) | |
| # Deliberately no root "" mapping: moving the entire root's submodules to | |
| # GPU 0 would defeat the split. Every parameter-bearing child is covered. | |
| return mapping | |
| def mapped_parameter_bytes(module, mapping, floating_bytes=None): | |
| """Count weights without materializing them; reject uncovered parameters.""" | |
| sizes = {0: 0, 1: 0} | |
| for name, parameter in module.named_parameters(): | |
| matches = [key for key in mapping if name == key or name.startswith(key + ".")] | |
| if not matches: | |
| raise RuntimeError(f"Device map does not cover parameter: {name}") | |
| target = mapping[max(matches, key=len)] | |
| size = floating_bytes if floating_bytes and parameter.is_floating_point() else parameter.element_size() | |
| sizes[target] += parameter.numel() * size | |
| return sizes | |
| def text_encoder_device_map(module, weight_budgets): | |
| """Choose a contiguous decoder split using the actual model's parameter sizes.""" | |
| num_layers = len(module.model.language_model.layers) | |
| best = None | |
| for cut in range(1, num_layers): | |
| # Embeddings and output head share GPU 0, including tied-weight configs. | |
| # The unused vision encoder stays on GPU 1 for this text-only script. | |
| mapping = { | |
| "model.language_model.embed_tokens": 0, | |
| "model.language_model.rotary_emb": 0, | |
| "model.language_model.norm": 0, | |
| "lm_head": 0, | |
| "model.visual": 1, | |
| } | |
| mapping.update({ | |
| f"model.language_model.layers.{index}": 0 if index < cut else 1 | |
| for index in range(num_layers) | |
| }) | |
| sizes = mapped_parameter_bytes(module, mapping, floating_bytes=2) | |
| score = max(sizes[index] / weight_budgets[index] for index in (0, 1)) | |
| if best is None or score < best[0]: | |
| best = (score, mapping, sizes, cut) | |
| if best is None: | |
| raise RuntimeError("The text encoder needs at least two decoder layers for this split.") | |
| _, mapping, sizes, cut = best | |
| return mapping, sizes, cut | |
| def main(): | |
| import argparse | |
| import gc | |
| import json | |
| import time | |
| from contextlib import contextmanager | |
| from importlib.metadata import PackageNotFoundError, version | |
| from pathlib import Path | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--prompt", | |
| default='A neon shop sign that reads "QWEN IMAGE 2.1", rainy night, reflections on wet pavement', | |
| ) | |
| parser.add_argument("--width", type=int, default=768) | |
| parser.add_argument("--height", type=int, default=768) | |
| parser.add_argument("--steps", type=int, default=40) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--output", default="t2i_bf16.png") | |
| parser.add_argument("--gpu0-blocks", type=int, default=16, | |
| help="Transformer blocks on GPU 0; the rest go to GPU 1 (default: 16).") | |
| args = parser.parse_args() | |
| if any(size <= 0 or size % 32 for size in (args.width, args.height)): | |
| parser.error("Width and height must be positive multiples of 32.") | |
| if args.steps <= 0: | |
| parser.error("Steps must be positive.") | |
| if args.gpu0_blocks <= 0: | |
| parser.error("--gpu0-blocks must be positive.") | |
| versions = {"script": "bf16-staged-2"} | |
| print(f"script: {versions['script']}", flush=True) | |
| missing = [] | |
| for name in ("torch", "torchvision", "transformers", "diffusers", "accelerate", "pillow"): | |
| try: | |
| versions[name] = version(name) | |
| print(f"{name}: {versions[name]}", flush=True) | |
| except PackageNotFoundError: | |
| missing.append(name) | |
| if missing: | |
| raise SystemExit("Missing dependencies. In the active environment run: uv pip install " + " ".join(missing)) | |
| import torch | |
| from accelerate import dispatch_model, init_empty_weights | |
| from accelerate.hooks import remove_hook_from_module | |
| from diffusers import ( | |
| AutoencoderKLQwenImage21, | |
| FlowMatchEulerDiscreteScheduler, | |
| QwenImage21Pipeline, | |
| QwenImage21Transformer2DModel, | |
| ) | |
| from transformers import Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLProcessor | |
| if torch.cuda.device_count() < 2: | |
| raise SystemExit("Two visible CUDA GPUs are required. Check CUDA_VISIBLE_DEVICES.") | |
| device = torch.device("cuda:0") | |
| dtype = torch.bfloat16 | |
| model_id = "Qwen/Qwen-Image-2.1" | |
| for index in (0, 1): | |
| with torch.cuda.device(index): | |
| if not torch.cuda.is_bf16_supported(): | |
| raise SystemExit(f"GPU {index} does not report BF16 support.") | |
| props = torch.cuda.get_device_properties(index) | |
| print(f"GPU {index}: {props.name}, {props.total_memory / 1024**3:.1f} GiB", flush=True) | |
| print(f"CUDA peer access 0 -> 1: {torch.cuda.can_device_access_peer(0, 1)}", flush=True) | |
| def sync(): | |
| for index in (0, 1): | |
| torch.cuda.synchronize(index) | |
| timings = {} | |
| peaks = {} | |
| @contextmanager | |
| def stage(label): | |
| sync() | |
| for index in (0, 1): | |
| torch.cuda.reset_peak_memory_stats(index) | |
| started = time.perf_counter() | |
| print(f"\n{label}...", flush=True) | |
| yield | |
| sync() | |
| timings[label] = time.perf_counter() - started | |
| peaks[label] = [torch.cuda.max_memory_allocated(i) / 1024**3 for i in (0, 1)] | |
| print(f"{label}: {timings[label]:.1f}s; peak allocated " | |
| f"GPU 0 {peaks[label][0]:.2f} GiB, GPU 1 {peaks[label][1]:.2f} GiB", flush=True) | |
| def verify_placement(module, label): | |
| sizes = {"cuda:0": 0, "cuda:1": 0} | |
| for name, parameter in module.named_parameters(): | |
| target = str(parameter.device) | |
| if target not in sizes: | |
| raise RuntimeError(f"{label} parameter {name} is on {target}; expected GPU-only placement.") | |
| sizes[target] += parameter.numel() * parameter.element_size() | |
| print(f"{label} weights: " + ", ".join( | |
| f"{target}={size / 1024**3:.2f} GiB" for target, size in sizes.items() | |
| ), flush=True) | |
| return sizes | |
| class StagedQwenImage21Pipeline(QwenImage21Pipeline): | |
| @property | |
| def _execution_device(self): | |
| # All pipeline-level tensors live here; Accelerate routes tensors | |
| # through the blocks on GPU 1 and brings model outputs back. | |
| return device | |
| overall_start = time.perf_counter() | |
| with stage("Load processor and scheduler"): | |
| pipe = StagedQwenImage21Pipeline( | |
| scheduler=FlowMatchEulerDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler"), | |
| processor=Qwen3VLProcessor.from_pretrained(model_id, subfolder="processor"), | |
| text_encoder=None, | |
| transformer=None, | |
| vae=None, | |
| ) | |
| def release_component(name): | |
| sync() | |
| module = getattr(pipe, name) | |
| remove_hook_from_module(module, recurse=True) | |
| setattr(pipe, name, None) | |
| del module | |
| gc.collect() | |
| for index in (0, 1): | |
| with torch.cuda.device(index): | |
| torch.cuda.empty_cache() | |
| print("After release: " + ", ".join( | |
| f"GPU {i} allocated {torch.cuda.memory_allocated(i) / 1024**3:.2f} GiB" for i in (0, 1) | |
| ), flush=True) | |
| with stage("Load BF16 text encoder across both GPUs"): | |
| encoder_config = Qwen3VLConfig.from_pretrained(model_id, subfolder="text_encoder") | |
| # Prompt encoding is one forward pass, so a generation KV cache is unnecessary. | |
| encoder_config.use_cache = False | |
| encoder_config.text_config.use_cache = False | |
| # Inspect shapes only: this creates no full-sized CPU or GPU weight tensors. | |
| with init_empty_weights(include_buffers=True): | |
| empty_encoder = Qwen3VLForConditionalGeneration(encoder_config) | |
| reserve_bytes = int(1.5 * 1024**3) | |
| weight_budgets = { | |
| index: max(1, torch.cuda.mem_get_info(index)[0] - reserve_bytes) | |
| for index in (0, 1) | |
| } | |
| encoder_map, planned_sizes, encoder_cut = text_encoder_device_map(empty_encoder, weight_budgets) | |
| num_encoder_layers = len(empty_encoder.model.language_model.layers) | |
| del empty_encoder | |
| gc.collect() | |
| for index in (0, 1): | |
| print(f"Text encoder plan: GPU {index} weights {planned_sizes[index] / 1024**3:.2f} GiB; " | |
| f"weight budget {weight_budgets[index] / 1024**3:.2f} GiB " | |
| "(1.5 GiB reserved for runtime)", flush=True) | |
| if planned_sizes[index] > weight_budgets[index]: | |
| raise RuntimeError( | |
| f"Insufficient free VRAM on GPU {index} for the planned BF16 encoder split. " | |
| "Close other GPU workloads and retry. No weights have been loaded yet." | |
| ) | |
| print(f"Encoder layers 0..{encoder_cut - 1}: GPU 0; " | |
| f"layers {encoder_cut}..{num_encoder_layers - 1}: GPU 1", flush=True) | |
| pipe.text_encoder = Qwen3VLForConditionalGeneration.from_pretrained( | |
| model_id, | |
| subfolder="text_encoder", | |
| config=encoder_config, | |
| dtype=dtype, | |
| device_map=encoder_map, | |
| low_cpu_mem_usage=True, | |
| ) | |
| print("Text encoder map:", pipe.text_encoder.hf_device_map, flush=True) | |
| verify_placement(pipe.text_encoder, "Text encoder") | |
| with stage("Encode prompt"), torch.inference_mode(): | |
| encoded = pipe.encode_prompt(prompt=args.prompt, device=device) | |
| prompt_embeds = encoded[0].detach().cpu() | |
| prompt_mask = None if encoded[1] is None else encoded[1].detach().cpu() | |
| del encoded | |
| with stage("Unload text encoder"): | |
| release_component("text_encoder") | |
| with stage("Load BF16 transformer across both GPUs"): | |
| config = QwenImage21Transformer2DModel.load_config(model_id, subfolder="transformer") | |
| num_layers = int(config["num_layers"]) | |
| mapping = transformer_device_map(num_layers, args.gpu0_blocks) | |
| pipe.transformer = QwenImage21Transformer2DModel.from_pretrained( | |
| model_id, | |
| subfolder="transformer", | |
| torch_dtype=dtype, | |
| device_map=mapping, | |
| low_cpu_mem_usage=True, | |
| ) | |
| # Explicitly preserve per-layer cache objects on their owning devices. | |
| # Some Diffusers versions don't forward the model's skip_keys to Accelerate. | |
| remove_hook_from_module(pipe.transformer, recurse=True) | |
| dispatch_model( | |
| pipe.transformer, | |
| device_map=mapping, | |
| main_device=0, | |
| skip_keys=["kv_cache", "layer_cache"], | |
| ) | |
| verify_placement(pipe.transformer, "Transformer") | |
| print(f"Blocks 0..{args.gpu0_blocks - 1}: GPU 0; " | |
| f"blocks {args.gpu0_blocks}..{num_layers - 1}: GPU 1", flush=True) | |
| with stage("Denoise"), torch.inference_mode(): | |
| packed_latents = pipe( | |
| prompt_embeds=prompt_embeds.to(device), | |
| prompt_embeds_mask=None if prompt_mask is None else prompt_mask.to(device), | |
| width=args.width, | |
| height=args.height, | |
| num_inference_steps=args.steps, | |
| generator=torch.Generator(device="cpu").manual_seed(args.seed), | |
| output_type="latent", | |
| use_kv_cache=True, | |
| ).images.detach().cpu() | |
| del prompt_embeds, prompt_mask | |
| with stage("Unload transformer"): | |
| release_component("transformer") | |
| with stage("Load BF16 VAE on GPU 0"): | |
| pipe.vae = AutoencoderKLQwenImage21.from_pretrained( | |
| model_id, | |
| subfolder="vae", | |
| torch_dtype=dtype, | |
| device_map={"": 0}, | |
| low_cpu_mem_usage=True, | |
| ) | |
| pipe.vae.enable_tiling() | |
| verify_placement(pipe.vae, "VAE") | |
| with stage("Decode image"), torch.inference_mode(): | |
| # Use the same unpacking and latent normalization as the original pipeline. | |
| latents = pipe._unpack_latents( | |
| packed_latents.to(device=device, dtype=dtype), | |
| args.height, args.width, pipe.vae_scale_factor, | |
| ) | |
| shape = (1, pipe.vae.config.z_dim, 1, 1, 1) | |
| mean = torch.tensor(pipe.vae.config.latents_mean, device=device, dtype=dtype).view(shape) | |
| std = torch.tensor(pipe.vae.config.latents_std, device=device, dtype=dtype).view(shape) | |
| decoded = pipe.vae.decode(latents * std + mean, return_dict=False)[0][:, :, 0] | |
| image = pipe.image_processor.postprocess(decoded, output_type="pil")[0] | |
| output = Path(args.output).expanduser() | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| image.save(output) | |
| timings["Total including loading"] = time.perf_counter() - overall_start | |
| print(f"\nSaved: {output.resolve()}", flush=True) | |
| for label, seconds in timings.items(): | |
| print(f" {label}: {seconds:.1f}s", flush=True) | |
| report_path = output.with_suffix(".timings.json") | |
| report_path.write_text(json.dumps({ | |
| "arguments": vars(args), | |
| "versions": versions, | |
| "seconds": timings, | |
| "peak_pytorch_allocated_gib": peaks, | |
| }, indent=2) + "\n") | |
| print(f"Timings: {report_path.resolve()}", flush=True) | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Qwen-Image-2.1 Quick Start requirements | |
| # https://github.com/QwenLM/Qwen-Image-2.1#requirements | |
| torch>=2.4.0 | |
| transformers>=5.17 | |
| diffusers @ git+https://github.com/huggingface/diffusers.git | |
| accelerate | |
| pillow | |
| # Required by Qwen3VLProcessor; omitted from the upstream Quick Start | |
| torchvision | |
| # Required for the dual-GPU script's 4-bit NF4 quantization | |
| bitsandbytes | |
| # The LD_LIBRARY_PATH / LD_PRELOAD workaround is handled by the Python script. | |
| # These are direct requirements, not a lockfile of the working environment. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment