Text-to-Image
Pruna AI
English
qwen
qwen-image
image-generation
image-editing
decoder-free
vae-free
dwd
Run this model with HF Jobs
Run PrunaAI/P-Q-Image-2.1-DWD on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/PrunaAI/P-Q-Image-2.1-DWD on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use PrunaAI/P-Q-Image-2.1-DWD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Pruna AI
How to use PrunaAI/P-Q-Image-2.1-DWD with Pruna AI:
from pruna import PrunaModel model = PrunaModel.from_pretrained("PrunaAI/P-Q-Image-2.1-DWD") - Notebooks
- Google Colab
- Kaggle
Release P-Q-Image-2.1-Turbo-DWD
Browse filesFiles changed (41)
- .gitattributes+4
- .gitignoreAdded+31
- CITATION.cffAdded+60
- LICENSEAdded+55
- LICENSE-APACHEAdded+201
- NOTICEAdded+22
- README.mdAdded+365
- assets/P-Q-Image-2.1-Turbo-DWD.jpgAdded
- assets/benchmark.jsonAdded+143
- assets/examples/crop_edit_snow.pngAdded
- assets/examples/crop_fox.pngAdded
- assets/examples/crop_portrait.pngAdded
- assets/examples/crop_street.pngAdded
- assets/examples/edit_0.jpgAdded
- assets/examples/edit_1.jpgAdded
- assets/examples/edit_2.jpgAdded
- assets/examples/edit_3.jpgAdded
- assets/examples/examples.jsonAdded+138
- assets/examples/t2i_0.jpgAdded
- assets/examples/t2i_1.jpgAdded
- assets/examples/t2i_2.jpgAdded
- assets/examples/t2i_3.jpgAdded
- assets/examples/t2i_4.jpgAdded
- assets/examples/t2i_5.jpgAdded
- config.jsonAdded+25
- docs/usage.mdAdded+244
- pyproject.tomlAdded+46
- scripts/benchmark_latency.pyAdded+247
- scripts/export_weights.pyAdded+55
- scripts/generate.pyAdded+76
- src/pq_image_dwd/__init__.pyAdded+26
- src/pq_image_dwd/color.pyAdded+92
- src/pq_image_dwd/encoders.pyAdded+141
- src/pq_image_dwd/model.pyAdded+207
- src/pq_image_dwd/pipeline.pyAdded+307
- src/pq_image_dwd/schedule.pyAdded+38
- src/pq_image_dwd/weights.pyAdded+145
- tests/test_color_schedule.pyAdded+57
- tests/test_pipeline.pyAdded+250
- tests/test_weights.pyAdded+104
- tests/tiny.pyAdded+104
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textassets/**/*.png filter=lfs diff=lfs merge=lfs -textassets/**/*.jpg filter=lfs diff=lfs merge=lfs -textassets/**/*.jpeg filter=lfs diff=lfs merge=lfs -textassets/**/*.webp filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031# Python__pycache__/*.py[cod]*.egg-info/.eggs/build/dist/.venv/venv/
# Tools.pytest_cache/.mypy_cache/.ruff_cache/.ipynb_checkpoints/
# Data, checkpoints and outputs (local defaults of the scripts)/data//checkpoints//eval//outputs/*.pt*.safetensors!/dwd_tail.safetensors/benchmark.jsondwd*.png
# OS / editors.DS_Store.idea/.vscode/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960cff-version: 1.2.0message: "If you use this software or the released weights, please cite the DWD paper (the method) and this software. The code is Apache-2.0; the weights are under the Qwen RESEARCH LICENSE AGREEMENT."title: "P-Q-Image-2.1-Turbo-DWD: Decoding Without a Decoder for Qwen-Image-2.1-Turbo"type: softwareauthors: - name: "Pruna AI"license: Apache-2.0repository-code: "https://huggingface.co/PrunaAI/P-Q-Image-2.1-Turbo-DWD"version: 0.1.0keywords: - diffusion - text-to-image - qwen-image - image-editing - decoder-freepreferred-citation: type: article title: "Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers" authors: - family-names: Chen given-names: Hansheng - family-names: Cai given-names: Shengqu - family-names: Ackermann given-names: Jan - family-names: Zirvi given-names: Rayhan - family-names: Wetzstein given-names: Gordon - family-names: Yan given-names: Xinchen - family-names: Guibas given-names: Leonidas year: 2026 journal: "arXiv preprint arXiv:2611.22287" url: "https://arxiv.org/abs/2611.22287" identifiers: - type: other value: "arXiv:2611.22287"references: - type: article title: "Decoding Without a Decoder: Direct Pixel Prediction from Diffusion Transformers" authors: - family-names: Chen given-names: Hansheng - family-names: Cai given-names: Shengqu - family-names: Ackermann given-names: Jan - family-names: Zirvi given-names: Rayhan - family-names: Wetzstein given-names: Gordon - family-names: Yan given-names: Xinchen - family-names: Guibas given-names: Leonidas year: 2026 journal: "arXiv preprint arXiv:2611.22287" url: "https://arxiv.org/abs/2611.22287"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455Qwen RESEARCH LICENSE AGREEMENT
Qwen RESEARCH LICENSE AGREEMENT Release Date: September 20, 2026
By clicking to agree or by using or distributing any portion or element of the Qwen Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
1. Definitions a. This Qwen RESEARCH LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement. b. "We" (or "Us") shall mean Hangzhou Tongyi Laboratory Technology Co., Ltd. c. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use. d. "Third Parties" shall mean individuals or legal entities that are not under common control with us or you. e. "Qwen" shall mean the large language models, diffusion models, and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing distributed by us. f. "Materials" shall mean, collectively, our proprietary Qwen and Documentation (and any portion thereof) made available under this Agreement. g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files. h. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. i. "Non-Commercial" shall mean for research or evaluation purposes only.
2. Grant of Rights a. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under our intellectual property or other rights owned by us embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials FOR NON-COMMERCIAL PURPOSES ONLY. b. You shall not use the Materials for any commercial purpose without obtaining a separate commercial license from us. If you wish to use the Materials commercially, you shall request a license from us at model-business@notice.qwencloud.com.
3. RedistributionSubject to Section 2 (Grant of Rights), you may distribute copies or make the Materials, or derivative works thereof, available as part of a product or service that contains any of them, with or without modifications, and in Source or Object form, provided that you meet the following conditions: a. You shall give any other recipients of the Materials or derivative works a copy of this Agreement; b. You shall cause any modified files to carry prominent notices stating that you changed the files; c. You shall retain in all copies of the Materials that you distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved."; and d. You may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of your modifications, or for any such derivative works as a whole, provided your use, reproduction, and distribution of the work otherwise complies with the terms and conditions of this Agreement.
4. Rules of use a. The Materials may be subject to export controls or restrictions in China, the United States or other countries or regions. You shall comply with applicable laws and regulations in your use of the Materials. b. If you use the Materials or any outputs or results therefrom to create, train, fine-tune, or improve an AI model that is distributed or made available, you shall prominently display “Built with Qwen” or “Improved using Qwen” in the related product documentation. c. You shall not use "Qwen" as the primary name or identifier of any derivative works or products; reasonable descriptive use (e.g., "fine-tuned from Qwen Image") is permitted.
5. Intellectual Property a. We retain ownership of all intellectual property rights in and to the Materials and derivatives made by or for us. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by you, you are and will be the owner of such derivative works and modifications. b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of us, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials. c. If you commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against us or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by you, then all licenses granted to you under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.
6. Disclaimer of Warranty and Limitation of Liability a. We are not obligated to support, update, provide training for, or develop any further version of the Qwen Materials or to grant any license thereto. b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM. c. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, NO MATTER HOW IT’S CAUSED. d. You will defend, indemnify and hold harmless us from and against any claim by any third party arising out of or related to your use or distribution of the Materials.
7. Survival and Termination. a. The term of this Agreement shall commence upon your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. b. We may terminate this Agreement if you breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, you must delete and cease use of the Materials. Sections 6 and 8 shall survive the termination of this Agreement.
8. Governing Law and Jurisdiction. a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
9. Other Terms and Conditions. a. Any arrangements, understandings, or agreements regarding the Material not stated herein are separate from and independent of the terms and conditions of this Agreement. You shall request a separate license from us, if you use the Materials in ways not expressly agreed to in this Agreement. b. We shall not be bound by any additional or different terms or conditions communicated by you unless expressly agreed.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2026 Pruna AI
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213141516171819202122Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026 Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved.
The DWD tail and head weights are a modification of Qwen-Image-2.1-Turbo.
---
P-Q-Image-2.1-Turbo-DWDCopyright 2026 Pruna AI
dwd_tail.safetensors The DWD tail and head, based on Qwen-Image-2.1-Turbo by the Qwen team (https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo), under the Qwen RESEARCH LICENSE AGREEMENT, see LICENSE. A copy of the last 4 transformer blocks, the time embedding, the shared modulation and norm_out was fine-tuned, and a pixel head was added.
src/, scripts/ and tests/ The pq_image_dwd code, Copyright 2026 Pruna AI, under the Apache License 2.0, see LICENSE-APACHE. It does not contain model weights.
src/pq_image_dwd/color.py The normalized Oklab colour encoding follows AsymFlow's OklabColorEncoder (LakonLab), Apache License 2.0. The Oklab matrices are by Bjorn Ottosson (public domain).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365---license: otherlicense_name: qwen-researchlicense_link: LICENSEbase_model: Qwen/Qwen-Image-2.1-Turbobase_model_relation: finetunepipeline_tag: text-to-imagelanguage: - entags: - qwen - qwen-image - text-to-image - image-generation - image-editing - decoder-free - vae-free - dwd - pruna-ai---<!-- header start --><p align="center"> <img src="assets/P-Q-Image-2.1-Turbo-DWD.jpg" width="800"></p><!-- header end -->
<p align="center"> <a href="https://github.com/PrunaAI/pruna"> <img src="https://img.shields.io/badge/GitHub-PrunaAI-9334E9?style=plastic&logo=github&logoColor=white" alt="GitHub"> </a> <a href="https://twitter.com/PrunaAI"> <img src="https://img.shields.io/badge/Twitter%2FX-@PrunaAI-9334E9?style=plastic&logo=x&logoColor=white" alt="Twitter/X"> </a> <a href="https://www.linkedin.com/company/pruna-ai"> <img src="https://img.shields.io/badge/LinkedIn-PrunaAI-9334E9?style=plastic&logo=linkedin&logoColor=white" alt="LinkedIn"> </a> <a href="https://discord.com/invite/JFQmtFKCjd"> <img src="https://img.shields.io/badge/Discord-Join%20us-9334E9?style=plastic&logo=discord&logoColor=white" alt="Discord"> </a> <a href="https://dashboard.pruna.ai/login?utm_source=huggingface&utm_medium=org_card&utm_campaign=hf_traffic"> <img src="https://img.shields.io/badge/Performance%20Models-Try%20them%20now-9334E9?style=plastic&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MTEiIGhlaWdodD0iNDc3IiBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMjMuNzAzIDMwMC41MzJjLTEuODQyLS42NzQtNC4xNDItMS4wNTctNS43MDMtMi4wMjktMTIuNTU4LTcuODQ2LTguODM3LTI1LjE3MiA1LjI1NS0yOC4zNjFhLjY2LjY2IDAgMCAwIC4zNDgtLjIwMS42LjYgMCAwIDAgLjE1Ni0uMzZxNi40OS04MS45ODYgNjguNTc3LTEzNC42MjlhLjM0LjM0IDAgMCAwIC4wOTItLjEyNS4zMy4zMyAwIDAgMC0uMDI2LS4zLjMzLjMzIDAgMCAwLS4xMTItLjEwOGMtNC4xMTUtMi40OTctOC42NC00Ljc1LTEyLjM1My03LjQ0M2ExOTAgMTkwIDAgMCAxLTE4Ljc5NC0xNS41MjJjLTIuOTM2LTIuNzY4LTMuNzAzLTUuODkxLjU4LTcuNzdhLjUuNSAwIDAgMCAuMjgtLjYwOEM1MyA3NS45NSA0OC40MTcgNDguNTk5IDQ1LjUxOCAxOS42NXEtLjM5My0zLjg1Mi0uMjcxLTYuMzJhLjc1Ljc1IDAgMCAxIC4xMzQtLjQuNy43IDAgMCAxIC4zMjQtLjI1NXEyLjEwNC0uODQyIDUuODQ0LTEuNDMxYzU4LjExNC05LjEzNiAxMjcuMDA5IDguNDI1IDE0NC4zMDcgNzIuNjQ1cS4xMDMuMzY0LjE3OCAwIDUuMDk2LTI0LjA5NyA0LjYzOC00OC4xOTMtLjA0Ny0yLjc4NyAxLjg3OS00Ljc4OCAxMC40MDctMTAuOCAyNC43OTgtOC42ODdjNy40NzEgMS4wOTUgNy43NDIgNC42MzggNy4yMDkgMTEuMWEzMzQgMzM0IDAgMCAxLTExLjg4NCA2NC43MDYuMzg4LjM4OCAwIDAgMCAuMTgyLjQ0NC40LjQgMCAwIDAgLjE2NC4wNTFjOTIuNDIxIDguNDUzIDE1OC44NzUgNzkuNDg5IDE2NS4wODQgMTcxLjI3NGExIDEgMCAwIDAgLjEyOS40MjQuODMuODMgMCAwIDAgLjI5MS4yOTZjMy43NSAyLjE3IDYuMiAyLjIxNiA4Ljg1NSA2LjU5MiA1LjA2OCA4LjMzMiAxLjQ1IDIwLjQzMS04LjU5MyAyMi40N2ExLjcxIDEuNzEgMCAwIDAtMS4zNjUgMS40NjhxLTkuMTczIDc1LjM4My02NC43NjIgMTIzLjM3MWMtMjguNjIyIDI0LjcwNC02NS43NDQgMzkuNzQ5LTEwMy40NjQgNDIuMzMtMTAwLjM1OSA2Ljg2My0xODQuNDg2LTY1LjYyMi0xOTUuMDA1LTE2NS41N2EuOC44IDAgMCAwLS4xNTQtLjM5NS43NC43NCAwIDAgMC0uMzMzLS4yNU0xNTEuMzM4IDk3LjY0M2wxOS4wNjYgMTkuMzc1YS41LjUgMCAwIDAgLjE1LjEuNS41IDAgMCAwIC4xNzYuMDMxLjQzLjQzIDAgMCAwIC4zMTktLjE1cTEwLjg0Ny0xMi40NjUgNy40NDMtMjguMTU1Yy00LjUzNS0yMC44Ni0xOC41OTgtMzcuNjY0LTM3LjI3MS00OC4zODktMjEuMDY3LTEyLjY4OS00Ny44NjUtMTUuOTA1LTcyLjI4LTE0Ljg0cS0uNjE3LjAzLS4xNC40MjJsNjMuNDcyIDUzLjMyNmEuNC40IDAgMCAwIC4xNDQuMDcyLjM0LjM0IDAgMCAwIC4zMDEtLjA2OC4zLjMgMCAwIDAgLjA4OC0uMTI2IDQ3IDQ3IDAgMCAwIDMuMjgyLTEzLjA4MXEuMDIzLS4yMzMuMTI0LS40MzN0LjI2OC0uMzM0YzIuOTU1LTIuNDc4IDQuMTE1LjQ1OCA0LjY5NCAyLjg1MnEyLjMyIDkuNTM3LjE4NyAxOS4yNDRhMS40OCAxLjQ4IDAgMCAwIC40NCAxLjQwM3ptLTYuNTI2IDkuMjk1LTkuMDI0LTEwLjI3NmEuNy43IDAgMCAwLS4zNDMtLjIwNy44Ni44NiAwIDAgMC0uNDMzIDBxLTExLjY4IDMuMDIxLTIzLjExNC0uODIyYy01LjgxNi0zLjg1Mi0uNzU4LTUuNTE3IDIuNTktNS44MTZxNS45MTgtLjUzMyAxMS43MzUtMi41MDZhLjMuMyAwIDAgMCAuMTI3LS4wOC4zLjMgMCAwIDAgLjA3My0uMTMzLjM0LjM0IDAgMCAwIC4wMDEtLjE1NC4zNC4zNCAwIDAgMC0uMDctLjEzOGMtMTkuNDU5LTIxLjE1LTQwLjc2LTQwLjI0NS02Mi4yNzUtNTkuMjY0cS0uMzU2LS4zMTgtLjMxOC4xNWEzMDggMzA4IDAgMCAwIDguMzg3IDUxLjgwMmM0LjU5MiAxOC4zMDggMTMuNzU1IDM0LjE1NyAzMS44NDggNDEuODcycTI2LjI0NyAxMS4xODIgNTMuNzI5IDIuODMzYS41ODMuNTgzIDAgMCAwIC4yOTktLjg4OCAyMzUgMjM1IDAgMCAwLTEzLjIxMi0xNi4zNzNtNDUuMTI1IDQ5Ljc0NXEtMTIuNTk1IDEuMzE4LTIzLjQ0MS01LjU4M2MtMy4wNzctNC44OTkgMi4wNjYtOC41OTMgNS40NDItMTEuMTgzYS41ODQuNTg0IDAgMCAwIC4xODctLjcwMSA4LjQ2IDguNDYgMCAwIDAtMy40ODgtMy44NjIuODEuODEgMCAwIDAtLjgyMy4wMDljLTE2LjY5MSA5Ljk3Ny0zNC40ODUgMTAuNzgyLTUzLjE4NiA2Ljk2N3EtMS41Ny0uMzItMi44NTIuNjQ1LTYxLjQ1MSA0Ni4zNy02OS42NyAxMjMuOTEzLS42ODMgNi40MzMtMS44MDYgOC44MjdjLTIuOTQ1IDYuMzAyLTcuNzcgNy44NDUtMTQuMjIyIDkuNDcycS0uNDQ5LjExMyAwIC4yMzRjOS4yNzYgMi4zMSAxNC42OCA2LjE0MyAxNi4wNzQgMTYuNDAxIDguNDYyIDYyLjQ5IDQ4Ljk0IDExNy44NjQgMTEwLjM4MyAxMzguMzQxYTEwNCAxMDQgMCAwIDAgMTEuMDA2IDMuNTA3YzkyLjY0NSAyMy45MDkgMTgxLjIzMi0zMy42NjIgMjAyLjgwNC0xMjUuMDU0cTEuNjA5LTYuNzkgMy40NS0xOS4wODVjMS4xMDQtNy4zOTYgNS42OTUtMTIuMTE4IDEzLjE0Ny0xMy41NjguNDEyLS4wODQgMS45MDgtLjc1Ny4yODEtLjk5MS04LjA1MS0xLjE0MS0xMi4yNC02LjM4Ni0xMi45ODgtMTQuMTI4cS0xLjA3NS0xMS4yNS0yLjUxNi0xOS4wMzhjLTExLjc3Mi02My44OTItNTYuMzgzLTExNC41NzItMTE5LjI4NS0xMzEuNDZxLTE1LjEyLTMuODgtMzAuOTg3LTUuMjQ1YS4zODYuMzg2IDAgMCAwLS40MDIuMjUyIDE2OC42IDE2OC42IDAgMCAxLTExLjM1MiAyNC44NTRjLTQuMTMzIDcuNDA2LTguMTYzIDE1LjQ5NC0xNS43NTYgMTYuNDc2Ii8+PGNpcmNsZSBjeD0iMTQwLjA2NSIgY3k9IjI3My4wMyIgcj0iNTAuNjE4IiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iOS4yMDMiLz48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMTQ2Ljk2NyAyNDIuMDkyYzE1LjY3MiAwIDI4LjM3NiAxMy45NjMgMjguMzc2IDMxLjE4OHMtMTIuNzA0IDMxLjE4OS0yOC4zNzYgMzEuMTg5LTI4LjM3Ny0xMy45NjQtMjguMzc3LTMxLjE4OWMwLTIuNjI1LjI5Ny01LjE3NC44NTItNy42MSAxLjYwNyAzLjcyNyA1LjMxMyA2LjMzOCA5LjYyOSA2LjMzOCA1Ljc4OSAwIDEwLjQ4MS00LjY5MyAxMC40ODItMTAuNDgycy00LjY5My0xMC40ODEtMTAuNDgyLTEwLjQ4MWMtLjc2MSAwLTEuNTA0LjA4My0yLjIxOS4yMzcgNS4xMzktNS42NzYgMTIuMjUzLTkuMTkgMjAuMTE1LTkuMTkiLz48Y2lyY2xlIGN4PSIyNjkuOTMyIiBjeT0iMjczLjAzIiByPSI1MC42MTgiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI5LjIwMyIvPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik0yNzYuODM0IDI0Mi4wOTJjMTUuNjcyIDAgMjguMzc2IDEzLjk2MyAyOC4zNzYgMzEuMTg4cy0xMi43MDQgMzEuMTg5LTI4LjM3NiAzMS4xODktMjguMzc3LTEzLjk2NC0yOC4zNzctMzEuMTg5YzAtMi42MjUuMjk3LTUuMTc0Ljg1My03LjYxIDEuNjA2IDMuNzI3IDUuMzEyIDYuMzM4IDkuNjI4IDYuMzM4IDUuNzg5IDAgMTAuNDgyLTQuNjkzIDEwLjQ4Mi0xMC40ODJzLTQuNjkzLTEwLjQ4MS0xMC40ODItMTAuNDgxYy0uNzYxIDAtMS41MDQuMDgzLTIuMjE5LjIzNyA1LjEzOS01LjY3NiAxMi4yNTQtOS4xOSAyMC4xMTUtOS4xOSIvPjxwYXRoIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSI5LjIwMyIgZD0iTTE3Ny4xMzUgMzQ1LjMyOGMuODk5LS4yNCAyLjgwMS0uMTk3IDYuMzA0LjQ2NCA2LjMxMSAxLjE5IDE2LjU4NSA0LjIyMSAyNi4xMjIgNC4yMjEgOS40NTIgMCAxNy4xMTgtMS45MjYgMjEuMzgzLTIuNjAzLjc3LS4xMjMgMS4zODUtLjE5OSAxLjg3OC0uMjM3LS4zNCAxMy44NDMtMTIuODkzIDI3LjcxLTI3Ljg2OCAyNy43MS0xNS4xNzIgMC0yNy44NzYtMTMuODM1LTI3Ljg3Ni0yOC44MTEgMC0uMzU3LjAyOS0uNTk2LjA1Ny0uNzQ0WiIvPjwvc3ZnPg==" alt="Performance Models"> </a></p><div align="center">
<h1 style="color: #9334E9;">⚡ P-Q-Image-2.1-Turbo-DWD</h1>
<h2>Qwen-Image-2.1-Turbo without the VAE decode</h2>
<h3> <span style="color: #9334E9;">No VAE decode</span> · <span style="color: #9334E9;">Up to 1.16x faster</span> · <span style="color: #9334E9;">24 GB less memory at 2K</span> · Text-to-image and image editing</h3>
</div>
**Built with Qwen.**
**P-Q-Image-2.1-Turbo-DWD** is a decoder-free pixel head for[`Qwen/Qwen-Image-2.1-Turbo`](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo). At the last of the model's 8sampling steps, a fine-tuned copy of the transformer's last 4 blocks and a small linear head write the image's pixelsdirectly, so the last Euler step and the VAE decode never run. Steps 1 to 7 are the stock model, unchanged. It is ourreplication of DWD, *Decoding Without a Decoder* by Chen et al.([arXiv 2611.22287](https://arxiv.org/abs/2611.22287)), on Qwen-Image-2.1-Turbo.
This repository holds the weights and the `pq_image_dwd` Python package for text-to-image and image editing. ForComfyUI, see [PrunaAI/P-Q-Image-2.1-Turbo-DWD-Comfy](https://huggingface.co/PrunaAI/P-Q-Image-2.1-Turbo-DWD-Comfy).
| | ||---|---|| **Tasks** | Text-to-image and image editing (one or more condition images) || **Sampling** | The Turbo model's 8 steps, no CFG; the head replaces the last step || **Resolution** | Trained at about 1 MP; evaluated at about 1 MP and at the model's 2K sizes || **Weights** | `dwd_tail.safetensors`: 0.98B parameters, 1.95 GB (bf16) || **VAE** | Decoder not needed; the encoder is used for editing only |
## Quickstart
Needs a **CUDA GPU**. The base model is downloaded from[`Qwen/Qwen-Image-2.1-Turbo`](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo) on first use (bf16 transformer14.2 GB and text encoder 16.3 GB); the head adds 1.95 GB.
```bashGIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/PrunaAI/P-Q-Image-2.1-Turbo-DWDcd P-Q-Image-2.1-Turbo-DWDpip install -e .```
The package pins `diffusers==0.41.0` and `transformers==5.23.0`, the versions it was tested with, and needsPyTorch 2.6 or newer (tested with 2.12.1).
```pythonfrom PIL import Imagefrom pq_image_dwd import DWDPipeline
pipe = DWDPipeline.from_pretrained("PrunaAI/P-Q-Image-2.1-Turbo-DWD") # base: Qwen/Qwen-Image-2.1-Turbo
# Text-to-imageimage = pipe("a red fox standing in fresh snow at sunrise", width=2048, height=2048, seed=0)image.save("fox.png")
# Image editingedited = pipe("Add gently falling snow to the whole scene.", image=Image.open("photo.jpg"), seed=0)edited.save("snow.png")
# The stock VAE image for the same seed, for comparison (loads the VAE decoder)dwd, vae = pipe("a red fox standing in fresh snow at sunrise", seed=0, return_vae=True)
# Optional: torch.compile the transformer blocks (one compile per resolution)pipe.enable_compile()```
Or from the command line:
```bashpython scripts/generate.py --prompt "a red fox standing in fresh snow at sunrise" --width 2048 --height 2048 --out fox.pngpython scripts/generate.py --prompt "Add gently falling snow to the whole scene." --image photo.jpg --out snow.png```
Add `--compare` to also write the stock VAE image as `<out>_vae.png`. Width and height must be multiples of 32.Full options, the latency benchmark, the weight export and the tests are described in [docs/usage.md](docs/usage.md).
## Examples
Stock Qwen-Image-2.1-Turbo with its VAE decode next to P-Q-Image-2.1-Turbo-DWD, with the same prompt and seed. Panelsare downscaled; the PSNR in each caption compares the two full-size images. Prompts, sizes and seeds are in[assets/examples/examples.json](assets/examples/examples.json).
### Text-to-image at 2K

*"a close-up portrait of an elderly fisherman with a grey beard, soft window light, 85mm photo", 2048 × 2048, 34.7 dB*

*"bird of paradise flower", 2528 × 1696, 39.7 dB*
<table> <tr> <td width="55%"><img src="assets/examples/t2i_2.jpg" alt="Red fox in snow, VAE decode vs DWD head" width="100%"></td> <td width="45%"><img src="assets/examples/t2i_4.jpg" alt="Futuristic city street after rain, VAE decode vs DWD head" width="100%"></td> </tr> <tr> <td><em>"a red fox standing in fresh snow at sunrise, professional wildlife photograph", 1696 × 2528, 33.2 dB</em></td> <td><em>"a futuristic city street after rain with neon reflections, cinematic film still", 1536 × 2752, 35.4 dB</em></td> </tr></table>

*"a purple and white ice cream shop with a purple and white striped awning", 2752 × 1536, 34.7 dB*

*"a stone wall with plants and flowers in it", 2048 × 2048, 29.7 dB: dense fine texture is where the head differs most*
### Image editing at 1 MP
Input, stock VAE image and DWD head image. The input images were generated with the stock model.

*"Turn this photo into a watercolor painting with soft washes and visible paper texture.", 1344 × 768, 31.2 dB*

*"Make it look like a faded vintage 1970s photograph.", 1152 × 896, 33.3 dB*

*"Add a small red hot-air balloon in the upper part of the image.", 1024 × 1024, 31.3 dB*

*"Add gently falling snow to the whole scene.", 896 × 1152, 33.0 dB*
### 1:1 crops
512 × 512 pixel crops at full resolution, stock VAE decode (left) vs DWD head (right).
<table> <tr> <td width="50%"><img src="assets/examples/crop_portrait.png" alt="Portrait crop" width="100%"></td> <td width="50%"><img src="assets/examples/crop_fox.png" alt="Fox fur crop" width="100%"></td> </tr> <tr> <td width="50%"><img src="assets/examples/crop_street.png" alt="City street crop" width="100%"></td> <td width="50%"><img src="assets/examples/crop_edit_snow.png" alt="Snow edit crop" width="100%"></td> </tr></table>
## Benchmark
### Speed
One NVIDIA B200, bf16, batch size 1, 8 steps, text-to-image. End to end: prompt encoding, the 8 steps and the decode,until the uint8 image is on the host. Both paths run interleaved on the same GPU with the same code; median of 10runs, and the saving is the median of paired differences with a bootstrap 95% interval. PyTorch 2.12.1 (CUDA 13.0),diffusers 0.41.0, transformers 5.23.0. Measured with[scripts/benchmark_latency.py](scripts/benchmark_latency.py); raw results in[assets/benchmark.json](assets/benchmark.json).
| Mode | Resolution | With VAE decode | P-Q-Image-2.1-Turbo-DWD | Saved (95% CI) | Speedup ||---|---|---:|---:|---:|---:|| eager | 1024 × 1024 | 767 ms | 696 ms | 67 ms (58–80) | **1.10x** || eager | 2048 × 2048 | 3500 ms | 3213 ms | 282 ms (273–298) | **1.09x** || `torch.compile` | 1024 × 1024 | 597 ms | 513 ms | 82 ms (78–88) | **1.16x** || `torch.compile` | 2048 × 2048 | 2797 ms | 2500 ms | 293 ms (290–310) | **1.12x** |
`torch.compile` compiles every transformer block (stock and tail); the VAE runs eager. The VAE decode alone takes72 ms at 1024 × 1024 and 283 ms at 2048 × 2048. The DWD last step takes 87 ms and 407 ms (eager), against 160 ms and691 ms for the stock last step plus the VAE decode. For reference, the diffusers `QwenImage21Pipeline` itself takes796 ms and 3604 ms (eager) on the same GPU.
### Memory
Peak activation memory during one text-to-image run (peak allocated minus the resident weights), same setup:
| Mode | Resolution | With VAE decode | P-Q-Image-2.1-Turbo-DWD ||---|---|---:|---:|| eager | 1024 × 1024 | 7.06 GB | **0.69 GB** || eager | 2048 × 2048 | 28.19 GB | **2.71 GB** || `torch.compile` | 1024 × 1024 | 9.21 GB | **2.53 GB** || `torch.compile` | 2048 × 2048 | 36.78 GB | **10.09 GB** |
Resident weights: transformer 14.23 GB and text encoder 16.29 GB (both needed either way), plus 1.95 GB for thehead; the 0.52 GB VAE decoder is not loaded (editing loads the 0.16 GB VAE encoder). Net, the peak at 2048 × 2048eager is about 24 GB lower.
### Fidelity to the stock VAE image
Same prompt, seed and steps 1 to 7; the DWD image compared with the stock VAE image. 64 cases per set; the edit setsare edits of real photos. Higher PSNR and lower LPIPS mean closer to the VAE image.
| Set | PSNR ↑ | LPIPS (VGG) ↓ | LPIPS (AlexNet) ↓ ||---|---:|---:|---:|| Text-to-image, 1 MP | 34.79 dB | 0.045 | 0.021 || Text-to-image, 2K | 35.93 dB | 0.046 | 0.018 || Editing, 1 MP | 35.30 dB | 0.048 | 0.029 || Editing, 2K | 36.50 dB | 0.057 | 0.033 |
Colour and tone stay with the VAE image; the main difference is in the finest texture, where the head is slightlysofter.
## How it works
- **Steps 1 to 7** run on the stock Qwen-Image-2.1-Turbo, unchanged: the same noise, sigmas, prefix KV cache and Euler updates as the stock pipeline, so every latent up to the last step is the stock one.- **Last step.** The stock input embeddings and first 28 blocks run as usual. A fine-tuned copy of the last 4 blocks, with its own time embedding, modulation and output norm, takes over on the whole sequence (text and condition-image tokens included).- **Head.** A `Linear(4096 → 768)` turns each image token into a 16 × 16 pixel tile in normalized Oklab, which is converted to sRGB. No output projection, no last Euler step, no VAE decode.- **Editing.** Condition images enter exactly as in the stock pipeline (VAE-encoded latents and Qwen3-VL image tokens), so editing needs the VAE encoder but never the decoder.- **Training.** About 18,000 runs of the stock model at about 1 MP (16,000 text-to-image and 2,000 edits), with the stock VAE image of each run as the target. The released weights are an EMA, stored in bf16; they give exactly the images of the full-precision weights under bf16 autocast.
## Limitations
- **Close to, not identical with, the VAE image.** The head is slightly softer than the VAE in the finest texture; dense texture (stone, fur, foliage) differs most.- **Heavy restyles can drift further.** Edits that re-texture the whole image strongly scored lower than the averages above in our spot checks (about 27 to 28 dB on crisp generated inputs).- **RGB only.** The head outputs no alpha channel, so there is no transparency output.- **Trained sizes.** Trained at about 1 MP and evaluated at 1024 × 1024, 1152 × 896, 896 × 1152, 1344 × 768, 768 × 1344 and at 2048 × 2048, 2528 × 1696, 1696 × 2528, 2752 × 1536, 1536 × 2752. Other sizes run but were not evaluated. Width and height must be multiples of 32.- **Turbo sampler only.** The head is trained for the last of the 8 Turbo steps. No CFG and no negative prompt.- **LoRAs are untested.** A LoRA on the last 4 blocks, the time embedding, the modulation or the output norm will not carry over to the last step.- **Benchmarked on one B200** with bf16 and batch size 1; speed and memory vary with hardware, resolution, batch size and software.
## What this is not
- Not a standalone model. It needs the `Qwen/Qwen-Image-2.1-Turbo` base weights.- Not a faster transformer. All 8 steps still run through the transformer; the saving is mainly the VAE decode.- Not a VAE decoder for other models or for arbitrary latents.- Not a drop-in for the stock diffusers `QwenImage21Pipeline`; use `DWDPipeline` from this repository, or the [ComfyUI version](https://huggingface.co/PrunaAI/P-Q-Image-2.1-Turbo-DWD-Comfy), whose images are close to, but not identical with, this package's.
## License
The end model is based on Qwen-Image-2.1-Turbo.
P-Q-Image-2.1-Turbo-DWD is a derivative of Qwen-Image-2.1-Turbo and its weights (`dwd_tail.safetensors`) aredistributed under the **Qwen RESEARCH LICENSE AGREEMENT**, see [LICENSE](LICENSE) and [NOTICE](NOTICE). Review its userestrictions before using or redistributing the weights.
The code in `src/`, `scripts/` and `tests/` is released under the Apache License 2.0, see[LICENSE-APACHE](LICENSE-APACHE).
Qwen is licensed under the Qwen RESEARCH LICENSE AGREEMENT, Copyright (c) 2026Hangzhou Tongyi Laboratory Technology Co., Ltd. All Rights Reserved.
## Citation
If you use this model, please cite the DWD paper and this release.
```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}}
@software{pruna2026pqimagedwd, title = {P-Q-Image-2.1-Turbo-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-Turbo-DWD}}```
## What's next?
- **Use P-Q-Image-2.1-Turbo-DWD to generate and edit images with Qwen-Image-2.1-Turbo without the VAE decode.**- Compress your own models with [Pruna](https://github.com/PrunaAI/pruna) and give us a ��️ for more efficiency!- Want to use our optimized image models right away? Check [P-Image-Ideogram](https://www.pruna.ai/p-image-ideogram) and [P-Image-Edit](https://www.pruna.ai/p-image-edit).
<style>.model-button { display: inline-flex; flex-direction: row; justify-content: center; align-items: center; gap: 8px;
padding: 8px 20px; border: none; border-radius: 8px;
background: #9334e9; color: #ffffff;
font-size: 14px; font-weight: 400; line-height: 1; text-decoration: none; white-space: nowrap; cursor: pointer;
box-sizing: border-box; overflow: visible; opacity: 1;}</style>
<a href="https://dashboard.pruna.ai/login?utm_source=huggingface&utm_medium=model_card&utm_campaign=hf_traffic" class="model-button">Try our models</a>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143{ "description": "Qwen-Image-2.1-Turbo text-to-image, batch 1, 8 steps, bf16, one GPU. 'vae': last step through the stock transformer + Euler update + VAE decode (the stock pipeline's computation); 'dwd': last step through the stock prefix + DWD tail + head. End-to-end = prompt encode to uint8 image on the host; median of interleaved runs. saved_ms: median of paired differences (bootstrap 95% CI). stock_pipeline: the diffusers QwenImage21Pipeline object (output_type pil). peak_activation_gb: peak allocated during one run minus resident weights. compile: torch.compile of every transformer block (stock and tail), VAE eager.", "script": "scripts/benchmark_latency.py --sizes 1024x1024,2048x2048 --modes eager,compile --reps 10 --stock-pipeline", "gpu": "NVIDIA B200", "torch": "2.12.1+cu130", "batch": 1, "steps": 8, "dtype": "bfloat16", "task": "text-to-image", "weights_gb": { "transformer": 14.23, "text_encoder": 16.29, "vae_decoder": 0.518, "vae_encoder": 0.157, "dwd_tail": 1.955 }, "diffusers": "0.41.0", "transformers": "5.23.0", "psnr_dwd_vs_vae": [ 35.26, 35.36 ], "modes": { "eager": { "1024x1024": { "width": 1024, "height": 1024, "reps": 10, "e2e_ms": { "vae": 767.35, "dwd": 696.07, "stock_pipeline": 796.02 }, "saved_ms": 66.67, "saved_ms_ci95": [ 58.0, 80.11 ], "speedup": 1.102, "components_ms": { "encode": 24.17, "steps_1_7": 580.63, "last_dwd": 87.38, "last_vae": 160.29, "vae_decode": 71.89 }, "peak_activation_gb": { "vae": 7.057, "dwd": 0.688 }, "last_step_saved_ms": 72.91, "peak_activation_saved_gb": 6.369 }, "2048x2048": { "width": 2048, "height": 2048, "reps": 10, "e2e_ms": { "vae": 3500.25, "dwd": 3213.3, "stock_pipeline": 3604.09 }, "saved_ms": 282.04, "saved_ms_ci95": [ 273.2, 297.66 ], "speedup": 1.089, "components_ms": { "encode": 25.07, "steps_1_7": 2787.13, "last_dwd": 406.66, "last_vae": 690.62, "vae_decode": 282.61 }, "peak_activation_gb": { "vae": 28.189, "dwd": 2.71 }, "last_step_saved_ms": 283.96, "peak_activation_saved_gb": 25.479 } }, "compile": { "1024x1024": { "width": 1024, "height": 1024, "reps": 10, "e2e_ms": { "vae": 596.98, "dwd": 512.85 }, "saved_ms": 81.89, "saved_ms_ci95": [ 77.97, 87.82 ], "speedup": 1.164, "components_ms": { "encode": 25.33, "steps_1_7": 421.72, "last_dwd": 64.97, "last_vae": 149.97, "vae_decode": 75.33 }, "peak_activation_gb": { "vae": 9.206, "dwd": 2.533 }, "last_step_saved_ms": 85.0, "peak_activation_saved_gb": 6.673 }, "2048x2048": { "width": 2048, "height": 2048, "reps": 10, "e2e_ms": { "vae": 2797.32, "dwd": 2499.54 }, "saved_ms": 292.61, "saved_ms_ci95": [ 289.5, 309.97 ], "speedup": 1.119, "components_ms": { "encode": 25.16, "steps_1_7": 2156.08, "last_dwd": 315.91, "last_vae": 610.96, "vae_decode": 282.65 }, "peak_activation_gb": { "vae": 36.779, "dwd": 10.09 }, "last_step_saved_ms": 295.05, "peak_activation_saved_gb": 26.689 } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138{ "t2i_2k": [ { "file": "t2i_0.jpg", "prompt": "a close-up portrait of an elderly fisherman with a grey beard, soft window light, 85mm photo", "width": 2048, "height": 2048, "seed": 2000, "psnr_db": 34.71, "lpips_vgg": 0.04676 }, { "file": "t2i_1.jpg", "prompt": "bird of paradise flower", "width": 2528, "height": 1696, "seed": 2001, "psnr_db": 39.67, "lpips_vgg": 0.02724 }, { "file": "t2i_2.jpg", "prompt": "a red fox standing in fresh snow at sunrise, professional wildlife photograph", "width": 1696, "height": 2528, "seed": 2002, "psnr_db": 33.2, "lpips_vgg": 0.0474 }, { "file": "t2i_3.jpg", "prompt": "a purple and white ice cream shop with a purple and white striped awning", "width": 2752, "height": 1536, "seed": 2003, "psnr_db": 34.66, "lpips_vgg": 0.04545 }, { "file": "t2i_4.jpg", "prompt": "a futuristic city street after rain with neon reflections, cinematic film still", "width": 1536, "height": 2752, "seed": 2004, "psnr_db": 35.37, "lpips_vgg": 0.04529 }, { "file": "t2i_5.jpg", "prompt": "a stone wall with plants and flowers in it", "width": 2048, "height": 2048, "seed": 2005, "psnr_db": 29.67, "lpips_vgg": 0.06644 } ], "edit_1mp": [ { "file": "edit_0.jpg", "instruction": "Turn this photo into a watercolor painting with soft washes and visible paper texture.", "width": 1344, "height": 768, "seed": 3000, "psnr_db": 31.17, "lpips_vgg": 0.05884 }, { "file": "edit_1.jpg", "instruction": "Make it look like a faded vintage 1970s photograph.", "width": 1152, "height": 896, "seed": 3001, "psnr_db": 33.25, "lpips_vgg": 0.05025 }, { "file": "edit_2.jpg", "instruction": "Add a small red hot-air balloon in the upper part of the image.", "width": 1024, "height": 1024, "seed": 3002, "psnr_db": 31.28, "lpips_vgg": 0.05034 }, { "file": "edit_3.jpg", "instruction": "Add gently falling snow to the whole scene.", "width": 896, "height": 1152, "seed": 3003, "psnr_db": 33.0, "lpips_vgg": 0.06011 } ], "crops": [ { "file": "crop_portrait.png", "source": "t2i2k_0", "crop_xy": [ 768, 665 ], "crop_size": 512, "psnr_db_crop": 29.86 }, { "file": "crop_fox.png", "source": "t2i2k_2", "crop_xy": [ 592, 1008 ], "crop_size": 512, "psnr_db_crop": 26.14 }, { "file": "crop_street.png", "source": "t2i2k_4", "crop_xy": [ 512, 1120 ], "crop_size": 512, "psnr_db_crop": 39.88 }, { "file": "crop_edit_snow.png", "source": "edit1mp_3", "crop_xy": [ 192, 320 ], "crop_size": 512, "psnr_db_crop": 31.93 } ]}12345678910111213141516171819202122232425{ "format": "pq-image-dwd-tail", "format_version": 1, "library": "pq_image_dwd", "base_model": "Qwen/Qwen-Image-2.1-Turbo", "file": "dwd_tail.safetensors", "k": 4, "steps": 8, "head_step": 8, "head_sigma": 0.414568, "patch": 16, "head_out": 768, "head_layout": "(c,p1,p2)", "color": "oklab_norm", "oklab_mean": [0.56, 0.0, 0.01], "oklab_std": 0.16, "weights": "ema", "dtype": "bfloat16", "float32_tensors": ["blocks.*.attn.norm_q.weight", "blocks.*.attn.norm_k.weight"], "compute": "bf16-autocast", "n_tensors": 42, "n_params": 977274624, "bytes": 1954555904, "sha256": "05a0088ffe90d0c479633e42aa59cdbfa1efac5792a3bde79601b4eb63d7551c"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244# 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 last4 blocks and a small linear pixel head turn the hidden states of the last sampling step straight into an RGB image, sothe last Euler step and the VAE decode are never run. It contains the inference pipeline (text-to-image and imageediting), 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 lowerLPIPS 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 at1 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 bothpaths 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 theKV cache, tail, head and Oklab-to-sRGB) takes 87 ms and 407 ms eager, against 160 ms and 691 ms for the stock last stepwith 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 to2.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 a7.1B-parameter transformer and a Qwen3-VL text encoder (about 30.5 GB of bf16 weights together); the tail adds1.95 GB, and the VAE decoder (0.5 GB) is not needed.
```bashgit clone https://huggingface.co/PrunaAI/P-Q-Image-2.1-Turbo-DWDcd P-Q-Image-2.1-Turbo-DWDpip install -e . # inferencepip 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 wastested with.
## Quickstart
```bashpython scripts/generate.py --prompt "a red fox in fresh snow at sunrise" --width 2048 --height 2048 --out fox.pngpython 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-Turbo-DWD`), a `dwd_tail.safetensors` file, or adirectory 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 thissquared, default 1024), `--device`, `--compile`, and `--compare`, which also writes the stock pipeline's image for thesame seed (VAE decode) as `<out>_vae.png`. Repeat `--prompt` for several images and `--image` for several conditionimages.
### Python API
```pythonfrom PIL import Imagefrom pq_image_dwd import DWDPipeline
pipe = DWDPipeline.from_pretrained("PrunaAI/P-Q-Image-2.1-Turbo-DWD") # or a local file / directoryimage = 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 outputimages = 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 aspectedited = 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 stocktransformer, the Qwen3-VL text encoder and the tail. The stock transformer is not modified; the tail is a separatemodule 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 wasevaluated 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 MPcondition 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
```bashpython 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 paireddifferences with a bootstrap 95% CI), plus component timings and peak activation memory. `--stock-pipeline` also timesthe 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
```bashpython 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 checkson load: format, base model, block count, steps, head sigma, head layout, Oklab constants) and verifies it against thesource. The loader also reads an fp32 tail file and gives the identical image.
## Tests
```bashpip 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'sdenoising loop (with and without the KV cache, text-to-image and editing), that the prefix equals the stock forward'shidden 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 checksumsrc/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 downloadscripts/ generate, benchmark_latency, export_weightstests/docs/ usage.mdassets/ 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-Turbo-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-Turbo-DWD}}```
## License
The weights (`dwd_tail.safetensors`) are a modification of Qwen-Image-2.1-Turbo and are under the Qwen RESEARCHLICENSE AGREEMENT, see [LICENSE](../LICENSE) and [NOTICE](../NOTICE). The code in `src/`, `scripts/` and `tests/` isunder the Apache License 2.0, see [LICENSE-APACHE](../LICENSE-APACHE).12345678910111213141516171819202122232425262728293031323334353637383940414243444546[build-system]requires = ["setuptools>=77"]build-backend = "setuptools.build_meta"
[project]name = "p-q-image-2-1-turbo-dwd"version = "0.1.0"description = "Decoding Without a Decoder (DWD) for Qwen-Image-2.1-Turbo: a pixel head that replaces the last step and the VAE decode"readme = "README.md"# the code (src/, scripts/, tests/) is Apache-2.0; the weights in this repository are under the Qwen RESEARCH# LICENSE AGREEMENT (LICENSE). See NOTICE.license = "Apache-2.0"license-files = ["LICENSE-APACHE", "NOTICE"]authors = [{ name = "Pruna AI" }]requires-python = ">=3.10"keywords = ["diffusion", "qwen-image", "text-to-image", "image-editing", "vae-free", "dwd"]classifiers = [ "Programming Language :: Python :: 3", "Operating System :: OS Independent", "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering :: Artificial Intelligence",]dependencies = [ "torch>=2.6", "diffusers==0.41.0", # the tail and the prefix forward use QwenImage21Transformer2DModel internals "transformers==5.23.0", # Qwen3-VL prompt encoder, as tested "accelerate", "safetensors", "huggingface-hub", "pillow", "numpy",]
[project.optional-dependencies]dev = ["pytest"]
[project.urls]Paper = "https://arxiv.org/abs/2611.22287""Base model" = "https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo"
[tool.setuptools.packages.find]where = ["src"]
[tool.pytest.ini_options]testpaths = ["tests"]pythonpath = ["src"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247#!/usr/bin/env python"""Latency and peak memory: Qwen-Image-2.1-Turbo with the VAE decode vs the DWD head, same GPU, same code.
Both paths: batch 1, text-to-image, 8 steps, no CFG, prompt encode -> 7 stock transformer steps (prefix KV cache, asthe stock pipeline) -> last step -> uint8 image on the host. VAE path: last step through the stock transformer, Euler update to t = 0, VAE decode (this is the stock QwenImage21Pipeline computation; --stock-pipeline also times the diffusers pipeline object itself) DWD path: last step through the stock prefix (blocks 1-28, no KV cache), the DWD tail and head, Oklab -> sRGB (no proj_out, no Euler update, no VAE decode)
Timing: the two end-to-end paths run INTERLEAVED (order alternates every rep), wall clock with a device sync; thesaving is the median of the paired differences with a bootstrap 95% CI. Component rows use CUDA events. Peak memory isthe peak allocated during one end-to-end run minus what was allocated before it (activations, not weights); residentweights are listed separately. Modes: eager, and compile (torch.compile of every transformer block, stock and tail;the VAE stays eager unless --compile-vae).
Before timing, a PSNR check compares the DWD image with the VAE image (same seed); a broken or mismatched tail landsfar below --min-psnr and the script exits with status 1.
python scripts/benchmark_latency.py --sizes 1024x1024,2048x2048 --modes eager,compile --out benchmark.json"""
from __future__ import annotations
import argparseimport importlib.utilimport jsonimport mathimport osimport randomimport statisticsimport sysimport time
import torch
if importlib.util.find_spec("pq_image_dwd") is None: # running from a source checkout without installing the package sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
from pq_image_dwd.pipeline import DEFAULT_TAIL, DWDPipeline # noqa: E402
PROMPTS = ["a red fox standing in fresh snow at sunrise, professional wildlife photograph", "a close-up portrait of an elderly fisherman with a grey beard, soft window light, 85mm photo", "a hand-painted wooden storefront sign that reads \"FRESH BREAD\" above a small bakery door"]
def _sync(): if torch.cuda.is_available(): torch.cuda.synchronize()
def _med(v: list[float]) -> float: return round(statistics.median(v), 2)
def _boot_ci(d: list[float], n: int = 2000, seed: int = 0) -> list[float]: rng = random.Random(seed) meds = sorted(statistics.median(rng.choices(d, k=len(d))) for _ in range(n)) return [round(meds[int(0.025 * n)], 2), round(meds[int(0.975 * n) - 1], 2)]
def _psnr(a: torch.Tensor, b: torch.Tensor) -> float: mse = ((a.float() - b.float()) ** 2).mean().item() return 99.0 if mse == 0 else 10 * math.log10(255.0 ** 2 / mse)
def _gb(m) -> float: return round(sum(p.numel() * p.element_size() for p in m.parameters()) / 1e9, 3)
class _Ev: """CUDA-event timer for one region (ms)."""
def __init__(self): self.s = torch.cuda.Event(enable_timing=True) self.e = torch.cuda.Event(enable_timing=True)
def __enter__(self): self.s.record() return self
def __exit__(self, *a): self.e.record()
def ms(self) -> float: return self.s.elapsed_time(self.e)
def e2e(pipe: DWDPipeline, prompt: str, h: int, w: int, seed: int, path: str): """One end-to-end run until the uint8 image is on the host.""" cond = pipe.encode(prompt) lat, cache = pipe.denoise(cond, h, w, seed) img = pipe.last_step_dwd(lat, cond, h, w) if path == "dwd" else pipe.last_step_vae(lat, cond, h, w, cache) return img.cpu()
def components(pipe: DWDPipeline, prompt: str, h: int, w: int, seed: int) -> dict: """CUDA-event timings (ms) of the parts of one run.""" ev = {k: _Ev() for k in ("encode", "steps_1_7", "last_dwd", "last_vae", "vae_decode")} with ev["encode"]: cond = pipe.encode(prompt) with ev["steps_1_7"]: lat, cache = pipe.denoise(cond, h, w, seed) with ev["last_dwd"]: pipe.last_step_dwd(lat, cond, h, w) with ev["last_vae"]: pipe.last_step_vae(lat, cond, h, w, cache) lat0 = lat.clone() vae = pipe._get_vae(decoder=True) with ev["vae_decode"]: vae.decode(lat0, h, w) _sync() return {k: e.ms() for k, e in ev.items()}
def peak_activation_gb(fn) -> float: _sync() torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() base = torch.cuda.memory_allocated() fn() _sync() return round((torch.cuda.max_memory_allocated() - base) / 1e9, 3)
def bench_size(pipe: DWDPipeline, w: int, h: int, reps: int, warmup: int, stock_pipe=None) -> dict: th, tw = h // 16, w // 16 prompt = PROMPTS[0] for i in range(warmup): for path in ("dwd", "vae"): e2e(pipe, prompt, th, tw, i, path) t = {"dwd": [], "vae": []} for r in range(reps): order = ("dwd", "vae") if r % 2 == 0 else ("vae", "dwd") for path in order: _sync() a = time.perf_counter() e2e(pipe, prompt, th, tw, 100 + r, path) _sync() t[path].append((time.perf_counter() - a) * 1000) diff = [v - d for v, d in zip(t["vae"], t["dwd"])] comp = [components(pipe, prompt, th, tw, 200 + r) for r in range(max(3, reps // 2))] out = {"width": w, "height": h, "reps": reps, "e2e_ms": {"vae": _med(t["vae"]), "dwd": _med(t["dwd"])}, "saved_ms": _med(diff), "saved_ms_ci95": _boot_ci(diff), "speedup": round(statistics.median(t["vae"]) / statistics.median(t["dwd"]), 3), "components_ms": {k: _med([c[k] for c in comp]) for k in comp[0]}, "peak_activation_gb": { "vae": peak_activation_gb(lambda: e2e(pipe, prompt, th, tw, 7, "vae")), "dwd": peak_activation_gb(lambda: e2e(pipe, prompt, th, tw, 7, "dwd"))}} c = out["components_ms"] out["last_step_saved_ms"] = round(c["last_vae"] - c["last_dwd"], 2) out["peak_activation_saved_gb"] = round(out["peak_activation_gb"]["vae"] - out["peak_activation_gb"]["dwd"], 3) if stock_pipe is not None: st = [] for r in range(warmup + reps): g = torch.Generator(pipe.dev).manual_seed(300 + r) _sync() a = time.perf_counter() stock_pipe(prompt=prompt, width=w, height=h, generator=g, output_type="pil") _sync() if r >= warmup: st.append((time.perf_counter() - a) * 1000) out["e2e_ms"]["stock_pipeline"] = _med(st) return out
def quality_check(pipe: DWDPipeline, w: int, h: int, n: int = 2) -> list[float]: out = [] for i in range(n): cond = pipe.encode(PROMPTS[i % len(PROMPTS)]) o = pipe.generate(cond, h // 16, w // 16, seed=i, dwd=True, vae=True) out.append(round(_psnr(o["dwd"], o["vae"]), 2)) return out
def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--tail", default=DEFAULT_TAIL) ap.add_argument("--base", default="Qwen/Qwen-Image-2.1-Turbo") ap.add_argument("--sizes", default="1024x1024,2048x2048") ap.add_argument("--modes", default="eager,compile") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--warmup", type=int, default=2) ap.add_argument("--min-psnr", type=float, default=30.0) ap.add_argument("--compile-vae", action="store_true", help="in compile mode, also torch.compile the VAE decoder") ap.add_argument("--stock-pipeline", action="store_true", help="also time the diffusers QwenImage21Pipeline object (eager only)") ap.add_argument("--out", default="benchmark.json") a = ap.parse_args(argv) if not torch.cuda.is_available(): ap.error("a CUDA GPU is needed") sizes = [tuple(int(v) for v in s.split("x")) for s in a.sizes.split(",")] pipe = DWDPipeline.from_pretrained(a.tail, base=a.base, device="cuda", load_vae=True) res = {"gpu": torch.cuda.get_device_name(), "torch": torch.__version__, "batch": 1, "steps": 8, "dtype": "bfloat16", "task": "text-to-image", "weights_gb": {"transformer": _gb(pipe.transformer), "text_encoder": _gb(pipe.text_encoder.te), "vae_decoder": round(_gb(pipe.vae.vae.decoder) + _gb(pipe.vae.vae.post_quant_conv), 3), "vae_encoder": round(_gb(pipe.vae.vae.encoder) + _gb(pipe.vae.vae.quant_conv), 3), "dwd_tail": _gb(pipe.tail)}} import diffusers import transformers
res["diffusers"], res["transformers"] = diffusers.__version__, transformers.__version__ w0, h0 = sizes[0] res["psnr_dwd_vs_vae"] = quality_check(pipe, w0, h0) print("PSNR DWD vs VAE", res["psnr_dwd_vs_vae"], flush=True) if min(res["psnr_dwd_vs_vae"]) < a.min_psnr: print(f"DWD image is far from the VAE image (< {a.min_psnr} dB): wrong or broken tail", flush=True) with open(a.out, "w") as fh: json.dump(res, fh, indent=1) return 1 stock_pipe = None if a.stock_pipeline: from diffusers import QwenImage21Pipeline
stock_pipe = QwenImage21Pipeline(scheduler=pipe.scheduler, vae=pipe.vae.vae, text_encoder=pipe.text_encoder.te, processor=pipe.text_encoder.pipe.processor, transformer=pipe.transformer, sample_sigmas=pipe.sigmas) stock_pipe.set_progress_bar_config(disable=True) res["modes"] = {} for mode in a.modes.split(","): rows = {} try: if mode == "compile": pipe.enable_compile() if a.compile_vae: pipe.vae.vae.decoder = torch.compile(pipe.vae.vae.decoder, dynamic=False) elif mode != "eager": raise ValueError(f"unknown mode {mode}") for w, h in sizes: warm = a.warmup + (2 if mode == "compile" else 0) rows[f"{w}x{h}"] = bench_size(pipe, w, h, a.reps, warm, stock_pipe if mode == "eager" else None) print(mode, w, h, json.dumps(rows[f"{w}x{h}"]), flush=True) except Exception as e: # report and go on with the next mode rows["error"] = f"{type(e).__name__}: {e}"[:500] print(mode, "FAILED", rows["error"], flush=True) res["modes"][mode] = rows with open(a.out, "w") as fh: json.dump(res, fh, indent=1) print(json.dumps(res, indent=1)) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env python"""Re-write a DWD tail file in the release layout: unused tensors dropped, Linear weights bf16 (or fp32 with--fp32), the attention RMSNorm weights fp32, metadata the pipeline checks on load. Verifies the result against thesource and prints its sha256.
python scripts/export_weights.py --src tail_fp32.safetensors --out dwd_tail.safetensors"""
import argparseimport hashlibimport jsonimport osimport sys
import torch
try: from pq_image_dwd.weights import export_tail, load_tail_fileexcept ImportError: # running from a source checkout without installing the package sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) from pq_image_dwd.weights import export_tail, load_tail_file
def sha256(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 24), b""): h.update(chunk) return h.hexdigest()
def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--src", required=True, help="tail file to convert") ap.add_argument("--out", required=True, help="output .safetensors") ap.add_argument("--fp32", action="store_true", help="keep the Linear weights in fp32") a = ap.parse_args(argv) dtype = torch.float32 if a.fp32 else torch.bfloat16 meta = export_tail(a.src, a.out, dtype=dtype) src, _ = load_tail_file(a.src) out, _ = load_tail_file(a.out) if set(src) != set(out): raise SystemExit("tensor names differ between source and output") for k, v in src.items(): want = v.float() if k.endswith(("norm_q.weight", "norm_k.weight")) else v.to(dtype) if not torch.equal(out[k], want): raise SystemExit(f"tensor {k} differs from the source") info = {"path": os.path.basename(a.out), "sha256": sha256(a.out), "bytes": os.path.getsize(a.out), "n_tensors": len(out), "n_params": int(sum(v.numel() for v in out.values())), "metadata": meta} print(json.dumps(info, indent=1)) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576#!/usr/bin/env python"""Generate or edit an image with Qwen-Image-2.1-Turbo and the DWD head (no VAE decode).
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 in.jpg --out snow.png
--tail takes a tail .safetensors file, a directory holding dwd_tail.safetensors, or a Hugging Face repo id. Width andheight must be multiples of 32; for an edit they default to about --output-resolution^2 pixels at the input's aspect.--compare also writes the stock pipeline's image for the same seed (VAE decode) next to the output."""
import argparseimport osimport sysimport time
try: from pq_image_dwd.pipeline import DEFAULT_TAIL, DWDPipelineexcept ImportError: # running from a source checkout without installing the package sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) from pq_image_dwd.pipeline import DEFAULT_TAIL, DWDPipeline
def main(argv=None) -> int: ap = argparse.ArgumentParser(description="Qwen-Image-2.1-Turbo + DWD head: text-to-image and editing without the " "VAE decode") ap.add_argument("--prompt", required=True, action="append", help="text prompt or edit instruction; repeat for several images (seeds seed, seed + 1, ...)") ap.add_argument("--image", action="append", default=None, help="condition image for editing; repeat for several condition images") ap.add_argument("--tail", default=DEFAULT_TAIL, help="tail .safetensors, a directory holding it, or a repo id") ap.add_argument("--base", default="Qwen/Qwen-Image-2.1-Turbo", help="base model repo id or local diffusers dir") ap.add_argument("--width", type=int, default=None) ap.add_argument("--height", type=int, default=None) ap.add_argument("--output-resolution", type=int, default=1024, help="condition images are resized to about this^2 pixels (and the default output size)") ap.add_argument("--seed", type=int, default=0) ap.add_argument("--out", default="dwd.png", help="output PNG; with several prompts, _<i> is added to the name") ap.add_argument("--compare", action="store_true", help="also write the stock pipeline's image (VAE decode) as <out>_vae.png") ap.add_argument("--device", default=None, help="default: cuda if available, else cpu") ap.add_argument("--compile", action="store_true", help="torch.compile the transformer blocks (slow first image)") a = ap.parse_args(argv) for name in ("width", "height"): v = getattr(a, name) if v is not None and (v <= 0 or v % 32): ap.error(f"--{name} must be a positive multiple of 32")
images = None if a.image: from PIL import Image
images = [Image.open(p) for p in a.image] t0 = time.perf_counter() pipe = DWDPipeline.from_pretrained(a.tail, base=a.base, device=a.device, compile=a.compile) print(f"loaded in {time.perf_counter() - t0:.1f} s", flush=True) t1 = time.perf_counter() res = pipe(a.prompt, image=images, width=a.width, height=a.height, seed=a.seed, output_resolution=a.output_resolution, return_vae=a.compare) dwd, vae = res if a.compare else (res, None) print(f"generated {len(dwd)} image(s) in {time.perf_counter() - t1:.2f} s", flush=True) root, ext = os.path.splitext(a.out) ext = ext or ".png" os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) for i, img in enumerate(dwd): stem = root if len(dwd) == 1 else f"{root}_{i}" img.save(stem + ext) print(f"wrote {stem + ext}") if vae is not None: vae[i].save(f"{stem}_vae{ext}") print(f"wrote {stem}_vae{ext}") return 0
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526"""DWD ("Decoding Without a Decoder", arXiv 2611.22287) for Qwen-Image-2.1-Turbo: a fine-tuned copy of thetransformer's last 4 blocks plus a Linear(4096 -> 768) pixel head that replaces the last sampler step and the VAEdecode.
Modules: pipeline DWDPipeline: text-to-image and image editing without the VAE decode model the trained tail (DWDTail) and the stock-prefix forward it reads weights tail file reading, checking and export color normalized Oklab -> sRGB, head patch layout schedule the turbo checkpoint's 8 sampler sigmas, timestep rounding encoders Qwen3-VL prompt encoder and VAE wrappers, model download"""
__version__ = "0.1.0"
from .color import OKLAB_MEAN, OKLAB_STD, head_to_srgb, oklab_norm_to_srgb, patchify, srgb_to_oklab_norm, to_uint8, unpatchify # noqa: E402,E501from .model import HEAD_OUT, Cond, DWDTail # noqa: E402from .pipeline import DEFAULT_TAIL, SIZES_1MP, SIZES_2K, DWDPipeline # noqa: E402from .schedule import SIGMAS, model_timestep # noqa: E402from .weights import BASE_REPO, TAIL_FILENAME, export_tail, load_tail, load_tail_file # noqa: E402
__all__ = [ "__version__", "OKLAB_MEAN", "OKLAB_STD", "head_to_srgb", "oklab_norm_to_srgb", "patchify", "srgb_to_oklab_norm", "to_uint8", "unpatchify", "HEAD_OUT", "Cond", "DWDTail", "DEFAULT_TAIL", "SIZES_1MP", "SIZES_2K", "DWDPipeline", "SIGMAS", "model_timestep", "BASE_REPO", "TAIL_FILENAME", "export_tail", "load_tail", "load_tail_file",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""Colour space and patch layout of the DWD head.
The head predicts normalized Oklab (mean (0.56, 0.0, 0.01), std 0.16), the colour encoding of AsymFlow'sOklabColorEncoder (LakonLab, Apache-2.0; the formulas are re-implemented here). The Oklab matrices are Bjorn Ottosson's(public domain).
encode: sRGB in [-1, 1] -> [0, 1] -> linear RGB (sRGB EOTF) -> LMS -> cube root -> Oklab -> (lab - mean) / std decode: the inverse; linear RGB is clamped to [0, 1] before the sRGB OETF.
Patch layout: one image token is one 16x16 pixel tile. Its 768 head outputs are in (c, p1, p2) order (3 channels,tile row, tile column), and the tokens are row-major over the (H/16, W/16) grid, the order of the packed latents."""
from __future__ import annotations
import torch
OKLAB_MEAN = (0.56, 0.0, 0.01)OKLAB_STD = 0.16PATCH = 16
_M1 = [[0.4122214708, 0.5363325363, 0.0514459929], [0.2119034982, 0.6806995451, 0.1073969566], [0.0883024619, 0.2817188376, 0.6299787005]]_M2 = [[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660]]_M2I = [[1.0, 0.3963377774, 0.2158037573], [1.0, -0.1055613458, -0.0638541728], [1.0, -0.0894841775, -1.2914855480]]_M1I = [[4.0767416621, -3.3077115913, 0.2309699292], [-1.2684380046, 2.6097574011, -0.3413193965], [-0.0041960863, -0.7034186147, 1.7076147010]]
def _mat(v, ref: torch.Tensor) -> torch.Tensor: return torch.tensor(v, dtype=ref.dtype, device=ref.device)
def _apply(m: torch.Tensor, x: torch.Tensor) -> torch.Tensor: """3x3 matrix over the channel dim (dim 1) of [B, 3, ...].""" return torch.einsum("ij,bj...->bi...", m, x)
def _bshape(x: torch.Tensor) -> tuple: return (1, 3) + (1,) * (x.dim() - 2)
def srgb_to_oklab_norm(x: torch.Tensor) -> torch.Tensor: """[B, 3, ...] sRGB in [-1, 1] -> normalized Oklab, computed in fp32 (or fp64 if given).""" x = x.float() if x.dtype not in (torch.float32, torch.float64) else x c = ((x + 1) / 2).clamp(0, 1) lin = torch.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) lms = _apply(_mat(_M1, x), lin) lms = torch.sign(lms) * lms.abs() ** (1 / 3) lab = _apply(_mat(_M2, x), lms) return (lab - _mat(OKLAB_MEAN, x).view(_bshape(x))) / OKLAB_STD
def oklab_norm_to_lin(y: torch.Tensor) -> torch.Tensor: """[B, 3, ...] normalized Oklab -> linear RGB, unclamped (fp32).""" y = y.float() if y.dtype not in (torch.float32, torch.float64) else y lab = y * OKLAB_STD + _mat(OKLAB_MEAN, y).view(_bshape(y)) lms = _apply(_mat(_M2I, y), lab) ** 3 return _apply(_mat(_M1I, y), lms)
def oklab_norm_to_srgb(y: torch.Tensor) -> torch.Tensor: """[B, 3, ...] normalized Oklab -> sRGB in [-1, 1] (fp32).""" lin = oklab_norm_to_lin(y).clamp(0, 1) c = torch.where(lin <= 0.0031308, 12.92 * lin, 1.055 * lin.clamp_min(1e-12) ** (1 / 2.4) - 0.055) return c * 2 - 1
def patchify(x: torch.Tensor, p: int = PATCH) -> torch.Tensor: """[B, C, p*h, p*w] -> [B, h*w, C*p*p], (c, p1, p2) order per token, tokens row-major.""" B, C, H, W = x.shape h, w = H // p, W // p return x.reshape(B, C, h, p, w, p).permute(0, 2, 4, 1, 3, 5).reshape(B, h * w, C * p * p)
def unpatchify(y: torch.Tensor, h: int, w: int, c: int = 3, p: int = PATCH) -> torch.Tensor: """[B, h*w, c*p*p] -> [B, c, p*h, p*w] (inverse of patchify).""" B = y.shape[0] return y.reshape(B, h, w, c, p, p).permute(0, 3, 1, 4, 2, 5).reshape(B, c, p * h, p * w)
def head_to_srgb(y: torch.Tensor, h: int, w: int) -> torch.Tensor: """Head output [B, h*w, 768] -> sRGB image [B, 3, 16h, 16w] in [-1, 1] (fp32).""" return oklab_norm_to_srgb(unpatchify(y.float(), h, w)).clamp(-1, 1)
def to_uint8(x: torch.Tensor) -> torch.Tensor: """[B, 3, H, W] in [-1, 1] -> [B, H, W, 3] uint8, computed in fp32 (the diffusers image postprocessor does the same arithmetic in the decoder's dtype, so on a bf16 VAE output it can differ by one code value).""" return ((x.float() / 2 + 0.5).clamp(0, 1) * 255).round().to(torch.uint8).permute(0, 2, 3, 1).contiguous()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""Frozen encoders: the Qwen3-VL prompt encoder and the Qwen-Image-2.1 VAE (AutoencoderKLQwenImage21).
Text: the stock QwenImage21Pipeline.encode_prompt, called on a pipeline object built without transformer and VAE, sothe prompt template, the vision-language image slots and the hidden-state selection are exactly the stock ones. Thelanguage-model head is replaced by Identity (only hidden states are read).Editing: QwenImage21Pipeline.__call__ steps 1-3: each condition image is converted to RGBA and resized to aboutoutput_resolution^2 pixels at its own aspect (multiples of 32); the resized image goes to the prompt encoder, and thesame resize, preprocessed to [-1, 1] with all four channels, goes to the VAE encoder (posterior mode,(z - mean) / std, spatial flatten to [1, h*w, 64]).VAE decode (only for the comparison image): (z * std + mean) -> decode -> RGB (alpha dropped)."""
from __future__ import annotations
import os
import torchimport torch.nn as nn
from .model import Cond
BASE_MODEL = "Qwen/Qwen-Image-2.1-Turbo"# the diffusers-layout parts this package loads (the VAE only for editing or the comparison image)ALLOW_PATTERNS = ["model_index.json", "scheduler/*", "text_encoder/*", "processor/*", "transformer/*", "vae/*"]_NEED = ("model_index.json", "transformer/config.json", "text_encoder/config.json", "scheduler/scheduler_config.json")
def resolve(model_path: str) -> str: """Repo id or local dir -> local snapshot dir. A local dir passes through; a repo already in the Hugging Face cache resolves to its snapshot when the needed parts are there; otherwise they are downloaded.""" if os.path.isdir(model_path): return model_path from huggingface_hub import snapshot_download from huggingface_hub.constants import HF_HUB_CACHE
repo = os.path.join(HF_HUB_CACHE, "models--" + model_path.replace("/", "--")) ref = os.path.join(repo, "refs", "main") if os.path.isfile(ref): with open(ref) as fh: snap = os.path.join(repo, "snapshots", fh.read().strip()) if all(os.path.isfile(os.path.join(snap, f)) for f in _NEED) and os.path.isdir(os.path.join(snap, "processor")): return snap return snapshot_download(model_path, allow_patterns=ALLOW_PATTERNS)
def calculate_dimensions(target_area: float, ratio: float) -> tuple[int, int]: """(width, height), multiples of 32, with about `target_area` pixels at aspect `ratio` (the stock pipeline's).""" from diffusers.pipelines.qwenimage21.pipeline_qwenimage21 import calculate_dimensions as cd
w, h, _ = cd(target_area, ratio) return int(w), int(h)
class TextEncoder: """prompt (+ resized condition images) -> (embeds [1, L, 4096] bf16, mask or None, img_mask [1, L] bool)."""
def __init__(self, model_path: str = BASE_MODEL, device="cuda", dtype=torch.bfloat16): from diffusers import FlowMatchEulerDiscreteScheduler, QwenImage21Pipeline from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
model_path = resolve(model_path) te = Qwen3VLForConditionalGeneration.from_pretrained(model_path, subfolder="text_encoder", dtype=dtype) te.lm_head = nn.Identity() self.te = te.to(device).eval().requires_grad_(False) proc = AutoProcessor.from_pretrained(model_path, subfolder="processor") sch = FlowMatchEulerDiscreteScheduler.from_pretrained(model_path, subfolder="scheduler") self.pipe = QwenImage21Pipeline(scheduler=sch, vae=None, text_encoder=self.te, processor=proc, transformer=None) self.device, self.dtype = torch.device(device), dtype
@torch.no_grad() def __call__(self, prompt: str, images: list | None = None): emb, mask, img_mask = self.pipe.encode_prompt(prompt=[prompt], image=images, device=self.device) return emb.to(self.dtype), None if mask is None else mask.bool(), img_mask.bool()
class VAE: """AutoencoderKLQwenImage21 wrapper: encode_vae_input (editing) and decode (comparison image)."""
def __init__(self, model_path: str = BASE_MODEL, device="cuda", dtype=torch.bfloat16, decoder: bool = True): from diffusers import AutoencoderKLQwenImage21
model_path = resolve(model_path) self.vae = AutoencoderKLQwenImage21.from_pretrained(model_path, subfolder="vae", torch_dtype=dtype).to(device) self.vae.eval().requires_grad_(False) c = self.vae.config self.z = c.z_dim self.mean = torch.tensor(c.latents_mean).view(1, self.z, 1, 1, 1).to(device, dtype) self.std = torch.tensor(c.latents_std).view(1, self.z, 1, 1, 1).to(device, dtype) self.dtype = dtype self.has_decoder = True if not decoder: self.drop_decoder()
def drop_decoder(self): """Free the decoder weights (encoding does not use them).""" self.vae.decoder = None self.vae.post_quant_conv = None self.has_decoder = False
@torch.no_grad() def encode_vae_input(self, x: torch.Tensor) -> torch.Tensor: """Pipeline-preprocessed [B, 4, 1, H, W] (RGBA in [-1, 1]) -> packed normalized latents [B, h*w, 64] (bf16), as QwenImage21Pipeline._encode_vae_image (posterior mode) + _pack_latents.""" B = x.shape[0] z = self.vae.encode(x.to(self.vae.device, self.dtype)).latent_dist.mode() z = (z - self.mean) / self.std h, w = z.shape[-2:] return z.view(B, self.z, h * w).transpose(1, 2)
@torch.no_grad() def decode(self, lat: torch.Tensor, h: int, w: int) -> torch.Tensor: """packed latents [B, h*w, 64] -> RGB image [B, 3, 16h, 16w] in [-1, 1] (fp32, clamped), as the stock pipeline (the alpha channel is dropped).""" if not self.has_decoder: raise RuntimeError("this VAE was loaded without its decoder") B = lat.shape[0] z = lat.transpose(1, 2).reshape(B, self.z, 1, h, w).to(self.dtype) z = z * self.std + self.mean img = self.vae.decode(z, return_dict=False)[0][:, :, 0] # [B, 4, H, W] return img[:, :3].float().clamp(-1, 1)
def edit_inputs(pipe_like, images: list, output_resolution: int, vae) -> tuple[list, torch.Tensor, tuple]: """Condition images -> (resized images for the prompt encoder, packed condition latents [1, Nc, 64], cond_shapes). pipe_like: anything with a diffusers VaeImageProcessor as `.image_processor`.""" pp = pipe_like.image_processor enc_imgs, lats, shapes = [], [], [] for img in images: if hasattr(img, "mode") and img.mode != "RGBA": img = img.convert("RGBA") iw, ih = calculate_dimensions(output_resolution * output_resolution, img.size[0] / img.size[1]) enc_imgs.append(pp.resize(img, width=iw, height=ih)) x = pp.preprocess(img, width=iw, height=ih).unsqueeze(2) # [1, 4, 1, H, W] in [-1, 1] lats.append(vae.encode_vae_input(x)) shapes.append((1, ih // 16, iw // 16)) return enc_imgs, torch.cat(lats, dim=1), tuple(shapes)
def make_cond(embeds, mask, img_mask, cond_lat=None, cond_shapes=()) -> Cond: return Cond(embeds, mask, img_mask, cond_lat, tuple(cond_shapes))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""The DWD tail on top of a stock diffusers QwenImage21Transformer2DModel (Qwen-Image-2.1: 32 single-stream blocks,D = 4096, one shared modulation for every block, causal_condition).
The stock transformer is never modified. At the last sampler step:
prefix the stock model's own input embeddings (img_in, txt_in, rotary), its time embedding + shared modulation and its first 32 - K blocks, run in bf16 with autocast off, on the whole joint sequence [text (+ condition-image tokens); target image] without a KV cache. This is exactly the stock forward up to block 32 - K. tail the trained copy of the last K blocks with its own time embedding, shared modulation and norm_out, run on the same joint sequence (the prefix rows are needed as attention keys) under bf16 autocast; norm_out is applied to the target-image rows only. head Linear(4096 -> 768): one 16x16 normalized-Oklab pixel tile per target token.
Layout of the joint sequence (as the stock forward builds it): the text embeddings, with every vision-language imageslot expanded to the 2x2 latent tokens it stands for, then one slot per 2x2 group of target tokens. Text andcondition-image tokens are causal and modulated from t = 0; the target image is last, bidirectional, and modulatedfrom the sampled t."""
from __future__ import annotations
import mathfrom dataclasses import dataclass
import torchimport torch.nn as nn
HEAD_OUT = 3 * 16 * 16IMG_TOKENS_PER_SLOT = 4 # one vision-language image slot stands for 2x2 latent tokens
@dataclassclass Cond: """Condition for one image: embeds [1, L, 4096] (bf16), mask [1, L] bool or None (None: no padding), img_mask [1, L] bool (the vision-language image slots; all False for text-to-image). Editing: cond_lat [1, Nc, 64] packed, normalized latents of the condition images (in order) and cond_shapes their (1, h, w) latent grids.""" embeds: torch.Tensor mask: torch.Tensor | None img_mask: torch.Tensor cond_lat: torch.Tensor | None = None cond_shapes: tuple = ()
def to(self, device) -> "Cond": return Cond(self.embeds.to(device), None if self.mask is None else self.mask.to(device), self.img_mask.to(device), None if self.cond_lat is None else self.cond_lat.to(device), self.cond_shapes)
@dataclassclass Ctx: """Per-forward metadata shared by the prefix and the tail (the stock forward's prefill path, no KV cache).""" rotary: torch.Tensor # [N, head_dim / 2] complex target_mask: torch.Tensor # [N] bool, True at the target image's tokens segments: list # block-causal prefix segments for QwenImage21AttnProcessor key_valid: torch.Tensor | None # [1, N] bool or None n_txt: int # number of tokens before the target image (text + condition images)
def target_img_mask(cond: Cond, h: int, w: int) -> torch.Tensor: """The transformer's img_mask: the condition's vision-language slots + one slot per 2x2 target tokens.""" return torch.cat([cond.img_mask, cond.img_mask.new_ones(cond.img_mask.shape[0], h * w // IMG_TOKENS_PER_SLOT)], 1)
def img_shapes(cond: Cond, h: int, w: int) -> list: """Per-image (frame, h, w) latent grids: condition images first, the target last.""" return [*cond.cond_shapes, (1, h, w)]
def check_grid(h: int, w: int): if h <= 0 or w <= 0 or h % 2 or w % 2: raise ValueError(f"the latent grid must be even in both directions (width and height multiples of 32), " f"got {w} x {h} tokens")
def build_ctx(transformer, cond: Cond, h: int, w: int, device) -> tuple[Ctx, torch.Tensor, torch.Tensor]: """Mirrors QwenImage21Transformer2DModel.forward (prefill, no KV cache) up to the block loop, minus the embeddings. Returns (ctx, repeats, image_pad_mask).""" from diffusers.models.transformers.transformer_qwenimage21 import _qwenimage21_prefix_segments
check_grid(h, w) shapes = img_shapes(cond, h, w) if (cond.cond_lat is None) != (not cond.cond_shapes): raise ValueError("cond_lat and cond_shapes must be given together") if cond.cond_lat is not None and cond.cond_lat.shape[1] != sum(math.prod(s) for s in cond.cond_shapes): raise ValueError("cond_lat does not match cond_shapes") img_mask = target_img_mask(cond, h, w) repeats = torch.where(img_mask, IMG_TOKENS_PER_SLOT, 1)[0] image_pad_mask = torch.repeat_interleave(img_mask[0], repeats) rotary = transformer.pos_embed(shapes, image_pad_mask, device=device) image_ids, target_mask = transformer.build_token_metadata(image_pad_mask, shapes) key_valid = None if cond.mask is not None: key_valid = torch.ones(cond.embeds.shape[0], image_pad_mask.shape[0], dtype=torch.bool, device=device) text_positions = (~image_pad_mask).nonzero(as_tuple=True)[0] vlm_text_positions = ~img_mask[0][: cond.mask.shape[1]] key_valid[:, text_positions] = cond.mask.bool()[:, vlm_text_positions] prefix_len = int((~target_mask).sum()) segments = _qwenimage21_prefix_segments(image_ids, prefix_len) return Ctx(rotary, target_mask, segments, key_valid, prefix_len), repeats, image_pad_mask
def with_zero_row(timestep: torch.Tensor) -> torch.Tensor: """causal_condition: the extra t = 0 row that text and condition-image tokens are modulated from.""" return torch.cat([timestep, timestep.new_zeros(1)], dim=0)
def run_block(blk, hs: torch.Tensor, mod: torch.Tensor, ctx: Ctx) -> torch.Tensor: return blk(hidden_states=hs, modulation=mod, rotary_emb=ctx.rotary, attention_mask=None, target_token_mask=ctx.target_mask, layer_cache=None, kv_cache_mode=None, cache_write_slice=None, segments=ctx.segments, key_valid=ctx.key_valid)
@torch.no_grad()def prefix_forward(transformer, n_blocks: int, x: torch.Tensor, cond: Cond, timestep: torch.Tensor, h: int, w: int): """The stock transformer's forward up to (not including) block `n_blocks`, without a KV cache.
x [1, h*w, 64] packed target latents (bf16), timestep [1] (model_timestep). With condition images the stock hidden_states are cat([cond.cond_lat, x]) (condition images first). Pure bf16 with autocast off, as the stock pipeline runs. Returns (hs [1, N, D], ctx).""" with torch.autocast(x.device.type, enabled=False): t = transformer B = x.shape[0] ctx, repeats, image_pad_mask = build_ctx(t, cond, h, w, x.device) hidden = t.img_in(x if cond.cond_lat is None else torch.cat([cond.cond_lat.to(x.dtype), x], dim=1)) enc = t.txt_in(cond.embeds) joint = torch.cat([enc, enc.new_zeros(B, (h * w) // IMG_TOKENS_PER_SLOT, enc.shape[2])], dim=1) joint = joint.repeat_interleave(repeats, dim=1) joint[:, image_pad_mask] = hidden temb = t.time_text_embed(with_zero_row(timestep.to(hidden.dtype)), hidden) mod = t.modulation(temb) for blk in t.transformer_blocks[:n_blocks]: joint = run_block(blk, joint, mod, ctx) return joint, ctx
# parameters kept in fp32 in the released file and at run time: under bf16 autocast every Linear runs in bf16 (so# bf16 storage changes none of them), but these RMSNorm weights are used directly and an fp32 weight keeps the# normalization in fp32FP32_SUFFIXES = ("attn.norm_q.weight", "attn.norm_k.weight")
def keeps_fp32(name: str) -> bool: return name.endswith(FP32_SUFFIXES)
class DWDTail(nn.Module): """Trained copy of the last K blocks + its own time embedding, shared modulation and norm_out, and the DWD head.
State dict keys: blocks.{i}.*, time_text_embed.*, modulation.1.weight, norm_out.linear.weight, head.weight, head.bias (the same module names as the diffusers transformer)."""
def __init__(self, k: int, dim: int = 4096, num_attention_heads: int = 32, attention_head_dim: int = 128, mlp_ratio: int = 3, eps: float = 1e-6): super().__init__() from diffusers.models.transformers.transformer_qwenimage21 import (QwenImage21AdaLayerNormContinuous, QwenImage21TimestepProjEmbeddings, QwenImage21TransformerBlock)
if dim != num_attention_heads * attention_head_dim: raise ValueError("dim must be num_attention_heads * attention_head_dim") self.k = k self.blocks = nn.ModuleList([QwenImage21TransformerBlock(dim, num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, eps=eps) for _ in range(k)]) self.time_text_embed = QwenImage21TimestepProjEmbeddings(embedding_dim=dim) self.modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 4 * dim, bias=False)) self.norm_out = QwenImage21AdaLayerNormContinuous(dim, dim, eps=eps) self.head = nn.Linear(dim, HEAD_OUT, bias=True)
@classmethod def for_transformer(cls, transformer, k: int, device="meta") -> "DWDTail": """An empty tail shaped like `transformer`'s last k blocks (on the meta device by default: load weights with load_state_dict(..., assign=True)).""" c = transformer.config with torch.device(device): return cls(k, c.num_attention_heads * c.attention_head_dim, c.num_attention_heads, c.attention_head_dim, c.mlp_ratio, c.eps)
def load_weights(self, sd: dict[str, torch.Tensor], time_freqs: torch.Tensor) -> "DWDTail": """Load a tail state dict (any dtype): every tensor in bf16 except the RMSNorm weights (fp32, see FP32_SUFFIXES). time_freqs: the sinusoidal timestep table (a non-persistent fp32 buffer, not in the file), taken from the stock transformer.""" names = set(self.state_dict()) missing, extra = names - set(sd), set(sd) - names if missing or extra: raise KeyError(f"tail weights do not match the model: missing {sorted(missing)[:5]}, " f"extra {sorted(extra)[:5]}") self.load_state_dict({n: v.to(torch.float32 if keeps_fp32(n) else torch.bfloat16) for n, v in sd.items()}, strict=True, assign=True) self.time_text_embed.time_proj.freqs = time_freqs.detach().to(torch.float32).clone() left = [n for n, t in list(self.named_parameters()) + list(self.named_buffers()) if t.is_meta] if left: raise RuntimeError(f"tail tensors left unloaded: {left[:5]}") return self.requires_grad_(False).eval()
def tokens(self, hs: torch.Tensor, timestep: torch.Tensor, ctx: Ctx) -> torch.Tensor: """hs [1, N, D] (prefix output), timestep [1] (model_timestep) -> norm_out target rows [1, h*w, D].""" temb = self.time_text_embed(with_zero_row(timestep.to(torch.bfloat16)), hs) mod = self.modulation(temb) for b in self.blocks: hs = run_block(b, hs, mod, ctx) return self.norm_out(hs[:, ctx.n_txt:], temb, ctx.target_mask[ctx.n_txt:])
def forward(self, hs: torch.Tensor, timestep: torch.Tensor, ctx: Ctx) -> torch.Tensor: """-> head output [1, h*w, 768] (normalized Oklab tiles, (c, p1, p2) order). Runs under bf16 autocast.""" with torch.autocast(hs.device.type, dtype=torch.bfloat16): return self.head(self.tokens(hs, timestep, ctx))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""Text-to-image and image editing with Qwen-Image-2.1-Turbo and the DWD head: no VAE decode.
steps 1-7 the stock transformer, unchanged (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 step 8 the stock prefix (blocks 1-28, no KV cache) -> the trained tail (4 blocks, own time embedding, modulation and norm_out) -> head on the target-image tokens -> normalized Oklab -> sRGB -> uint8 (no proj_out, no last Euler step, no VAE decode)
The prefix and the stock steps run in plain bf16 with autocast off, like the stock pipeline; the tail runs under bf16autocast. Width and height must be multiples of 32. No classifier-free guidance (the turbo model does not use it).
Usage: pipe = DWDPipeline.from_pretrained("PrunaAI/P-Q-Image-2.1-Turbo-DWD") image = pipe("a red fox in fresh snow at sunrise", width=2048, height=2048, seed=0) edited = pipe("Add gently falling snow to the whole scene.", image=Image.open("in.jpg"), seed=0)"""
from __future__ import annotations
import osimport warningsfrom dataclasses import dataclass
import torch
from . import schedule as Sfrom .color import head_to_srgb, to_uint8from .encoders import BASE_MODEL, calculate_dimensions, edit_inputsfrom .model import Cond, DWDTail, check_grid, img_shapes, prefix_forward, target_img_maskfrom .weights import BASE_REPO, load_tail
DEFAULT_TAIL = "PrunaAI/P-Q-Image-2.1-Turbo-DWD"# evaluated sizes (width, height): about 1 MP (the training size) and the model's 2K sizesSIZES_1MP = [(1024, 1024), (1152, 896), (896, 1152), (1344, 768), (768, 1344)]SIZES_2K = [(2048, 2048), (2528, 1696), (1696, 2528), (2752, 1536), (1536, 2752)]
@dataclassclass _Plan: """Per-size sampler constants.""" ts: list # scheduler timesteps (t * 1000, fp32 scalars on the device) sig: torch.Tensor # [steps + 1] fp32 sigmas incl. the final 0, on the device
class DWDPipeline: """Stock Qwen-Image-2.1-Turbo transformer + trained DWD tail + text encoder (+ VAE, only for editing and for the optional comparison image). Build it with `from_pretrained` or `from_components`."""
def __init__(self, transformer, tail: DWDTail, text_encoder, scheduler, vae=None, device=None, metadata: dict | None = None, sigmas: list[float] | None = None, base_path: str | None = None): """transformer: a stock diffusers QwenImage21Transformer2DModel (bf16, not modified); tail: a loaded DWDTail; text_encoder: callable (prompt, images or None) -> (embeds, mask, img_mask); scheduler: a diffusers FlowMatchEulerDiscreteScheduler; vae: an encoders.VAE-like object, or None (loaded from base_path when needed).""" from diffusers.image_processor import VaeImageProcessor
self.dev = torch.device(device) if device is not None else next(tail.parameters()).device if not transformer.config.causal_condition or transformer.config.patch_size != 1: raise ValueError("expected a Qwen-Image-2.1 transformer (causal_condition, patch_size 1)") self.transformer = transformer.to(self.dev).requires_grad_(False).eval() self.tail = tail.to(self.dev) self.k = len(tail.blocks) self.n_prefix = len(transformer.transformer_blocks) - self.k if self.n_prefix <= 0: raise ValueError(f"tail has {self.k} blocks but the transformer has {len(transformer.transformer_blocks)}") self.text_encoder, self.scheduler, self.vae = text_encoder, scheduler, vae self.metadata = dict(metadata or {}) self.sigmas = list(sigmas or S.SIGMAS) head_sigma = float(self.metadata.get("head_sigma", S.HEAD_SIGMA)) if abs(self.sigmas[-1] - head_sigma) > 1e-6: warnings.warn(f"the head was trained at sigma {head_sigma}, but the last sampler sigma is " f"{self.sigmas[-1]}", stacklevel=2) self.base_path = base_path self.image_processor = VaeImageProcessor(vae_scale_factor=16, vae_latent_channels=64) self.latent_channels = transformer.config.in_channels self.compiled = False self._plan: _Plan | None = None
# -- construction --------------------------------------------------------------------------------------------- @classmethod def from_components(cls, transformer, tail, text_encoder, scheduler=None, vae=None, device=None, sigmas: list[float] | None = None, base_path: str | None = None, compile: bool = False) -> "DWDPipeline": """transformer: a stock QwenImage21Transformer2DModel. tail: path / directory / repo id of a tail file, or (state_dict, metadata). scheduler: defaults to the turbo checkpoint's FlowMatchEulerDiscreteScheduler config.""" from .weights import check_metadata, clean_state_dict
if isinstance(tail, str): sd, meta = load_tail(tail) else: sd = clean_state_dict(tail[0]) meta = check_metadata(tail[1], sd) if scheduler is None: from diffusers import FlowMatchEulerDiscreteScheduler
scheduler = FlowMatchEulerDiscreteScheduler(base_image_seq_len=256, base_shift=0.5, max_image_seq_len=8192, max_shift=0.9, shift=1.0, time_shift_type="exponential", use_dynamic_shifting=False) if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" # the sinusoidal timestep table is a non-persistent fp32 buffer: from_pretrained(torch_dtype=bf16) keeps it in # fp32 but Module.to(bf16) rounds it, which shifts every block's modulation; keep (or rebuild) it in fp32 tp = transformer.time_text_embed.time_proj kept = tp.freqs.detach().clone() if tp.freqs.dtype == torch.float32 else None if any(p.dtype != torch.bfloat16 for p in transformer.parameters()): transformer = transformer.to(torch.bfloat16) if kept is not None: tp.freqs = kept freqs = fp32_time_freqs(transformer) t = DWDTail.for_transformer(transformer, meta["k"]).load_weights(sd, freqs) pipe = cls(transformer, t, text_encoder, scheduler, vae=vae, device=device, metadata=meta, sigmas=sigmas, base_path=base_path) if compile: pipe.enable_compile() return pipe
@classmethod def from_pretrained(cls, tail: str = DEFAULT_TAIL, base: str = BASE_MODEL, device=None, compile: bool = False, load_vae: bool = False) -> "DWDPipeline": """tail: a tail .safetensors file, a directory holding dwd_tail.safetensors, or a Hugging Face repo id. base: the Qwen-Image-2.1-Turbo repo id or a local diffusers directory. The VAE is not loaded unless load_vae=True; it is loaded on first use otherwise (editing needs its encoder, return_vae its decoder).""" from diffusers import FlowMatchEulerDiscreteScheduler, QwenImage21Transformer2DModel
from .encoders import VAE, TextEncoder, resolve
if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" sd, meta = load_tail(tail) if meta.get("base_repo") not in (None, base) and not os.path.isdir(base): warnings.warn(f"the tail was trained on {meta['base_repo']}; loading it on {base}", stacklevel=2) path = resolve(base) transformer = QwenImage21Transformer2DModel.from_pretrained(path, subfolder="transformer", torch_dtype=torch.bfloat16) scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(path, subfolder="scheduler") text = TextEncoder(path, device=device) vae = VAE(path, device=device) if load_vae else None return cls.from_components(transformer, (sd, meta), text, scheduler, vae=vae, device=device, sigmas=S.sample_sigmas(path), base_path=path, compile=compile)
# -- optional parts -------------------------------------------------------------------------------------------- def _get_vae(self, decoder: bool): if self.vae is not None and (not decoder or getattr(self.vae, "has_decoder", True)): return self.vae if self.base_path is None: raise RuntimeError("no VAE: pass vae= to from_components (needed for editing and return_vae)") from .encoders import VAE
self.vae = VAE(self.base_path, device=self.dev, decoder=decoder) return self.vae
def enable_compile(self, mode: str | None = None): """torch.compile every transformer block (stock and tail; one compile per resolution and sequence length). mode: None (default) or "max-autotune-no-cudagraphs".""" import torch._dynamo
torch._dynamo.config.cache_size_limit = max(torch._dynamo.config.cache_size_limit, 64) kw = {"dynamic": False} if mode is None else {"dynamic": False, "mode": mode} for b in list(self.transformer.transformer_blocks) + list(self.tail.blocks): b.compile(**kw) self.compiled = True
# -- sampler -------------------------------------------------------------------------------------------------- def plan(self) -> _Plan: if self._plan is None: self.scheduler.set_timesteps(sigmas=self.sigmas, device="cpu") ts = [t.to(self.dev) for t in self.scheduler.timesteps.float()] self._plan = _Plan(ts, self.scheduler.sigmas.float().clone().to(self.dev)) return self._plan
def noise(self, h: int, w: int, seed: int) -> torch.Tensor: """Initial packed latents [1, h*w, 64], drawn like the stock pipeline (generator on the pipeline device).""" g = torch.Generator(self.dev).manual_seed(seed) lat = torch.randn(1, 1, self.latent_channels, h, w, generator=g, device=self.dev, dtype=torch.bfloat16) return lat.view(1, self.latent_channels, h * w).transpose(1, 2)
@torch.no_grad() def encode(self, prompt: str, image=None, output_resolution: int = 1024) -> Cond: """Prompt (+ condition images: a PIL image or a list) -> Cond for one image.""" if image is None: emb, mask, img_mask = self.text_encoder(prompt, None) return Cond(emb.to(self.dev, torch.bfloat16), None if mask is None else mask.to(self.dev), img_mask.to(self.dev)) images = list(image) if isinstance(image, (list, tuple)) else [image] enc_imgs, lat, shapes = edit_inputs(self, images, output_resolution, self._get_vae(decoder=False)) emb, mask, img_mask = self.text_encoder(prompt, enc_imgs) return Cond(emb.to(self.dev, torch.bfloat16), None if mask is None else mask.to(self.dev), img_mask.to(self.dev), lat.to(self.dev, torch.bfloat16), shapes)
def _stock_velocity(self, lat, cond: Cond, t, h, w, cache, mode): inp = lat if cond.cond_lat is None else torch.cat([cond.cond_lat, lat], dim=1) timestep = t.expand(lat.shape[0]).to(lat.dtype) v = self.transformer(hidden_states=inp, timestep=timestep / 1000, encoder_hidden_states=cond.embeds, encoder_hidden_states_mask=cond.mask, img_shapes=[img_shapes(cond, h, w)], img_mask=target_img_mask(cond, h, w), kv_cache=cache, kv_cache_mode=mode, return_dict=False)[0] return v[:, -lat.shape[1]:]
@torch.no_grad() def denoise(self, cond: Cond, h: int, w: int, seed: int, use_kv_cache: bool = True): """Steps 1-7 with the stock transformer -> (latent entering the last step, the prefix KV cache or None).""" from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21KVCache
check_grid(h, w) p = self.plan() cache = QwenImage21KVCache(len(self.transformer.transformer_blocks)) if use_kv_cache else None with torch.autocast(self.dev.type, enabled=False): lat = self.noise(h, w, seed) for i in range(len(p.ts) - 1): mode = None if cache is None else ("extract" if i == 0 else "cached") v = self._stock_velocity(lat, cond, p.ts[i], h, w, cache, mode) lat = (lat.float() + (p.sig[i + 1] - p.sig[i]) * v).to(torch.bfloat16) return lat, cache
@torch.no_grad() def last_step_dwd(self, lat: torch.Tensor, cond: Cond, h: int, w: int) -> torch.Tensor: """The DWD last step: stock prefix (no cache) -> tail -> head -> uint8 [1, 16h, 16w, 3].""" t = self.plan().ts[-1].reshape(1).to(torch.bfloat16) / 1000 # the stock timestep rounding with torch.autocast(self.dev.type, enabled=False): hs, ctx = prefix_forward(self.transformer, self.n_prefix, lat, cond, t, h, w) return to_uint8(head_to_srgb(self.tail(hs, t, ctx), h, w))
@torch.no_grad() def last_step_vae(self, lat: torch.Tensor, cond: Cond, h: int, w: int, cache=None) -> torch.Tensor: """The stock last step: stock transformer -> Euler update to t = 0 -> VAE decode -> uint8 [1, 16h, 16w, 3].""" p = self.plan() vae = self._get_vae(decoder=True) with torch.autocast(self.dev.type, enabled=False): mode = None if cache is None else ("extract" if len(p.ts) == 1 else "cached") v = self._stock_velocity(lat, cond, p.ts[-1], h, w, cache, mode) lat0 = (lat.float() + (p.sig[-1] - p.sig[-2]) * v).to(torch.bfloat16) return to_uint8(vae.decode(lat0, h, w))
@torch.no_grad() def generate(self, cond: Cond, h: int, w: int, seed: int, dwd: bool = True, vae: bool = False, use_kv_cache: bool = True) -> dict: """One image on an h x w token grid. Returns {"dwd": uint8 [1, 16h, 16w, 3] (if dwd), "vae": the stock pipeline's image for the same seed (if vae), "lat_last": the latent entering the last step}.""" lat, cache = self.denoise(cond, h, w, seed, use_kv_cache) out = {"lat_last": lat} if dwd: out["dwd"] = self.last_step_dwd(lat, cond, h, w) if vae: out["vae"] = self.last_step_vae(lat, cond, h, w, cache) return out
def _size(self, image, width, height, output_resolution) -> tuple[int, int]: if image is not None and (width is None or height is None): last = image[-1] if isinstance(image, (list, tuple)) else image cw, ch = calculate_dimensions(output_resolution * output_resolution, last.size[0] / last.size[1]) width, height = width or cw, height or ch width, height = width or output_resolution, height or output_resolution if width % 32 or height % 32 or width <= 0 or height <= 0: raise ValueError(f"width and height must be positive multiples of 32, got {width}x{height}") return width, height
def __call__(self, prompt: str | list[str], image=None, width: int | None = None, height: int | None = None, seed: int = 0, output_resolution: int = 1024, output_type: str = "pil", return_vae: bool = False, use_kv_cache: bool = True): """prompt: a string (one image) or a list (one image per prompt, seeds seed, seed + 1, ...). image: condition image(s) for editing (a PIL image or a list, shared by every prompt); each is resized to about output_resolution^2 pixels. width / height: default output_resolution (text-to-image) or about output_resolution^2 pixels at the aspect of the last condition image (editing). output_type: "pil" (PIL.Image), "np" (uint8 HxWx3 array) or "pt" (uint8 tensor [H, W, 3]). return_vae: also return the stock pipeline's image for the same seed (the last step through the stock tail, Euler update and VAE decode; loads the VAE decoder) -> (dwd, vae). Its latents and decode are the stock pipeline's; the uint8 conversion runs in fp32 (diffusers rounds in bf16: up to one code value apart).""" if output_type not in ("pil", "np", "pt"): raise ValueError(f"output_type must be 'pil', 'np' or 'pt', got {output_type!r}") single = isinstance(prompt, str) prompts = [prompt] if single else list(prompt) width, height = self._size(image, width, height, output_resolution) h, w = height // 16, width // 16 dwd, vae = [], [] for i, pr in enumerate(prompts): cond = self.encode(pr, image, output_resolution) o = self.generate(cond, h, w, seed + i, dwd=True, vae=return_vae, use_kv_cache=use_kv_cache) dwd.append(_convert(o["dwd"][0], output_type)) if return_vae: vae.append(_convert(o["vae"][0], output_type)) if single: return (dwd[0], vae[0]) if return_vae else dwd[0] return (dwd, vae) if return_vae else dwd
def fp32_time_freqs(transformer) -> torch.Tensor: """The transformer's sinusoidal timestep table in fp32 (rebuilt with the values it is built with if a cast rounded it); returns it.""" from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21TemporalTimesteps
tp = transformer.time_text_embed.time_proj if tp.freqs.dtype == torch.float32: return tp.freqs freqs = QwenImage21TemporalTimesteps(tp.timestep_dim).freqs.to(tp.freqs.device) tp.freqs = freqs.clone() return freqs
def _convert(img: torch.Tensor, output_type: str): img = img.cpu() if output_type == "pt": return img if output_type == "np": return img.numpy() from PIL import Image
return Image.fromarray(img.numpy())1234567891011121314151617181920212223242526272829303132333435363738"""The fixed 8-step sampler of Qwen-Image-2.1-Turbo.
Flow convention (diffusers FlowMatchEulerDiscreteScheduler): z_t = (1 - t) z0 + t eps, velocity v = eps - z0, t = 1 isnoise; Euler step z <- z + v * (t_next - t).
The turbo checkpoint ships its sampling sigmas (model_index.json `sample_sigmas`), and its scheduler has no dynamicshift, so the sigmas are the same at every resolution: 1.0, .978453, .95418, .926626, .89508, .845148, .704534, .414568 (-> 0)The DWD head replaces the LAST step (t = .414568 -> 0): the stock model runs the first 7 steps, and at the 8th thetrained tail + head turn the transformer's hidden states into pixels."""
from __future__ import annotations
import jsonimport os
import torch
SIGMAS = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568]STEPS = len(SIGMAS)HEAD_SIGMA = SIGMAS[-1]
def sample_sigmas(base_path: str | None) -> list[float]: """The base checkpoint's `sample_sigmas` (model_index.json), or SIGMAS when the file has none.""" if base_path and os.path.isfile(os.path.join(base_path, "model_index.json")): with open(os.path.join(base_path, "model_index.json")) as fh: s = json.load(fh).get("sample_sigmas") if s: return [float(v) for v in s] return list(SIGMAS)
def model_timestep(t: torch.Tensor) -> torch.Tensor: """What the transformer receives, with the stock rounding: the pipeline casts the scheduler timestep (t * 1000, fp32) to the latents' dtype (bf16) and divides by 1000 in bf16; the transformer multiplies by 1000 in fp32.""" return (t.float() * 1000).to(torch.bfloat16) / 1000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""The tail file: reading, checking and writing `dwd_tail.safetensors`.
The released file holds the trained tail and head (EMA weights): 4 transformer blocks, the copies of the timeembedding and the shared modulation, norm_out, and head. Linear weights are bf16; the 8 attention RMSNorm weights(128 values each) are fp32, because the tail runs under bf16 autocast, where those weights are used as stored (seemodel.FP32_SUFFIXES). This is the same computation as running fp32 weights under bf16 autocast.
The safetensors metadata (all strings) describes how to run the head:
format "pq-image-dwd-tail" format_version "1" base_repo the base model the tail was trained on k number of transformer blocks in the tail steps sampler steps; the head replaces the last one head_sigma the sigma of that last step patch pixels per token side (16) head_layout order of the 768 head outputs per token: "(c,p1,p2)" color "oklab_norm": head outputs are normalized Oklab oklab_mean JSON list, normalization mean oklab_std normalization std weights "ema" dtype storage dtype of the Linear weights ("bfloat16" or "float32") compute "bf16-autocast"
`load_tail_file` also reads the earlier fp32 export of the same weights (no `format` key, plus an unused proj_out),which gives the identical tail."""
from __future__ import annotations
import jsonimport osimport re
import torch
from .color import OKLAB_MEAN, OKLAB_STD, PATCHfrom .model import keeps_fp32from .schedule import HEAD_SIGMA, STEPS
FORMAT = "pq-image-dwd-tail"FORMAT_VERSION = 1BASE_REPO = "Qwen/Qwen-Image-2.1-Turbo"HEAD_LAYOUT = "(c,p1,p2)"TAIL_FILENAME = "dwd_tail.safetensors"TAIL_PREFIXES = ("blocks.", "time_text_embed.", "modulation.", "norm_out.", "head.")UNUSED_KEYS = ("proj_out.weight",) # trained-tail velocity output: present in the fp32 export, never used_DTYPES = {"bfloat16": torch.bfloat16, "float32": torch.float32}
def count_blocks(sd: dict) -> int: """Number of tail blocks in a state dict (keys blocks.<i>.*).""" idx = {int(m.group(1)) for k in sd if (m := re.match(r"blocks\.(\d+)\.", k))} if idx != set(range(len(idx))): raise ValueError(f"tail block indices are not contiguous from 0: {sorted(idx)}") return len(idx)
def clean_state_dict(sd: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: """Drop the unused keys and check that only tail and head tensors are left.""" out = {k: v for k, v in sd.items() if k not in UNUSED_KEYS} bad = [k for k in out if not k.startswith(TAIL_PREFIXES)] if bad: raise ValueError(f"unexpected keys in the tail state: {bad[:5]}") if "head.weight" not in out: raise ValueError("the state has no DWD head") return out
def build_metadata(k: int, dtype: torch.dtype, base_repo: str = BASE_REPO) -> dict[str, str]: return {"format": FORMAT, "format_version": str(FORMAT_VERSION), "base_repo": base_repo, "k": str(k), "steps": str(STEPS), "head_sigma": repr(float(HEAD_SIGMA)), "patch": str(PATCH), "head_layout": HEAD_LAYOUT, "color": "oklab_norm", "oklab_mean": json.dumps(list(OKLAB_MEAN)), "oklab_std": repr(float(OKLAB_STD)), "weights": "ema", "dtype": str(dtype).replace("torch.", ""), "compute": "bf16-autocast"}
def check_metadata(meta: dict | None, sd: dict | None = None) -> dict: """Validate the metadata of a tail file. Returns it parsed: {k, steps, base_repo, ...}.
A file without a `format` key is accepted as the earlier export of the same weights when its tensors are a DWD tail (sd given); its metadata is then rebuilt from the tensors.""" meta = dict(meta or {}) if "format" not in meta and sd is not None and "head.weight" in sd and any(k.startswith("blocks.") for k in sd): dtype = sd["head.weight"].dtype meta = build_metadata(count_blocks(sd), dtype, meta.get("base_model", BASE_REPO)) if meta.get("format") != FORMAT: raise ValueError(f"not a DWD tail file for this package (format={meta.get('format')!r})") if int(meta.get("format_version", -1)) > FORMAT_VERSION: raise ValueError(f"tail format_version {meta['format_version']} is newer than this code ({FORMAT_VERSION})") if int(meta["patch"]) != PATCH or meta["head_layout"] != HEAD_LAYOUT or meta.get("color") != "oklab_norm": raise ValueError(f"unsupported head layout: patch {meta['patch']}, {meta['head_layout']}, {meta.get('color')}") mean, std = json.loads(meta["oklab_mean"]), float(meta["oklab_std"]) if any(abs(a - b) > 1e-9 for a, b in zip(mean, OKLAB_MEAN)) or abs(std - OKLAB_STD) > 1e-9: raise ValueError(f"tail was trained with Oklab mean {mean} / std {std}; this code uses " f"{list(OKLAB_MEAN)} / {OKLAB_STD}") return {**meta, "k": int(meta["k"]), "steps": int(meta["steps"])}
def load_tail_file(path: str) -> tuple[dict[str, torch.Tensor], dict]: """Read a tail file: (tensors on CPU, unused keys dropped; parsed metadata).""" from safetensors import safe_open from safetensors.torch import load_file
with safe_open(path, framework="pt") as f: raw_meta = f.metadata() sd = clean_state_dict(load_file(path)) meta = check_metadata(raw_meta, sd) if count_blocks(sd) != meta["k"]: raise ValueError(f"metadata says k={meta['k']} but the file has {count_blocks(sd)} blocks") return sd, meta
def load_tail(tail: str, filename: str = TAIL_FILENAME) -> tuple[dict[str, torch.Tensor], dict]: """A .safetensors file, a directory holding `filename`, or a Hugging Face repo id -> (tensors, metadata).""" if os.path.isdir(tail): tail = os.path.join(tail, filename) elif tail.endswith(".safetensors") and not os.path.isfile(tail): raise FileNotFoundError(tail) elif not os.path.isfile(tail): from huggingface_hub import hf_hub_download
tail = hf_hub_download(tail, filename) return load_tail_file(tail)
def release_state_dict(sd: dict[str, torch.Tensor], dtype: torch.dtype = torch.bfloat16) -> dict[str, torch.Tensor]: """Tail tensors in the released layout: unused keys dropped, Linear weights in `dtype`, the RMSNorm weights fp32.""" if dtype not in _DTYPES.values(): raise ValueError(f"dtype must be bfloat16 or float32, got {dtype}") return {n: v.detach().to(torch.float32 if keeps_fp32(n) else dtype).contiguous().clone() for n, v in sorted(clean_state_dict(sd).items())}
def export_tail(src: str, out_path: str, dtype: torch.dtype = torch.bfloat16, base_repo: str = BASE_REPO) -> dict[str, str]: """Re-write a tail file (e.g. the fp32 export) as a release file with clean metadata. Returns the metadata.""" from safetensors.torch import save_file
sd, _ = load_tail_file(src) out = release_state_dict(sd, dtype) meta = build_metadata(count_blocks(out), dtype, base_repo) os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True) save_file(out, out_path, metadata=meta) return meta123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Oklab round trip, head patch layout, uint8 rounding, and the turbo sampler constants."""
import jsonimport osimport sys
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src"))
import torch # noqa: E402
def test_oklab_round_trip(): from pq_image_dwd.color import oklab_norm_to_srgb, srgb_to_oklab_norm
g = torch.Generator().manual_seed(0) x = torch.rand(2, 3, 8, 8, generator=g, dtype=torch.float64) * 2 - 1 assert torch.allclose(oklab_norm_to_srgb(srgb_to_oklab_norm(x)), x, atol=1e-6) # white and black land on the normalized Oklab constants white = srgb_to_oklab_norm(torch.ones(1, 3, 1, 1, dtype=torch.float64))[:, :, 0, 0] black = srgb_to_oklab_norm(-torch.ones(1, 3, 1, 1, dtype=torch.float64))[:, :, 0, 0] assert torch.allclose(white, torch.tensor([[(1 - 0.56) / 0.16, 0.0, -0.01 / 0.16]], dtype=torch.float64), atol=1e-6) assert torch.allclose(black, torch.tensor([[-0.56 / 0.16, 0.0, -0.01 / 0.16]], dtype=torch.float64), atol=1e-6)
def test_patch_layout(): from pq_image_dwd.color import head_to_srgb, oklab_norm_to_srgb, patchify, unpatchify
x = torch.arange(2 * 3 * 32 * 48, dtype=torch.float32).reshape(2, 3, 32, 48) y = patchify(x) assert y.shape == (2, 2 * 3, 768) assert torch.equal(unpatchify(y, 2, 3), x) # token 1 is the tile at row 0, column 1; its first 256 values are channel 0 of that tile, row-major assert torch.equal(y[0, 1, :256], x[0, 0, :16, 16:32].reshape(-1)) yb = torch.randn(1, 6, 768).to(torch.bfloat16) assert torch.equal(head_to_srgb(yb, 2, 3), oklab_norm_to_srgb(unpatchify(yb.float(), 2, 3)).clamp(-1, 1))
def test_to_uint8(): from pq_image_dwd.color import to_uint8
x = torch.tensor([-1.0, -0.5, 0.0, 1.0, 2.0]).view(1, 1, 1, 5).expand(1, 3, 1, 5) u = to_uint8(x) assert u.shape == (1, 1, 5, 3) and u.dtype == torch.uint8 assert u[0, 0, :, 0].tolist() == [0, 64, 128, 255, 255]
def test_sigmas_and_timesteps(tmp_path): from pq_image_dwd import schedule as S
assert S.STEPS == 8 and S.HEAD_SIGMA == 0.414568 (tmp_path / "model_index.json").write_text(json.dumps({"sample_sigmas": S.SIGMAS})) assert S.sample_sigmas(str(tmp_path)) == S.SIGMAS assert S.sample_sigmas(None) == S.SIGMAS # the head step's timestep after the stock bf16 rounding t = S.model_timestep(torch.tensor([S.HEAD_SIGMA])) assert t.dtype == torch.bfloat16 and float(t) == 0.4140625123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""DWDPipeline on a tiny CPU model (random weights, no downloads):
- steps 1-7 (and the optional stock last step + VAE) are exactly the stock QwenImage21Pipeline denoising loop, with and without its prefix KV cache, for text-to-image and editing;- the prefix at the last step is exactly the stock forward's hidden states entering the tail's first block;- the tail loaded from the bf16 release file gives exactly the head output of the fp32 weights under bf16 autocast (the evaluated computation), and the earlier fp32 file gives the same image."""
import osimport sys
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src"))sys.path.insert(0, HERE)
import pytest # noqa: E402import torch # noqa: E402
pytest.importorskip("diffusers")pytest.importorskip("safetensors")
from tiny import C_LAT, K, TinyText, TinyVAE, sched, tiny_tail_state, tiny_transformer # noqa: E402
W, H = 64, 32 # pixels -> 4 x 2 tokens
def _legacy_file(tmp_path, tr, name="legacy.safetensors"): """The earlier export's layout: fp32 tensors incl. an unused proj_out, metadata without a `format` key.""" from safetensors.torch import save_file
sd = tiny_tail_state(tr) path = str(tmp_path / name) save_file(sd, path, metadata={"base_model": "Qwen/Qwen-Image-2.1-Turbo", "k": str(K), "weights": "ema"}) return path, sd
def _release_file(tmp_path, legacy): from pq_image_dwd.weights import export_tail
out = str(tmp_path / "dwd_tail.safetensors") export_tail(legacy, out) return out
def _pipe(tail, vae=None): from pq_image_dwd.pipeline import DWDPipeline
return DWDPipeline.from_components(tiny_transformer(0), tail, TinyText(), sched(), vae=vae or TinyVAE(), device="cpu")
def _stock_loop(tr, cond, h, w, seed, steps, kv: bool): """QwenImage21Pipeline.__call__ steps 3-5 re-typed: prepare_latents, retrieve_timesteps with the turbo sigmas, timestep cast, transformer call (prefix KV cache extract / cached), scheduler.step. Runs `steps` steps.""" from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21KVCache from diffusers.utils.torch_utils import randn_tensor
from pq_image_dwd import schedule as S
sch = sched() gen = torch.Generator("cpu").manual_seed(seed) lat = randn_tensor((1, 1, C_LAT, h, w), generator=gen, device=torch.device("cpu"), dtype=torch.bfloat16) lat = lat.view(1, C_LAT, h * w).transpose(1, 2) sch.set_timesteps(sigmas=S.SIGMAS, device="cpu", mu=0.9) sch.set_begin_index(0) img_mask = torch.cat([cond.img_mask, cond.img_mask.new_ones(1, h * w // 4)], 1) shapes = [[*cond.cond_shapes, (1, h, w)]] cache = QwenImage21KVCache(len(tr.transformer_blocks)) if kv else None with torch.no_grad(): for i, t in enumerate(sch.timesteps[:steps]): inp = lat if cond.cond_lat is None else torch.cat([cond.cond_lat, lat], 1) timestep = t.expand(1).to(lat.dtype) v = tr(hidden_states=inp, timestep=timestep / 1000, encoder_hidden_states=cond.embeds, encoder_hidden_states_mask=cond.mask, img_shapes=shapes, img_mask=img_mask, kv_cache=cache, kv_cache_mode=None if cache is None else ("extract" if i == 0 else "cached"), return_dict=False)[0][:, -h * w:] lat = sch.step(v, t, lat, return_dict=False)[0] return lat
def _captured_prefix(tr, lat, cond, h, w, n_prefix): """Run the stock forward (no cache) at the last sigma and capture the hidden states entering block n_prefix.""" from pq_image_dwd import schedule as S
cap = {}
def hook(mod, args, kwargs): cap["hs"] = kwargs["hidden_states"].clone()
hk = tr.transformer_blocks[n_prefix].register_forward_pre_hook(hook, with_kwargs=True) t = torch.tensor([S.SIGMAS[-1] * 1000], dtype=torch.float32).to(torch.bfloat16) / 1000 inp = lat if cond.cond_lat is None else torch.cat([cond.cond_lat, lat], 1) with torch.no_grad(): tr(hidden_states=inp, timestep=t, encoder_hidden_states=cond.embeds, encoder_hidden_states_mask=cond.mask, img_shapes=[[*cond.cond_shapes, (1, h, w)]], img_mask=torch.cat([cond.img_mask, cond.img_mask.new_ones(1, h * w // 4)], 1), return_dict=False) hk.remove() return cap["hs"], t
def _edit_image(seed=3, size=(64, 32)): import numpy as np from PIL import Image
rng = np.random.default_rng(seed) return Image.fromarray(rng.integers(0, 255, (size[1], size[0], 3), dtype=np.uint8))
@pytest.mark.parametrize("edit", [False, True])def test_steps_are_the_stock_pipeline(tmp_path, edit): from pq_image_dwd.color import to_uint8
legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) cond = pipe.encode("a cat on a mat", [_edit_image()] if edit else None, output_resolution=48) if edit: assert cond.cond_lat is not None and cond.cond_shapes == ((1, 2, 4),) h, w = H // 16, W // 16 o = pipe.generate(cond, h, w, seed=5, dwd=False, vae=True) tr = tiny_transformer(0) for kv in (True, False): assert torch.equal(_stock_loop(tr, cond, h, w, 5, 7, kv), o["lat_last"]) ref = _stock_loop(tr, cond, h, w, 5, 8, kv) assert torch.equal(to_uint8(TinyVAE().decode(ref, h, w)), o["vae"]) o2 = pipe.generate(cond, h, w, seed=5, dwd=False, vae=True, use_kv_cache=False) assert torch.equal(o2["vae"], o["vae"]) if edit: # the condition image matters other = pipe.encode("a cat on a mat", [_edit_image(seed=4)], output_resolution=48) assert not torch.equal(pipe.generate(other, h, w, seed=5, dwd=False)["lat_last"], o["lat_last"])
@pytest.mark.parametrize("edit", [False, True])def test_prefix_is_the_stock_forward(tmp_path, edit): from pq_image_dwd.model import prefix_forward
legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) cond = pipe.encode("a dog", [_edit_image()] if edit else None, output_resolution=48) h, w = H // 16, W // 16 lat = pipe.generate(cond, h, w, seed=2, dwd=False)["lat_last"] ref, t = _captured_prefix(tiny_transformer(0), lat, cond, h, w, pipe.n_prefix) hs, ctx = prefix_forward(pipe.transformer, pipe.n_prefix, lat, cond, t, h, w) assert torch.equal(hs, ref) assert ctx.n_txt == hs.shape[1] - h * w
@pytest.mark.parametrize("edit", [False, True])def test_head_is_the_fp32_autocast_path(tmp_path, edit): """The pipeline image == stock steps 1-7, captured stock prefix, the fp32 tail under bf16 autocast (the evaluated computation), Oklab -> sRGB -> uint8. Holds for the bf16 release file and for the fp32 file.""" from pq_image_dwd.color import head_to_srgb, to_uint8 from pq_image_dwd.model import DWDTail from pq_image_dwd.pipeline import fp32_time_freqs
tr = tiny_transformer(0) legacy, sd = _legacy_file(tmp_path, tr) release = _release_file(tmp_path, legacy) pipe = _pipe(release) image = [_edit_image()] if edit else None img = pipe("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt") assert img.shape == (H, W, 3) and img.dtype == torch.uint8
cond = pipe.encode("a cat", image, output_resolution=48) h, w = H // 16, W // 16 lat = _stock_loop(tr, cond, h, w, 3, 7, kv=True) hs, t = _captured_prefix(tr, lat, cond, h, w, pipe.n_prefix) ref_tail = DWDTail.for_transformer(tr, K, device="cpu") ref_tail.load_state_dict({n: v for n, v in sd.items() if n != "proj_out.weight"}) # fp32 weights ref_tail.time_text_embed.time_proj.freqs = fp32_time_freqs(tr) assert all(p.dtype == torch.float32 for p in ref_tail.parameters()) from pq_image_dwd.model import build_ctx
ctx = build_ctx(tr, cond, h, w, "cpu")[0] with torch.no_grad(): y = ref_tail(hs, t, ctx) assert torch.equal(to_uint8(head_to_srgb(y, h, w))[0], img) # the fp32 file gives the same image assert torch.equal(_pipe(legacy)("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt"), img) # and the return_vae image is the stock pipeline's d, v = pipe("a cat", image=image, width=W, height=H, seed=3, output_resolution=48, output_type="pt", return_vae=True) assert torch.equal(d, img) assert torch.equal(v, to_uint8(TinyVAE().decode(_stock_loop(tr, cond, h, w, 3, 8, kv=True), h, w))[0])
def test_tail_dtypes_and_stock_model_untouched(tmp_path): tr0 = tiny_transformer(0) legacy, _ = _legacy_file(tmp_path, tr0) pipe = _pipe(_release_file(tmp_path, legacy)) assert pipe.k == K and pipe.n_prefix == len(tr0.transformer_blocks) - K assert len(pipe.transformer.transformer_blocks) == len(tr0.transformer_blocks) assert pipe.transformer.norm_out is not None and pipe.transformer.proj_out is not None for (n, a), (_, b) in zip(pipe.transformer.state_dict().items(), tr0.state_dict().items()): assert torch.equal(a, b), n for n, p in pipe.tail.named_parameters(): want = torch.float32 if n.endswith(("norm_q.weight", "norm_k.weight")) else torch.bfloat16 assert p.dtype == want and not p.requires_grad and not p.is_meta, n assert pipe.tail.time_text_embed.time_proj.freqs.dtype == torch.float32 assert not hasattr(pipe.tail, "proj_out")
def test_inputs_and_outputs(tmp_path): import numpy as np from PIL import Image
legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) a = pipe("a cat", width=W, height=H, seed=0) assert isinstance(a, Image.Image) and a.size == (W, H) b = pipe(["a cat", "a dog"], width=W, height=H, seed=0, output_type="np") assert len(b) == 2 and b[0].shape == (H, W, 3) and b[0].dtype == np.uint8 assert np.array_equal(b[0], np.asarray(a)) # first prompt uses seed 0 c = pipe("a dog", width=W, height=H, seed=1, output_type="np") assert np.array_equal(b[1], c) # second prompt uses seed + 1 assert not np.array_equal(pipe("a cat", width=W, height=H, seed=1, output_type="np"), b[0]) for bad in ((48, 32), (64, 16), (-32, 32)): with pytest.raises(ValueError): pipe("a cat", width=bad[0], height=bad[1]) with pytest.raises(ValueError): pipe("a cat", width=W, height=H, output_type="latent") # editing: the output size defaults to about output_resolution^2 at the condition image's aspect e = pipe("make it snowy", image=_edit_image(size=(128, 64)), seed=0, output_resolution=48) assert e.size == (64, 32) # a file of another format, and a tail with a different block count than its metadata says, are rejected from safetensors.torch import save_file
from pq_image_dwd.weights import build_metadata, check_metadata, load_tail_file
with pytest.raises(ValueError): check_metadata({"format": "something-else"}) sd = {k: v for k, v in tiny_tail_state(tiny_transformer(0)).items() if k != "proj_out.weight"} bad = str(tmp_path / "k_mismatch.safetensors") save_file(sd, bad, metadata=build_metadata(K + 1, torch.float32)) with pytest.raises(ValueError, match="blocks"): load_tail_file(bad)
def test_compile_flag_does_not_change_the_image(tmp_path): pytest.importorskip("torch._dynamo") legacy, _ = _legacy_file(tmp_path, tiny_transformer(0)) pipe = _pipe(legacy) ref = pipe("a cat", width=W, height=H, seed=0, output_type="pt") try: pipe.enable_compile() out = pipe("a cat", width=W, height=H, seed=0, output_type="pt") except Exception as e: # no compiler toolchain on this machine pytest.skip(f"torch.compile unavailable: {type(e).__name__}") assert (out.int() - ref.int()).abs().max() <= 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Tail file export and loading: the release file drops the unused proj_out, stores Linear weights in bf16 and theattention RMSNorm weights in fp32, carries clean metadata, and loads to the same tail as the fp32 file."""
import jsonimport osimport sys
HERE = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, os.path.join(os.path.dirname(HERE), "src"))sys.path.insert(0, HERE)
import pytest # noqa: E402import torch # noqa: E402
pytest.importorskip("diffusers")pytest.importorskip("safetensors")
from tiny import K, tiny_tail_state, tiny_transformer # noqa: E402
def _legacy(tmp_path): from safetensors.torch import save_file
sd = tiny_tail_state(tiny_transformer(0)) p = str(tmp_path / "legacy.safetensors") save_file(sd, p, metadata={"base_model": "Qwen/Qwen-Image-2.1-Turbo", "k": str(K), "weights": "ema", "step": "1"}) return p, sd
def test_export_layout_and_metadata(tmp_path): from safetensors import safe_open
from pq_image_dwd.weights import FORMAT, export_tail, load_tail_file
legacy, sd = _legacy(tmp_path) out = str(tmp_path / "dwd_tail.safetensors") meta = export_tail(legacy, out) with safe_open(out, framework="pt") as f: stored = f.metadata() keys = set(f.keys()) dt = {k: f.get_tensor(k).dtype for k in keys} assert stored == meta assert set(stored) == {"format", "format_version", "base_repo", "k", "steps", "head_sigma", "patch", "head_layout", "color", "oklab_mean", "oklab_std", "weights", "dtype", "compute"} assert stored["format"] == FORMAT and stored["k"] == str(K) and stored["steps"] == "8" assert stored["base_repo"] == "Qwen/Qwen-Image-2.1-Turbo" and stored["dtype"] == "bfloat16" assert json.loads(stored["oklab_mean"]) == [0.56, 0.0, 0.01] and float(stored["head_sigma"]) == 0.414568 assert keys == set(sd) - {"proj_out.weight"} for k, d in dt.items(): assert d == (torch.float32 if k.endswith(("norm_q.weight", "norm_k.weight")) else torch.bfloat16), k a, ma = load_tail_file(out) b, mb = load_tail_file(legacy) assert "proj_out.weight" not in b and set(a) == set(b) assert ma["k"] == mb["k"] == K and mb["format"] == FORMAT # bf16 storage is the round-to-nearest of the fp32 weights (what bf16 autocast computes with) for k in a: want = b[k] if k.endswith(("norm_q.weight", "norm_k.weight")) else b[k].to(torch.bfloat16) assert torch.equal(a[k], want), k
def test_fp32_export_and_rejections(tmp_path): from safetensors.torch import save_file
from pq_image_dwd.weights import export_tail, load_tail, load_tail_file
legacy, sd = _legacy(tmp_path) out = str(tmp_path / "fp32.safetensors") meta = export_tail(legacy, out, dtype=torch.float32) assert meta["dtype"] == "float32" assert all(v.dtype == torch.float32 for v in load_tail_file(out)[0].values()) # a directory holding dwd_tail.safetensors d = tmp_path / "repo" d.mkdir() export_tail(legacy, str(d / "dwd_tail.safetensors")) assert load_tail(str(d))[1]["k"] == K with pytest.raises(FileNotFoundError): load_tail(str(tmp_path / "missing.safetensors")) # wrong format, wrong head layout, stray tensors bad = str(tmp_path / "bad.safetensors") save_file({"x": torch.zeros(1)}, bad, metadata={"format": "dwd-klein-tail"}) with pytest.raises(ValueError): load_tail_file(bad) save_file({**sd, "extra.weight": torch.zeros(1)}, bad) with pytest.raises(ValueError): load_tail_file(bad) m = dict(meta) m["head_layout"] = "(p1,p2,c)" save_file({k: v for k, v in sd.items() if k != "proj_out.weight"}, bad, metadata=m) with pytest.raises(ValueError): load_tail_file(bad)
def test_tail_rejects_mismatched_weights(): from pq_image_dwd.model import DWDTail
tr = tiny_transformer(0) sd = {k: v for k, v in tiny_tail_state(tr).items() if k != "proj_out.weight"} t = DWDTail.for_transformer(tr, K) with pytest.raises(KeyError): t.load_weights({k: v for k, v in sd.items() if k != "head.bias"}, tr.time_text_embed.time_proj.freqs) t = DWDTail.for_transformer(tr, K + 1) with pytest.raises(KeyError): t.load_weights(sd, tr.time_text_embed.time_proj.freqs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Tiny CPU stand-ins for the real components (random weights, no downloads). Imported by the tests after they putsrc/ and tests/ on sys.path."""
from __future__ import annotations
import zlib
import torchimport torch.nn as nnimport torch.nn.functional as F
JOINT = 24C_LAT = 64K = 2
def tiny_transformer(seed: int = 0, n_layers: int = 4): """A small QwenImage21Transformer2DModel in bf16 with its timestep table in fp32, as from_pretrained(torch_dtype= bf16) loads the real one.""" from diffusers import QwenImage21Transformer2DModel
torch.manual_seed(seed) m = QwenImage21Transformer2DModel(patch_size=1, in_channels=C_LAT, out_channels=C_LAT, num_layers=n_layers, attention_head_dim=16, num_attention_heads=2, context_in_dim=JOINT, mlp_ratio=3, axes_dims_rope=(4, 6, 6), causal_condition=True) with torch.no_grad(): # non-trivial modulations / zero-centred norms for p in m.parameters(): p.add_(0.02 * torch.randn_like(p)) freqs = m.time_text_embed.time_proj.freqs.float().clone() m = m.to(torch.bfloat16).eval() m.time_text_embed.time_proj.freqs = freqs return m
def tiny_tail_state(transformer, k: int = K, seed: int = 1, proj_out: bool = True) -> dict[str, torch.Tensor]: """A trained-looking fp32 tail state dict (the layout of the fp32 export): copies of the transformer's last k blocks, time embedding, modulation and norm_out, perturbed, plus a random head and (optionally) proj_out.""" g = torch.Generator().manual_seed(seed) n = len(transformer.transformer_blocks) sd = {} for i, b in enumerate(transformer.transformer_blocks[n - k:]): for name, v in b.state_dict().items(): sd[f"blocks.{i}.{name}"] = v.float() for part in ("time_text_embed", "modulation", "norm_out"): for name, v in getattr(transformer, part).state_dict().items(): sd[f"{part}.{name}"] = v.float() sd = {n_: v + 0.01 * torch.randn(v.shape, generator=g) for n_, v in sd.items()} D = transformer.config.num_attention_heads * transformer.config.attention_head_dim sd["head.weight"] = 0.05 * torch.randn(768, D, generator=g) sd["head.bias"] = 0.05 * torch.randn(768, generator=g) if proj_out: sd["proj_out.weight"] = transformer.proj_out.weight.float() + 0.01 * torch.randn( transformer.proj_out.weight.shape, generator=g) return sd
class TinyText: """(prompt, images) -> (embeds [1, L, JOINT] bf16, None, img_mask): deterministic per prompt (crc32 seed). With condition images, one vision-language slot per 2x2 latent tokens of each image is inserted after two text tokens, as the stock template places the image before the instruction."""
def __call__(self, prompt, images=None): crc = zlib.crc32(prompt.encode()) g = torch.Generator().manual_seed(crc) txt = torch.randn(4 + crc % 4, JOINT, generator=g) mask = torch.zeros(txt.shape[0], dtype=torch.bool) if images: slots = sum((im.size[0] // 16) * (im.size[1] // 16) // 4 for im in images) s = torch.randn(slots, JOINT, generator=g) txt = torch.cat([txt[:2], s, txt[2:]]) mask = torch.cat([mask[:2], torch.ones(slots, dtype=torch.bool), mask[2:]]) return txt[None].to(torch.bfloat16), None, mask[None]
class TinyVAE(nn.Module): """encode_vae_input: [B, 4, 1, H, W] -> packed [B, (H/16)(W/16), 64] via a 16x16 average pool and a fixed linear map; decode: packed [B, h*w, 64] -> [B, 3, 16h, 16w] in [-1, 1] (first 3 channels, nearest x16)."""
has_decoder = True
def __init__(self, seed: int = 1): super().__init__() g = torch.Generator().manual_seed(seed) self.register_buffer("w", torch.randn(C_LAT, 4, generator=g) * 0.5)
@torch.no_grad() def encode_vae_input(self, x): p = F.avg_pool2d(x[:, :, 0].float(), 16) # [B, 4, h, w] B, C, h, w = p.shape return (p.reshape(B, C, h * w).permute(0, 2, 1) @ self.w.t()).to(torch.bfloat16)
@torch.no_grad() def decode(self, lat, h, w): x = lat.float()[..., :3].permute(0, 2, 1).reshape(lat.shape[0], 3, h, w) return torch.tanh(F.interpolate(x, scale_factor=16, mode="nearest"))
def sched(): from diffusers import FlowMatchEulerDiscreteScheduler
# the turbo checkpoint's scheduler_config.json return FlowMatchEulerDiscreteScheduler(base_image_seq_len=256, base_shift=0.5, max_image_seq_len=8192, max_shift=0.9, shift=1.0, time_shift_type="exponential", use_dynamic_shifting=False).gitattributes+4
.gitignoreAdded+31
CITATION.cffAdded+60
LICENSEAdded+55
LICENSE-APACHEAdded+201
NOTICEAdded+22
README.mdAdded+365
assets/P-Q-Image-2.1-Turbo-DWD.jpgAdded

Large File Pointer Details
- SHA256: f0de9db5a7d6df250a0a5f89d8dae5d4928dbaa79d286308b6ac15430c1bf76a
- Pointer size: 131 Bytes
- Size of remote file: 710 kB
assets/benchmark.jsonAdded+143
assets/examples/crop_edit_snow.pngAdded

Large File Pointer Details
- SHA256: 0f617e6b0b3fc712bf13b056e39ca6a5da86d8ab90ee4e1181bcd89ae3aa9b61
- Pointer size: 132 Bytes
- Size of remote file: 1.01 MB
assets/examples/crop_fox.pngAdded

Large File Pointer Details
- SHA256: 045254ed89e908d7dc622735802db88853e30af5348fa4e865abc586126bc619
- Pointer size: 132 Bytes
- Size of remote file: 1.26 MB
assets/examples/crop_portrait.pngAdded

Large File Pointer Details
- SHA256: 2463f1ac298ac75ac35bd8ffcda581a4b108392b13894fb5cbcd8825353b2f02
- Pointer size: 132 Bytes
- Size of remote file: 1.04 MB
assets/examples/crop_street.pngAdded

Large File Pointer Details
- SHA256: 8ec667b3644202ec92901f782a3d62525152be48e56df823d71593685c5d9bf2
- Pointer size: 131 Bytes
- Size of remote file: 619 kB
assets/examples/edit_0.jpgAdded

Large File Pointer Details
- SHA256: 22b9a85bbfa39facc8d160e0c9bafe1ae559e1369be7aa3780d2032b121e9331
- Pointer size: 131 Bytes
- Size of remote file: 376 kB
assets/examples/edit_1.jpgAdded

Large File Pointer Details
- SHA256: 06fe198b240efe29e252dfad6f4814f1b9877c45efaf3a5d4ed6b2413721b310
- Pointer size: 131 Bytes
- Size of remote file: 333 kB
assets/examples/edit_2.jpgAdded

Large File Pointer Details
- SHA256: 33cd30562462fddc3e2854d0ff504a4d15b8167bbc96dea0dc218c2c853c1cbc
- Pointer size: 131 Bytes
- Size of remote file: 522 kB
assets/examples/edit_3.jpgAdded

Large File Pointer Details
- SHA256: 694a5027fd00d90f815a3c6a7ecaca1bb0daf5c36467655b8b959937531acf9e
- Pointer size: 131 Bytes
- Size of remote file: 429 kB
assets/examples/examples.jsonAdded+138
assets/examples/t2i_0.jpgAdded

Large File Pointer Details
- SHA256: 4d1df173401c92f09d99f56ed34f3a70a3895d83777e9678a35d754a30a179c8
- Pointer size: 131 Bytes
- Size of remote file: 484 kB
assets/examples/t2i_1.jpgAdded

Large File Pointer Details
- SHA256: 6011e33707634dd5b36fa016c1001a07ddde3e019754aa4ba8dce70c22fc8770
- Pointer size: 131 Bytes
- Size of remote file: 214 kB
assets/examples/t2i_2.jpgAdded

Large File Pointer Details
- SHA256: cd51efae38df5f25ef0ed22838435c653d6e70b270bad7648293caa187035b29
- Pointer size: 131 Bytes
- Size of remote file: 277 kB
assets/examples/t2i_3.jpgAdded

Large File Pointer Details
- SHA256: 8dcf7a017cbc7dfbb7a9690648559d108fbf31009a63711974faef325d4d0579
- Pointer size: 131 Bytes
- Size of remote file: 304 kB
assets/examples/t2i_4.jpgAdded

Large File Pointer Details
- SHA256: 3de8f4f3824a4338b5c2f91d672ff46e646260f0e649c3847161421f9249cc7c
- Pointer size: 131 Bytes
- Size of remote file: 282 kB
assets/examples/t2i_5.jpgAdded

Large File Pointer Details
- SHA256: e1ed71d933aea44b8516633f20ba11b069b5d190592dee6eeddd70ada704b29d
- Pointer size: 132 Bytes
- Size of remote file: 1.13 MB
config.jsonAdded+25
docs/usage.mdAdded+244
pyproject.tomlAdded+46
scripts/benchmark_latency.pyAdded+247
scripts/export_weights.pyAdded+55
scripts/generate.pyAdded+76
src/pq_image_dwd/__init__.pyAdded+26
src/pq_image_dwd/color.pyAdded+92
src/pq_image_dwd/encoders.pyAdded+141
src/pq_image_dwd/model.pyAdded+207
src/pq_image_dwd/pipeline.pyAdded+307
src/pq_image_dwd/schedule.pyAdded+38
src/pq_image_dwd/weights.pyAdded+145
tests/test_color_schedule.pyAdded+57
tests/test_pipeline.pyAdded+250
tests/test_weights.pyAdded+104
tests/tiny.pyAdded+104