P-Q-Image-2.1-DWD / docs /usage.md
sdiazlor's picture
fix: rename the model
85e2c6a
|
Raw History Blame Contribute Delete
12.7 kB
# pq_image_dwd: Qwen-Image-2.1-Turbo without the VAE decode
This repository reproduces DWD ("Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers",
[arXiv 2611.22287](https://arxiv.org/abs/2611.22287)) on
[Qwen-Image-2.1-Turbo](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo). A fine-tuned copy of the transformer's last
4 blocks and a small linear pixel head turn the hidden states of the last sampling step straight into an RGB image, so
the last Euler step and the VAE decode are never run. It contains the inference pipeline (text-to-image and image
editing), the weight export, a latency benchmark and CPU tests.
Built with Qwen.
## How it works
- **Sampling.** Qwen-Image-2.1-Turbo samples in 8 fixed steps. Steps 1-7 run on the stock model, unchanged: the same
noise, sigmas, timestep rounding, prefix KV cache and Euler update as the stock `QwenImage21Pipeline`, so every
latent up to step 8 is the stock pipeline's.
- **Last step.** At step 8 (sigma 0.414568) the stock prefix (the input embeddings and blocks 0-27) runs as
usual, without the KV cache. The trained tail then takes over: a copy of the last 4 blocks (28-31) with its own time embedding,
shared modulation and `norm_out`, on the whole joint sequence (text and condition-image tokens are attention keys).
- **Head.** A `Linear(4096 -> 768)` reads the `norm_out` rows of the target image. Each token becomes one 16x16 pixel
tile with 3 channels of normalized Oklab, which is converted to sRGB. No `proj_out`, no last Euler step, no VAE
decode.
- **Editing.** Condition images enter the prefix exactly as in `QwenImage21Pipeline` (Qwen3-VL image slots in the
prompt, VAE-encoded latents before the target). The head decodes only the target image's tokens. Editing needs the
VAE encoder, never the decoder.
- **Precision.** The stock model and the prefix run in bf16 with autocast off, like the stock pipeline. The tail runs
under bf16 autocast. Its Linear weights are stored in bf16 (autocast computes them in bf16 anyway) and its 8
attention RMSNorm weights in fp32, so the bf16 file computes exactly what fp32 weights compute under autocast.
## Results
### Fidelity to the stock VAE image
Same seed, same steps 1-7; the head image vs the stock pipeline's VAE image. 64 cases per set; higher PSNR and lower
LPIPS mean closer to the VAE image.
| Set | PSNR (dB) | LPIPS (VGG) | LPIPS (AlexNet) |
|---|---:|---:|---:|
| Text-to-image, 1 MP | 34.79 | 0.045 | 0.021 |
| Text-to-image, 2K | 35.93 | 0.046 | 0.018 |
| Editing, 1 MP | 35.30 | 0.048 | 0.029 |
| Editing, 2K | 36.50 | 0.057 | 0.033 |
This package reproduces the evaluated computation exactly: on 20 checks (8 text-to-image at 1 MP, 8 at 2K, 4 edits at
1 MP) its DWD images and VAE images were bit-identical to the reference implementation, with the bf16 release file.
### Speed and memory
Qwen-Image-2.1-Turbo on one NVIDIA B200, batch 1, 8 steps, bf16, text-to-image, end to end (prompt encoding, 8 steps,
the decode, until the uint8 image is on the host). Measured with `scripts/benchmark_latency.py`, which interleaves both
paths on the same GPU ([assets/benchmark.json](../assets/benchmark.json)).
| Mode | Resolution | With VAE decode | With DWD head | Saved | Speedup |
|---|---|---:|---:|---:|---:|
| eager | 1024 x 1024 | 767 ms | 696 ms | 67 ms | **1.10x** |
| eager | 2048 x 2048 | 3500 ms | 3213 ms | 282 ms | **1.09x** |
| `torch.compile` | 1024 x 1024 | 597 ms | 513 ms | 82 ms | **1.16x** |
| `torch.compile` | 2048 x 2048 | 2797 ms | 2500 ms | 293 ms | **1.12x** |
The VAE decode alone takes 72 ms at 1024 x 1024 and 283 ms at 2048 x 2048. The DWD last step (stock prefix without the
KV cache, tail, head and Oklab-to-sRGB) takes 87 ms and 407 ms eager, against 160 ms and 691 ms for the stock last step
with the VAE decode. Peak activation memory (eager) drops from 7.1 GB to 0.7 GB at 1024 x 1024 and from 28.2 GB to
2.7 GB at 2048 x 2048; the tail adds 1.95 GB of weights and the VAE decoder's 0.5 GB are not loaded. The diffusers
`QwenImage21Pipeline` object itself takes 796 ms and 3604 ms eager on the same GPU.
## Installation
Python 3.10+ and PyTorch 2.6+ (tested with 2.12.1). A CUDA GPU is needed for practical use: the base model is a
7.1B-parameter transformer and a Qwen3-VL text encoder (about 30.5 GB of bf16 weights together); the tail adds
1.95 GB, and the VAE decoder (0.5 GB) is not needed.
```bash
git clone https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD
cd P-Q-Image-2.1-DWD
pip install -e . # inference
pip install -e ".[dev]" # + tests
```
`diffusers` is pinned to 0.41.0 because the tail and the prefix forward use internals of
`QwenImage21Transformer2DModel`; `transformers` is pinned to 5.23.0, the version the Qwen3-VL prompt encoding was
tested with.
## Quickstart
```bash
python scripts/generate.py --prompt "a red fox in fresh snow at sunrise" --width 2048 --height 2048 --out fox.png
python scripts/generate.py --prompt "Add gently falling snow to the whole scene." --image photo.jpg --out snow.png
```
`--tail` takes a Hugging Face repo id (default `PrunaAI/P-Q-Image-2.1-DWD`), a `dwd_tail.safetensors` file, or a
directory holding it. The base model (`Qwen/Qwen-Image-2.1-Turbo`, override with `--base`) is downloaded on first use.
Other options: `--width`, `--height`, `--seed`, `--output-resolution` (condition images are resized to about this
squared, default 1024), `--device`, `--compile`, and `--compare`, which also writes the stock pipeline's image for the
same seed (VAE decode) as `<out>_vae.png`. Repeat `--prompt` for several images and `--image` for several condition
images.
### Python API
```python
from PIL import Image
from pq_image_dwd import DWDPipeline
pipe = DWDPipeline.from_pretrained("PrunaAI/P-Q-Image-2.1-DWD") # or a local file / directory
image = pipe("a red fox in fresh snow at sunrise", width=2048, height=2048, seed=0)
image.save("fox.png")
# several prompts (seeds 0, 1, ...), numpy output
images = pipe(["a lighthouse at dusk", "a bowl of ramen"], width=1344, height=768, seed=0, output_type="np")
# editing: one or more condition images; the output size defaults to about 1 MP at the last image's aspect
edited = pipe("Add gently falling snow to the whole scene.", image=Image.open("photo.jpg"), seed=0)
# the stock pipeline's image for the same seed, for comparison (loads the VAE decoder)
dwd, vae = pipe("a red fox in fresh snow at sunrise", width=1024, height=1024, seed=0, return_vae=True)
# torch.compile every transformer block (static shapes, one compile per resolution)
pipe.enable_compile()
```
`from_pretrained(tail, base="Qwen/Qwen-Image-2.1-Turbo", device=None, compile=False, load_vae=False)` loads the stock
transformer, the Qwen3-VL text encoder and the tail. The stock transformer is not modified; the tail is a separate
module of 0.98B parameters. The VAE is loaded on first use: its encoder for editing, its decoder only for
`return_vae=True`. To bring your own modules, use `DWDPipeline.from_components(transformer, tail, text_encoder,
scheduler=None, vae=None)`.
`__call__(prompt, image=None, width=None, height=None, seed=0, output_resolution=1024, output_type="pil",
return_vae=False, use_kv_cache=True)`:
- `output_type` is `"pil"`, `"np"` (uint8 HxWx3) or `"pt"` (uint8 tensor [H, W, 3]). `return_vae=True` returns
`(dwd, vae)`.
- The noise is drawn on the pipeline's device from `torch.Generator(device).manual_seed(seed)`, as the stock pipeline
does with a generator on the same device, so `return_vae=True` gives the stock pipeline's image for that seed: the
same final latents and the same VAE decode. Only the conversion to uint8 differs: it runs in fp32 here, while the
diffusers postprocessor runs it in bf16, so some pixels differ by one code value (and diffusers also returns the
VAE's alpha channel).
- Lower-level pieces: `encode(prompt, image=None, output_resolution=1024) -> Cond`, `generate(cond, h, w, seed,
dwd=True, vae=False)` on an `h x w` token grid (`h = height / 16`), `denoise`, `last_step_dwd`, `last_step_vae`.
### Supported sizes
Width and height must be multiples of 32. The tail was trained on about 1 MP (text-to-image and editing) and was
evaluated at about 1 MP (1024 x 1024, 1152 x 896, 896 x 1152, 1344 x 768, 768 x 1344) and at the model's 2K sizes
(2048 x 2048, 2528 x 1696, 1696 x 2528, 2752 x 1536, 1536 x 2752), for text-to-image and for edits with about 1 MP
condition images. Other sizes run but have not been evaluated.
### Limitations
- The 8-step turbo sampler only: the head was trained for its last step (sigma 0.414568).
- No classifier-free guidance and no negative prompt (the turbo model does not use them).
- RGB output only. The stock VAE decodes an alpha channel; the head does not.
- One image per call internally (a list of prompts runs one by one).
- LoRAs are untested. A LoRA that changes the last 4 blocks, the time embedding, the modulation or `norm_out` changes
weights the tail replaces at the last step, so it will not carry over to that step.
- The output is close to, not identical with, the stock VAE image for the same seed. The head is slightly softer
than the VAE in the finest texture.
## Latency benchmark
```bash
python scripts/benchmark_latency.py --sizes 1024x1024,2048x2048 --modes eager,compile --out benchmark.json
```
Times the stock VAE path and the DWD path interleaved on the same GPU and the same code (median of paired
differences with a bootstrap 95% CI), plus component timings and peak activation memory. `--stock-pipeline` also times
the diffusers `QwenImage21Pipeline` object itself. It first checks the DWD image against the VAE image (PSNR,
`--min-psnr`) and exits with status 1 if the tail looks broken.
## Weight export
```bash
python scripts/export_weights.py --src tail.safetensors --out dwd_tail.safetensors
```
Re-writes a tail file in the release layout (bf16 Linear weights, fp32 RMSNorm weights, metadata the pipeline checks
on load: format, base model, block count, steps, head sigma, head layout, Oklab constants) and verifies it against the
source. The loader also reads an fp32 tail file and gives the identical image.
## Tests
```bash
pip install -e ".[dev]"
pytest -q
```
The tests run on CPU with tiny random models and no downloads. They check that steps 1-7 are the stock pipeline's
denoising loop (with and without the KV cache, text-to-image and editing), that the prefix equals the stock forward's
hidden states, and that the bf16 tail gives exactly the head image of fp32 weights under bf16 autocast.
## Repository layout
```
dwd_tail.safetensors the DWD tail and head (Qwen RESEARCH LICENSE AGREEMENT, see LICENSE)
config.json tail format, sizes and checksum
src/pq_image_dwd/
pipeline.py DWDPipeline: text-to-image and editing without the VAE decode
model.py the tail (DWDTail) and the stock-prefix forward
weights.py tail file loading, checking and export
color.py normalized Oklab -> sRGB, head patch layout
schedule.py the turbo sampler sigmas and timestep rounding
encoders.py Qwen3-VL prompt encoder and VAE wrappers, model download
scripts/ generate, benchmark_latency, export_weights
tests/
docs/ usage.md
assets/ benchmark results and example images
```
## Acknowledgements
- Hansheng Chen, Shengqu Cai, Jan Ackermann, Rayhan Zirvi, Gordon Wetzstein, Xinchen Yan and Leonidas Guibas for
DWD.
- LakonLab's AsymFlow for the normalized Oklab colour encoding.
- The Qwen team for Qwen-Image-2.1-Turbo, and Hugging Face diffusers and transformers.
## Citation
If you use this code or the released weights, please cite the DWD paper:
```bibtex
@article{chen2026dwd,
title = {Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers},
author = {Chen, Hansheng and Cai, Shengqu and Ackermann, Jan and Zirvi, Rayhan and Wetzstein, Gordon
and Yan, Xinchen and Guibas, Leonidas},
journal = {arXiv preprint arXiv:2611.22287},
year = {2026}
}
```
and this repository:
```bibtex
@software{pruna2026pqimagedwd,
title = {P-Q-Image-2.1-DWD: Decoding Without a Decoder for Qwen-Image-2.1-Turbo},
author = {{Pruna AI}},
year = {2026},
version = {0.1.0},
url = {https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD}
}
```
## License
The weights (`dwd_tail.safetensors`) are a modification of Qwen-Image-2.1-Turbo and are under the Qwen RESEARCH
LICENSE AGREEMENT, see [LICENSE](../LICENSE) and [NOTICE](../NOTICE). The code in `src/`, `scripts/` and `tests/` is
under the Apache License 2.0, see [LICENSE-APACHE](../LICENSE-APACHE).