Text-to-Image
Diffusion Single File
sdxl
sdxl-lightning
comfyui
convrot
int8
int6
w6a8
int4
w4a8
gptq
quantized
Instructions to use SUSSYEATING/SDXL-Lightning-ConvRot with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusion Single File
How to use SUSSYEATING/SDXL-Lightning-ConvRot with Diffusion Single File:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Commit ·
5d75b0d
0
Parent(s):
Keep clean single-commit release state
Browse files- .gitattributes +38 -0
- LICENSE.md +61 -0
- NOTICE +17 -0
- README.md +78 -0
- comparisons/lightning_p0_s42_4way.png +3 -0
- comparisons/lightning_p3_s42_4way.png +3 -0
- comparisons/lightning_p6_s42_4way.png +3 -0
- metrics/g4_lightning_int4_summary.json +130 -0
- metrics/g4_lightning_int6_summary.json +130 -0
- metrics/g4_lightning_int8_summary.json +130 -0
- scripts/calib_prompts.txt +32 -0
- scripts/convrot_pipeline.py +534 -0
- scripts/quantize_convrot_gptq.py +523 -0
- scripts/verify_sdxl_quant.py +250 -0
- sdxl-lightning-4step-int4-convrot.safetensors +3 -0
- sdxl-lightning-4step-int6-convrot.safetensors +3 -0
- sdxl-lightning-4step-int8-convrot.safetensors +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
comparisons/lightning_p0_s42_4way.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
comparisons/lightning_p3_s42_4way.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
comparisons/lightning_p6_s42_4way.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2024 Bytedance Inc.
|
| 2 |
+
Copyright (c) 2023 Stability AI
|
| 3 |
+
CreativeML Open RAIL++-M License dated July 26, 2023
|
| 4 |
+
|
| 5 |
+
Section I: PREAMBLE
|
| 6 |
+
Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
|
| 7 |
+
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
|
| 8 |
+
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
|
| 9 |
+
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this agreement aims to strike a balance between both in order to enable responsible open-science in the field of AI.
|
| 10 |
+
This CreativeML Open RAIL++-M License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
|
| 11 |
+
NOW THEREFORE, You and Licensor agree as follows:
|
| 12 |
+
Definitions
|
| 13 |
+
"License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
|
| 14 |
+
"Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
|
| 15 |
+
"Output" means the results of operating a Model as embodied in informational content resulting therefrom.
|
| 16 |
+
"Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
|
| 17 |
+
"Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
|
| 18 |
+
"Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
|
| 19 |
+
"Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
|
| 20 |
+
"Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
|
| 21 |
+
"You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
|
| 22 |
+
"Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
|
| 23 |
+
"Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model 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 Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
| 24 |
+
"Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
|
| 25 |
+
|
| 26 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
| 27 |
+
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in
|
| 28 |
+
|
| 29 |
+
Section III.
|
| 30 |
+
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, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
|
| 31 |
+
Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, 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 Model 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 Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
|
| 32 |
+
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
| 33 |
+
Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions: Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material. You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; You must cause any modified files to carry prominent notices stating that You changed the files; You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
|
| 34 |
+
Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
|
| 35 |
+
The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
|
| 36 |
+
|
| 37 |
+
Section IV: OTHER PROVISIONS
|
| 38 |
+
Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
|
| 39 |
+
Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
|
| 40 |
+
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (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 Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
|
| 41 |
+
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 Model and the Complementary Material (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.
|
| 42 |
+
Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material 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.
|
| 43 |
+
If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
|
| 44 |
+
|
| 45 |
+
END OF TERMS AND CONDITIONS
|
| 46 |
+
|
| 47 |
+
Attachment A
|
| 48 |
+
Use Restrictions
|
| 49 |
+
You agree not to use the Model or Derivatives of the Model:
|
| 50 |
+
In any way that violates any applicable national, federal, state, local or international law or regulation;
|
| 51 |
+
For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
|
| 52 |
+
To generate or disseminate verifiably false information and/or content with the purpose of harming others;
|
| 53 |
+
To generate or disseminate personal identifiable information that can be used to harm an individual;
|
| 54 |
+
To defame, disparage or otherwise harass others;
|
| 55 |
+
For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
|
| 56 |
+
For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
|
| 57 |
+
To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
|
| 58 |
+
For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
|
| 59 |
+
To provide medical advice and medical results interpretation;
|
| 60 |
+
To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
|
| 61 |
+
|
NOTICE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NOTICE — SDXL-Lightning 4-Step ConvRot Quantized Checkpoints
|
| 2 |
+
|
| 3 |
+
1. Upstream Attribution & Copyrights
|
| 4 |
+
- Base Model: ByteDance/SDXL-Lightning
|
| 5 |
+
URL: https://huggingface.co/ByteDance/SDXL-Lightning
|
| 6 |
+
Copyright (c) 2024 Bytedance Inc. & Copyright (c) 2023 Stability AI.
|
| 7 |
+
License: CreativeML Open RAIL++-M (see LICENSE.md).
|
| 8 |
+
|
| 9 |
+
2. Prominent Notice of Modifications (CreativeML Open RAIL++-M Section III)
|
| 10 |
+
These derivative model checkpoints modify the linear layers of the upstream UNet / diffusion_model weights via:
|
| 11 |
+
- Block Hadamard rotation (ConvRot) followed by row-wise symmetric INT8 ([-127, 127]) or INT6 ([-31, 31]) weight quantization, storing ComfyUI-compatible TensorCoreINT8Layout metadata (.weight_scale, .comfy_quant, _quantization_metadata).
|
| 12 |
+
- Optional sensitivity-ranked protection keeping the 80 most trajectory-sensitive linear layers in FP16 (659 / 739 quantized in sdxl-lightning-4step-int8-convrot and sdxl-lightning-4step-w6a8-int6-protected-convrot) vs all 739 linear layers quantized in sdxl-lightning-4step-w6a8-int6-all-convrot.
|
| 13 |
+
- Calibration bias correction applied to linear biases using 32 prompts (scripts/calib_prompts.txt). Conv2d, CLIP text encoders, and VAE remain unquantized in FP16.
|
| 14 |
+
- Bit-packed *-packed.safetensors files pack 4 signed 6-bit integer values per 3 uint8 bytes and restore losslessly via scripts/unpack_int6.py.
|
| 15 |
+
|
| 16 |
+
3. Use-Based Restrictions Notice (Section III Paragraph 5 & Attachment A)
|
| 17 |
+
All checkpoints in this repository are Derivatives of the Model governed by the CreativeML Open RAIL++-M License (see LICENSE.md), including the mandatory Use-Based Restrictions set forth in Paragraph 5 and Attachment A. Any downstream use, redistribution, hosting, or further modification must comply with and pass through those Use-Based Restrictions and include a copy of LICENSE.md and this NOTICE.
|
README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: openrail++
|
| 3 |
+
library_name: diffusion-single-file
|
| 4 |
+
base_model: ByteDance/SDXL-Lightning
|
| 5 |
+
base_model_relation: quantized
|
| 6 |
+
pipeline_tag: text-to-image
|
| 7 |
+
tags:
|
| 8 |
+
- sdxl
|
| 9 |
+
- sdxl-lightning
|
| 10 |
+
- comfyui
|
| 11 |
+
- diffusion-single-file
|
| 12 |
+
- convrot
|
| 13 |
+
- int8
|
| 14 |
+
- int6
|
| 15 |
+
- w6a8
|
| 16 |
+
- int4
|
| 17 |
+
- w4a8
|
| 18 |
+
- gptq
|
| 19 |
+
- quantized
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# SDXL-Lightning 4-Step ConvRot (INT8, INT6 & INT4) for ComfyUI
|
| 23 |
+
|
| 24 |
+
ConvRot-quantized single-file ComfyUI checkpoints of **[ByteDance/SDXL-Lightning](https://huggingface.co/ByteDance/SDXL-Lightning)** in three clean bit widths: **Full INT8**, **Full INT6 (`w6a8_int8`)**, and **Full INT4 (`asym_w4a8_int8`)**.
|
| 25 |
+
|
| 26 |
+
Built with **ConvRot (block Hadamard rotation)** + **Act-Order GPTQ Hessian error compensation** + **through-grid FP8 group-scale search / Lloyd-Max codebooks** + **calibration bias correction**, keeping Conv2d layers, text encoders (CLIP-L / OpenCLIP-G), and VAE unquantized in FP16.
|
| 27 |
+
|
| 28 |
+
**Related SDXL ConvRot repositories:**
|
| 29 |
+
- **[SUSSYEATING/SDXL-Base-1.0-ConvRot](https://huggingface.co/SUSSYEATING/SDXL-Base-1.0-ConvRot)** *(Open RAIL++-M)*
|
| 30 |
+
- **[SUSSYEATING/SDXL-Refiner-1.0-ConvRot](https://huggingface.co/SUSSYEATING/SDXL-Refiner-1.0-ConvRot)** *(Open RAIL++-M)*
|
| 31 |
+
- **[SUSSYEATING/SDXL-Turbo-ConvRot](https://huggingface.co/SUSSYEATING/SDXL-Turbo-ConvRot)** *(Stability AI Community License)*
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
---
|
| 35 |
+
|
| 36 |
+
## Available Checkpoints
|
| 37 |
+
|
| 38 |
+
| Precision Tier | File (`ComfyUI/models/checkpoints/`) | Size (vs 6.94 GB FP16) | Quantized UNet Linears |
|
| 39 |
+
| :--- | :--- | :---: | :--- |
|
| 40 |
+
| **Full INT8 ConvRot** | [`sdxl-lightning-4step-int8-convrot.safetensors`](./sdxl-lightning-4step-int8-convrot.safetensors) | **4.72 GB** (-32.0%) | 739 / 739 INT8 |
|
| 41 |
+
| **Full INT6 ConvRot** | [`sdxl-lightning-4step-int6-convrot.safetensors`](./sdxl-lightning-4step-int6-convrot.safetensors) | **4.31 GB** (-37.8%) | 658 / 739 INT6 (W6A8) + 81 INT8 (`K=640`/det) |
|
| 42 |
+
| **Full INT4 ConvRot** | [`sdxl-lightning-4step-int4-convrot.safetensors`](./sdxl-lightning-4step-int4-convrot.safetensors) | **3.77 GB** (-45.6%) | 658 / 739 INT4 (W4A8) + 81 INT8 (`K=640`/det) |
|
| 43 |
+
|
| 44 |
+
All files load directly in stock ComfyUI (`Load Checkpoint`, **ComfyUI >= v0.45.0**) using native `comfy-kitchen` CUDA kernels — no extra nodes or unpacking required. *(For SDXL Base/Lightning/Turbo, 80 small `K=640` linear layers plus the single architecture-detection `to_k` key remain in ConvRot INT8 because `comfy-kitchen` `w6a8`/`w4a8` kernels require `K % 256 == 0`.)*
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
## Visual Comparisons (4 steps, `sgm_uniform`, 1024x1024)
|
| 49 |
+
|
| 50 |
+

|
| 51 |
+

|
| 52 |
+

|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## Evaluation Metrics (8 prompts x 1024x1024, ComfyUI v0.45.3)
|
| 57 |
+
|
| 58 |
+
Measured via [`scripts/verify_sdxl_quant.py`](./scripts/verify_sdxl_quant.py) directly against unquantized FP16 (`sdxl_lightning_4step.safetensors`):
|
| 59 |
+
- **Unquantized BF16 Reference (vs FP16):** Cosine `0.99348` (min `0.97744`), SSIM `0.94868` (min `0.90096`), PSNR `32.76 dB` (min `29.26 dB`)
|
| 60 |
+
|
| 61 |
+
| Precision Tier | Cosine Mean / Min | SSIM Mean / Min | PSNR Mean / Min | Warm Speed/Img | Report |
|
| 62 |
+
| :--- | :---: | :---: | :---: | :---: | :--- |
|
| 63 |
+
| **Full INT8 ConvRot** | **0.99290** / 0.98239 | **0.94852** / 0.90629 | **32.48** / 26.80 dB | 0.37s | [`g4_lightning_int8_summary.json`](./metrics/g4_lightning_int8_summary.json) |
|
| 64 |
+
| **Full INT6 ConvRot** | **0.98989** / 0.95676 | **0.93520** / 0.84038 | **32.03** / 26.34 dB | 0.40s | [`g4_lightning_int6_summary.json`](./metrics/g4_lightning_int6_summary.json) |
|
| 65 |
+
| **Full INT4 ConvRot** | **0.96818** / 0.93316 | **0.85894** / 0.78216 | **25.44** / 22.99 dB | 0.41s | [`g4_lightning_int4_summary.json`](./metrics/g4_lightning_int4_summary.json) |
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## How to Use in ComfyUI
|
| 70 |
+
|
| 71 |
+
1. Download **INT8**, **INT6**, or **INT4** `.safetensors` into `ComfyUI/models/checkpoints/`.
|
| 72 |
+
2. Load directly with ComfyUI's built-in **`Load Checkpoint`** node (`ComfyUI >= v0.45.0`).
|
| 73 |
+
|
| 74 |
+
---
|
| 75 |
+
|
| 76 |
+
## License & Use Restrictions (CreativeML Open RAIL++-M)
|
| 77 |
+
|
| 78 |
+
All checkpoints in this repository are **Derivatives of the Model** under the **[CreativeML Open RAIL++-M License](./LICENSE.md)** (Copyright © 2024 Bytedance Inc.; Copyright © 2023 Stability AI). See [`NOTICE`](./NOTICE) for full attributions and modification details, and pass through [`LICENSE.md`](./LICENSE.md) and [`NOTICE`](./NOTICE) with any redistribution.
|
comparisons/lightning_p0_s42_4way.png
ADDED
|
Git LFS Details
|
comparisons/lightning_p3_s42_4way.png
ADDED
|
Git LFS Details
|
comparisons/lightning_p6_s42_4way.png
ADDED
|
Git LFS Details
|
metrics/g4_lightning_int4_summary.json
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"summary": {
|
| 3 |
+
"q_cos": {
|
| 4 |
+
"mean": 0.968182162104067,
|
| 5 |
+
"min": 0.9331587040078793
|
| 6 |
+
},
|
| 7 |
+
"q_ssim": {
|
| 8 |
+
"mean": 0.8589395955204964,
|
| 9 |
+
"min": 0.7821643352508545
|
| 10 |
+
},
|
| 11 |
+
"q_psnr": {
|
| 12 |
+
"mean": 25.444590388512754,
|
| 13 |
+
"min": 22.99291939460497
|
| 14 |
+
},
|
| 15 |
+
"b_cos": {
|
| 16 |
+
"mean": 0.9934811761192526,
|
| 17 |
+
"min": 0.9774430311345284
|
| 18 |
+
},
|
| 19 |
+
"b_ssim": {
|
| 20 |
+
"mean": 0.9486830607056618,
|
| 21 |
+
"min": 0.9009554982185364
|
| 22 |
+
},
|
| 23 |
+
"b_psnr": {
|
| 24 |
+
"mean": 32.76348619085778,
|
| 25 |
+
"min": 29.262203485754593
|
| 26 |
+
},
|
| 27 |
+
"mode": "lightning",
|
| 28 |
+
"fp16": "sdxl_lightning_4step.safetensors",
|
| 29 |
+
"quant": "sdxl-lightning-4step-int4-convrot.safetensors",
|
| 30 |
+
"steps": 4,
|
| 31 |
+
"size": 1024,
|
| 32 |
+
"renders": 8,
|
| 33 |
+
"fp16_bytes": 6938040682,
|
| 34 |
+
"quant_bytes": 3772875825,
|
| 35 |
+
"timing": {
|
| 36 |
+
"fp16": {
|
| 37 |
+
"quantized_layers": 0,
|
| 38 |
+
"total_layers": 794,
|
| 39 |
+
"total_s": 2.2258992195129395,
|
| 40 |
+
"warm_mean_s": 0.15113420514288528
|
| 41 |
+
},
|
| 42 |
+
"bf16": {
|
| 43 |
+
"quantized_layers": 0,
|
| 44 |
+
"total_layers": 794,
|
| 45 |
+
"total_s": 1.8416118621826172,
|
| 46 |
+
"warm_mean_s": 0.1482163002856396
|
| 47 |
+
},
|
| 48 |
+
"quant": {
|
| 49 |
+
"quantized_layers": 739,
|
| 50 |
+
"total_layers": 794,
|
| 51 |
+
"total_s": 4.301131010055542,
|
| 52 |
+
"warm_mean_s": 0.4102858932853581
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"rows": [
|
| 57 |
+
{
|
| 58 |
+
"key": "p0_s42",
|
| 59 |
+
"q_cos": 0.9686206785676874,
|
| 60 |
+
"q_ssim": 0.8825349807739258,
|
| 61 |
+
"q_psnr": 24.84008534206055,
|
| 62 |
+
"b_cos": 0.9958390972649831,
|
| 63 |
+
"b_ssim": 0.9647495150566101,
|
| 64 |
+
"b_psnr": 34.071319153766815
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"key": "p1_s42",
|
| 68 |
+
"q_cos": 0.973850067035869,
|
| 69 |
+
"q_ssim": 0.8995558619499207,
|
| 70 |
+
"q_psnr": 25.80669103565228,
|
| 71 |
+
"b_cos": 0.9957289018420392,
|
| 72 |
+
"b_ssim": 0.9649030566215515,
|
| 73 |
+
"b_psnr": 33.94747884338996
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"key": "p2_s42",
|
| 77 |
+
"q_cos": 0.9609567494998388,
|
| 78 |
+
"q_ssim": 0.82905513048172,
|
| 79 |
+
"q_psnr": 22.99291939460497,
|
| 80 |
+
"b_cos": 0.9955180320099095,
|
| 81 |
+
"b_ssim": 0.9483562111854553,
|
| 82 |
+
"b_psnr": 31.2901873584441
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"key": "p3_s42",
|
| 86 |
+
"q_cos": 0.9899565425658435,
|
| 87 |
+
"q_ssim": 0.9088268280029297,
|
| 88 |
+
"q_psnr": 30.825079842310647,
|
| 89 |
+
"b_cos": 0.9990687437592017,
|
| 90 |
+
"b_ssim": 0.9715254902839661,
|
| 91 |
+
"b_psnr": 37.40556777464224
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"key": "p4_s42",
|
| 95 |
+
"q_cos": 0.9635566571955309,
|
| 96 |
+
"q_ssim": 0.7821643352508545,
|
| 97 |
+
"q_psnr": 24.32321830932786,
|
| 98 |
+
"b_cos": 0.9939828308172979,
|
| 99 |
+
"b_ssim": 0.9297152161598206,
|
| 100 |
+
"b_psnr": 31.24327770020377
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"key": "p5_s42",
|
| 104 |
+
"q_cos": 0.9869676777522904,
|
| 105 |
+
"q_ssim": 0.9415023922920227,
|
| 106 |
+
"q_psnr": 27.104734888064648,
|
| 107 |
+
"b_cos": 0.9981210218620029,
|
| 108 |
+
"b_ssim": 0.9780817031860352,
|
| 109 |
+
"b_psnr": 35.183197556682785
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"key": "p6_s42",
|
| 113 |
+
"q_cos": 0.9331587040078793,
|
| 114 |
+
"q_ssim": 0.7900576591491699,
|
| 115 |
+
"q_psnr": 24.498085894958194,
|
| 116 |
+
"b_cos": 0.9774430311345284,
|
| 117 |
+
"b_ssim": 0.9009554982185364,
|
| 118 |
+
"b_psnr": 29.70465765397799
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"key": "p7_s42",
|
| 122 |
+
"q_cos": 0.9683902202075972,
|
| 123 |
+
"q_ssim": 0.8378195762634277,
|
| 124 |
+
"q_psnr": 23.165908401122874,
|
| 125 |
+
"b_cos": 0.9921477502640577,
|
| 126 |
+
"b_ssim": 0.9311777949333191,
|
| 127 |
+
"b_psnr": 29.262203485754593
|
| 128 |
+
}
|
| 129 |
+
]
|
| 130 |
+
}
|
metrics/g4_lightning_int6_summary.json
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"summary": {
|
| 3 |
+
"q_cos": {
|
| 4 |
+
"mean": 0.9898927716536442,
|
| 5 |
+
"min": 0.9567565647004941
|
| 6 |
+
},
|
| 7 |
+
"q_ssim": {
|
| 8 |
+
"mean": 0.9351999163627625,
|
| 9 |
+
"min": 0.8403822779655457
|
| 10 |
+
},
|
| 11 |
+
"q_psnr": {
|
| 12 |
+
"mean": 32.03008194336978,
|
| 13 |
+
"min": 26.337870100239925
|
| 14 |
+
},
|
| 15 |
+
"b_cos": {
|
| 16 |
+
"mean": 0.9934811761192526,
|
| 17 |
+
"min": 0.9774430311345284
|
| 18 |
+
},
|
| 19 |
+
"b_ssim": {
|
| 20 |
+
"mean": 0.9486830607056618,
|
| 21 |
+
"min": 0.9009554982185364
|
| 22 |
+
},
|
| 23 |
+
"b_psnr": {
|
| 24 |
+
"mean": 32.76348619085778,
|
| 25 |
+
"min": 29.262203485754593
|
| 26 |
+
},
|
| 27 |
+
"mode": "lightning",
|
| 28 |
+
"fp16": "sdxl_lightning_4step.safetensors",
|
| 29 |
+
"quant": "sdxl-lightning-4step-int6-convrot.safetensors",
|
| 30 |
+
"steps": 4,
|
| 31 |
+
"size": 1024,
|
| 32 |
+
"renders": 8,
|
| 33 |
+
"fp16_bytes": 6938040682,
|
| 34 |
+
"quant_bytes": 4313382791,
|
| 35 |
+
"timing": {
|
| 36 |
+
"fp16": {
|
| 37 |
+
"quantized_layers": 0,
|
| 38 |
+
"total_layers": 794,
|
| 39 |
+
"total_s": 2.2276711463928223,
|
| 40 |
+
"warm_mean_s": 0.15183039257155023
|
| 41 |
+
},
|
| 42 |
+
"bf16": {
|
| 43 |
+
"quantized_layers": 0,
|
| 44 |
+
"total_layers": 794,
|
| 45 |
+
"total_s": 1.8353800773620605,
|
| 46 |
+
"warm_mean_s": 0.14815370614282333
|
| 47 |
+
},
|
| 48 |
+
"quant": {
|
| 49 |
+
"quantized_layers": 739,
|
| 50 |
+
"total_layers": 794,
|
| 51 |
+
"total_s": 3.904664993286133,
|
| 52 |
+
"warm_mean_s": 0.4006172318571381
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"rows": [
|
| 57 |
+
{
|
| 58 |
+
"key": "p0_s42",
|
| 59 |
+
"q_cos": 0.9976443762753403,
|
| 60 |
+
"q_ssim": 0.9747118949890137,
|
| 61 |
+
"q_psnr": 36.30577807556013,
|
| 62 |
+
"b_cos": 0.9958390972649831,
|
| 63 |
+
"b_ssim": 0.9647495150566101,
|
| 64 |
+
"b_psnr": 34.071319153766815
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"key": "p1_s42",
|
| 68 |
+
"q_cos": 0.9961568802300296,
|
| 69 |
+
"q_ssim": 0.9661180377006531,
|
| 70 |
+
"q_psnr": 34.048384422675994,
|
| 71 |
+
"b_cos": 0.9957289018420392,
|
| 72 |
+
"b_ssim": 0.9649030566215515,
|
| 73 |
+
"b_psnr": 33.94747884338996
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"key": "p2_s42",
|
| 77 |
+
"q_cos": 0.9927446396854887,
|
| 78 |
+
"q_ssim": 0.9381133913993835,
|
| 79 |
+
"q_psnr": 29.313014498829627,
|
| 80 |
+
"b_cos": 0.9955180320099095,
|
| 81 |
+
"b_ssim": 0.9483562111854553,
|
| 82 |
+
"b_psnr": 31.2901873584441
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"key": "p3_s42",
|
| 86 |
+
"q_cos": 0.9985686027031818,
|
| 87 |
+
"q_ssim": 0.9714229106903076,
|
| 88 |
+
"q_psnr": 37.580431321644085,
|
| 89 |
+
"b_cos": 0.9990687437592017,
|
| 90 |
+
"b_ssim": 0.9715254902839661,
|
| 91 |
+
"b_psnr": 37.40556777464224
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"key": "p4_s42",
|
| 95 |
+
"q_cos": 0.9874264512607909,
|
| 96 |
+
"q_ssim": 0.8868193626403809,
|
| 97 |
+
"q_psnr": 28.901226084228426,
|
| 98 |
+
"b_cos": 0.9939828308172979,
|
| 99 |
+
"b_ssim": 0.9297152161598206,
|
| 100 |
+
"b_psnr": 31.24327770020377
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"key": "p5_s42",
|
| 104 |
+
"q_cos": 0.9968576437318357,
|
| 105 |
+
"q_ssim": 0.9734973311424255,
|
| 106 |
+
"q_psnr": 34.04313938397297,
|
| 107 |
+
"b_cos": 0.9981210218620029,
|
| 108 |
+
"b_ssim": 0.9780817031860352,
|
| 109 |
+
"b_psnr": 35.183197556682785
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"key": "p6_s42",
|
| 113 |
+
"q_cos": 0.9567565647004941,
|
| 114 |
+
"q_ssim": 0.8403822779655457,
|
| 115 |
+
"q_psnr": 26.337870100239925,
|
| 116 |
+
"b_cos": 0.9774430311345284,
|
| 117 |
+
"b_ssim": 0.9009554982185364,
|
| 118 |
+
"b_psnr": 29.70465765397799
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"key": "p7_s42",
|
| 122 |
+
"q_cos": 0.9929870146419928,
|
| 123 |
+
"q_ssim": 0.9305341243743896,
|
| 124 |
+
"q_psnr": 29.710811659807078,
|
| 125 |
+
"b_cos": 0.9921477502640577,
|
| 126 |
+
"b_ssim": 0.9311777949333191,
|
| 127 |
+
"b_psnr": 29.262203485754593
|
| 128 |
+
}
|
| 129 |
+
]
|
| 130 |
+
}
|
metrics/g4_lightning_int8_summary.json
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"summary": {
|
| 3 |
+
"q_cos": {
|
| 4 |
+
"mean": 0.9928979424502529,
|
| 5 |
+
"min": 0.9823923645573054
|
| 6 |
+
},
|
| 7 |
+
"q_ssim": {
|
| 8 |
+
"mean": 0.9485225901007652,
|
| 9 |
+
"min": 0.9062896370887756
|
| 10 |
+
},
|
| 11 |
+
"q_psnr": {
|
| 12 |
+
"mean": 32.47808780049283,
|
| 13 |
+
"min": 26.804302874053164
|
| 14 |
+
},
|
| 15 |
+
"b_cos": {
|
| 16 |
+
"mean": 0.9934811761192526,
|
| 17 |
+
"min": 0.9774430311345284
|
| 18 |
+
},
|
| 19 |
+
"b_ssim": {
|
| 20 |
+
"mean": 0.9486830607056618,
|
| 21 |
+
"min": 0.9009554982185364
|
| 22 |
+
},
|
| 23 |
+
"b_psnr": {
|
| 24 |
+
"mean": 32.76348619085778,
|
| 25 |
+
"min": 29.262203485754593
|
| 26 |
+
},
|
| 27 |
+
"mode": "lightning",
|
| 28 |
+
"fp16": "sdxl_lightning_4step.safetensors",
|
| 29 |
+
"quant": "sdxl-lightning-4step-int8-convrot.safetensors",
|
| 30 |
+
"steps": 4,
|
| 31 |
+
"size": 1024,
|
| 32 |
+
"renders": 8,
|
| 33 |
+
"fp16_bytes": 6938040682,
|
| 34 |
+
"quant_bytes": 4718756459,
|
| 35 |
+
"timing": {
|
| 36 |
+
"fp16": {
|
| 37 |
+
"quantized_layers": 0,
|
| 38 |
+
"total_layers": 794,
|
| 39 |
+
"total_s": 2.2258992195129395,
|
| 40 |
+
"warm_mean_s": 0.15113420514288528
|
| 41 |
+
},
|
| 42 |
+
"bf16": {
|
| 43 |
+
"quantized_layers": 0,
|
| 44 |
+
"total_layers": 794,
|
| 45 |
+
"total_s": 1.8416118621826172,
|
| 46 |
+
"warm_mean_s": 0.1482163002856396
|
| 47 |
+
},
|
| 48 |
+
"quant": {
|
| 49 |
+
"quantized_layers": 739,
|
| 50 |
+
"total_layers": 794,
|
| 51 |
+
"total_s": 4.037699937820435,
|
| 52 |
+
"warm_mean_s": 0.36938223628567357
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"rows": [
|
| 57 |
+
{
|
| 58 |
+
"key": "p0_s42",
|
| 59 |
+
"q_cos": 0.9970807923976209,
|
| 60 |
+
"q_ssim": 0.9731174111366272,
|
| 61 |
+
"q_psnr": 35.538493229560395,
|
| 62 |
+
"b_cos": 0.9958390972649831,
|
| 63 |
+
"b_ssim": 0.9647495150566101,
|
| 64 |
+
"b_psnr": 34.071319153766815
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"key": "p1_s42",
|
| 68 |
+
"q_cos": 0.9971512728309041,
|
| 69 |
+
"q_ssim": 0.9730351567268372,
|
| 70 |
+
"q_psnr": 35.07667341960973,
|
| 71 |
+
"b_cos": 0.9957289018420392,
|
| 72 |
+
"b_ssim": 0.9649030566215515,
|
| 73 |
+
"b_psnr": 33.94747884338996
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"key": "p2_s42",
|
| 77 |
+
"q_cos": 0.9856257769993342,
|
| 78 |
+
"q_ssim": 0.9062896370887756,
|
| 79 |
+
"q_psnr": 26.804302874053164,
|
| 80 |
+
"b_cos": 0.9955180320099095,
|
| 81 |
+
"b_ssim": 0.9483562111854553,
|
| 82 |
+
"b_psnr": 31.2901873584441
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"key": "p3_s42",
|
| 86 |
+
"q_cos": 0.9987270024966513,
|
| 87 |
+
"q_ssim": 0.9687862396240234,
|
| 88 |
+
"q_psnr": 36.858858767737246,
|
| 89 |
+
"b_cos": 0.9990687437592017,
|
| 90 |
+
"b_ssim": 0.9715254902839661,
|
| 91 |
+
"b_psnr": 37.40556777464224
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"key": "p4_s42",
|
| 95 |
+
"q_cos": 0.9966818595005243,
|
| 96 |
+
"q_ssim": 0.9496252536773682,
|
| 97 |
+
"q_psnr": 33.63465240621789,
|
| 98 |
+
"b_cos": 0.9939828308172979,
|
| 99 |
+
"b_ssim": 0.9297152161598206,
|
| 100 |
+
"b_psnr": 31.24327770020377
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"key": "p5_s42",
|
| 104 |
+
"q_cos": 0.995954831623314,
|
| 105 |
+
"q_ssim": 0.9704432487487793,
|
| 106 |
+
"q_psnr": 32.95824983199621,
|
| 107 |
+
"b_cos": 0.9981210218620029,
|
| 108 |
+
"b_ssim": 0.9780817031860352,
|
| 109 |
+
"b_psnr": 35.183197556682785
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"key": "p6_s42",
|
| 113 |
+
"q_cos": 0.9823923645573054,
|
| 114 |
+
"q_ssim": 0.9223983883857727,
|
| 115 |
+
"q_psnr": 30.398491103711773,
|
| 116 |
+
"b_cos": 0.9774430311345284,
|
| 117 |
+
"b_ssim": 0.9009554982185364,
|
| 118 |
+
"b_psnr": 29.70465765397799
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"key": "p7_s42",
|
| 122 |
+
"q_cos": 0.9895696391963689,
|
| 123 |
+
"q_ssim": 0.9244853854179382,
|
| 124 |
+
"q_psnr": 28.554980771056222,
|
| 125 |
+
"b_cos": 0.9921477502640577,
|
| 126 |
+
"b_ssim": 0.9311777949333191,
|
| 127 |
+
"b_psnr": 29.262203485754593
|
| 128 |
+
}
|
| 129 |
+
]
|
| 130 |
+
}
|
scripts/calib_prompts.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
a photo of a woman in a red coat walking through a busy city street, detailed, natural light
|
| 2 |
+
Close-up portrait photo of an elderly fisherman with weathered skin and a grey beard, soft window light, 85mm
|
| 3 |
+
A misty alpine lake at sunrise, pine forest, snow-capped mountains reflected in the water, landscape photography
|
| 4 |
+
A vintage neon sign that says OPEN 24 HOURS on a rainy city street at night, reflections on wet asphalt
|
| 5 |
+
Macro photo of a red fox fur and amber eye, extremely detailed, shallow depth of field
|
| 6 |
+
Isometric illustration of a cozy wizard library with floating books and warm candlelight, digital art
|
| 7 |
+
A gourmet burger with melted cheese and sesame bun on a wooden board, food photography, studio lighting
|
| 8 |
+
Futuristic glass skyscraper in a desert city, golden hour, architectural photography, wide angle
|
| 9 |
+
Watercolor painting of a hummingbird drinking from a purple flower, loose brush strokes, white paper
|
| 10 |
+
Minimalist Scandinavian living room interior with oak furniture and large windows, natural daylight
|
| 11 |
+
Aerial drone photograph of winding turquoise river delta in Iceland, volcanic black sand
|
| 12 |
+
Oil painting of a stormy sea with an old wooden sailing ship under dramatic clouds
|
| 13 |
+
Street photography in Tokyo Shibuya crossing in heavy rain with colorful umbrellas and bokeh lights
|
| 14 |
+
Studio product photograph of a luxury mechanical wristwatch on dark slate stone, dramatic rim light
|
| 15 |
+
Cyberpunk alley with holographic billboards, steam vents, and a lone hooded figure in neon light
|
| 16 |
+
Fresh croissants and espresso cup on a marble bistro table in Paris morning sun
|
| 17 |
+
Photorealistic 3D render of a glossy ceramic astronaut helmet reflecting nebula stars
|
| 18 |
+
Japanesezen bamboo garden after rain with stone lantern and moss-covered path
|
| 19 |
+
Dramatic black and white portrait of a jazz saxophonist on a smoky dimly lit stage
|
| 20 |
+
Vintage red convertible parked along California Pacific Coast Highway overlooking ocean cliffs
|
| 21 |
+
macro crystal snowflake on dark wool fabric, ultra sharp focus, studio lighting
|
| 22 |
+
Medieval stone castle perched on a misty Scottish cliff at twilight
|
| 23 |
+
Modern electric sports car speeding through a mountain tunnel with light trails
|
| 24 |
+
Botanical illustration of wildflower meadow species in vintage scientific style
|
| 25 |
+
Colorful Mediterranean cliffside village at sunset with warm lights reflecting on the sea
|
| 26 |
+
Snow leopard resting on a rocky Himalayan ridge, telephoto shot, crisp detail
|
| 27 |
+
Art Deco grand theater lobby with brass railings, marble floors, and warm chandeliers
|
| 28 |
+
Vibrant autumn maple forest trail carpeted in fallen orange and red leaves
|
| 29 |
+
Fresh sushi platter arranged on handcrafted black stoneware plate, overhead food photography
|
| 30 |
+
Astronaut standing on red Martian desert plain looking toward dusty horizon, cinematic wide shot
|
| 31 |
+
Delicate glassblowing workshop with glowing molten amber glass and dark studio background
|
| 32 |
+
Classic steam locomotive crossing a stone viaduct bridge through mountain fog
|
scripts/convrot_pipeline.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SDXL ConvRot INT8 quantization & verification toolkit for ComfyUI.
|
| 2 |
+
|
| 3 |
+
Fixes two gaps in upstream HSWQ SDXL scripts for stock ComfyUI v0.45.0:
|
| 4 |
+
1. Diag un-rotation bug: reconstructs (q * s) @ H in original coordinate frame so
|
| 5 |
+
per-layer trajectory impact reflects INT8 quantization noise rather than un-rotated
|
| 6 |
+
Hadamard scrambling (per HSWQ CHANGELOG v2.5.0).
|
| 7 |
+
2. Stock ComfyUI compatibility & VAE retention: protects all Conv2d layers in FP16
|
| 8 |
+
(upstream ComfyUI v0.45.0 MixedPrecisionOps handles Linear INT8 natively, not Conv2d)
|
| 9 |
+
and preserves embedded FP16 VAE weights (first_stage_model.*) required by
|
| 10 |
+
standard ComfyUI checkpoint workflows (VAEDecode -> CheckpointLoaderSimple output slot 2).
|
| 11 |
+
3. Model-accurate trajectories & bias correction: supports Base, Lightning, Turbo,
|
| 12 |
+
and Refiner conditioning/samplers/schedulers instead of hardcoding dpmpp_2m/karras
|
| 13 |
+
and a single fallback prompt.
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import gc
|
| 17 |
+
import json
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
from safetensors import safe_open
|
| 25 |
+
from safetensors.torch import save_file
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _setup_comfy(comfy_path: str):
|
| 29 |
+
root = os.path.abspath(comfy_path)
|
| 30 |
+
if root not in sys.path:
|
| 31 |
+
sys.path.insert(0, root)
|
| 32 |
+
import importlib.machinery
|
| 33 |
+
import types
|
| 34 |
+
|
| 35 |
+
# Guard against torch/torchaudio ABI mismatch if present.
|
| 36 |
+
try:
|
| 37 |
+
import torchaudio # noqa: F401
|
| 38 |
+
except Exception:
|
| 39 |
+
for k in [k for k in sys.modules if k == "torchaudio" or k.startswith("torchaudio.")]:
|
| 40 |
+
del sys.modules[k]
|
| 41 |
+
ta = types.ModuleType("torchaudio")
|
| 42 |
+
ta.__spec__ = importlib.machinery.ModuleSpec("torchaudio", None, is_package=True)
|
| 43 |
+
ta.__path__ = []
|
| 44 |
+
fn = types.ModuleType("torchaudio.functional")
|
| 45 |
+
fn.__spec__ = importlib.machinery.ModuleSpec("torchaudio.functional", None)
|
| 46 |
+
fn.resample = lambda w, *a, **kw: w
|
| 47 |
+
tr = types.ModuleType("torchaudio.transforms")
|
| 48 |
+
tr.__spec__ = importlib.machinery.ModuleSpec("torchaudio.transforms", None)
|
| 49 |
+
tr.MelSpectrogram = type("MelSpectrogram", (), {"__init__": lambda *a, **k: None, "to": lambda s, *a, **k: s})
|
| 50 |
+
tr.MelScale = type("MelScale", (), {"__init__": lambda *a, **k: None})
|
| 51 |
+
ta.functional, ta.transforms = fn, tr
|
| 52 |
+
sys.modules["torchaudio"] = ta
|
| 53 |
+
sys.modules["torchaudio.functional"] = fn
|
| 54 |
+
sys.modules["torchaudio.transforms"] = tr
|
| 55 |
+
|
| 56 |
+
import comfy.options
|
| 57 |
+
comfy.options.enable_args_parsing(False)
|
| 58 |
+
import comfy.model_management # noqa: F401
|
| 59 |
+
import comfy.ops # noqa: F401
|
| 60 |
+
import comfy.sample # noqa: F401
|
| 61 |
+
import comfy.samplers # noqa: F401
|
| 62 |
+
import comfy.sd # noqa: F401
|
| 63 |
+
import comfy.utils # noqa: F401
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def convrot_group_size_for_features(n: int, preferred: int = 256) -> int | None:
|
| 67 |
+
if n < 4:
|
| 68 |
+
return None
|
| 69 |
+
gs = preferred
|
| 70 |
+
while gs >= 4:
|
| 71 |
+
if n % gs == 0 and math.log(gs, 4) % 1 == 0:
|
| 72 |
+
return gs
|
| 73 |
+
gs //= 4
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def build_hadamard(size: int, device="cpu", dtype=torch.float32) -> torch.Tensor:
|
| 78 |
+
h4 = torch.tensor(
|
| 79 |
+
[[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]],
|
| 80 |
+
dtype=dtype,
|
| 81 |
+
device=device,
|
| 82 |
+
)
|
| 83 |
+
h = h4
|
| 84 |
+
cur = 4
|
| 85 |
+
while cur < size:
|
| 86 |
+
h = torch.kron(h, h4)
|
| 87 |
+
cur *= 4
|
| 88 |
+
return h / (size ** 0.5)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def rotate_weight(weight: torch.Tensor, h_matrix: torch.Tensor, group_size: int) -> torch.Tensor:
|
| 92 |
+
out_features, in_features = weight.shape
|
| 93 |
+
grouped = weight.reshape(out_features, in_features // group_size, group_size)
|
| 94 |
+
return torch.matmul(grouped, h_matrix.T.to(weight.dtype)).reshape(weight.shape)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def rotate_activation_lastdim(x: torch.Tensor, h_matrix: torch.Tensor, group_size: int) -> torch.Tensor:
|
| 98 |
+
orig = x.shape
|
| 99 |
+
f = orig[-1]
|
| 100 |
+
grouped = x.reshape(-1, f // group_size, group_size)
|
| 101 |
+
return torch.matmul(grouped, h_matrix.to(x.dtype)).reshape(orig)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def quantize_int8_rowwise(w: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 105 |
+
abs_max = w.abs().amax(dim=-1, keepdim=True).float().clamp(min=1e-30)
|
| 106 |
+
scale = abs_max / 127.0
|
| 107 |
+
q = (w / scale.to(w.dtype)).round().clamp(-127, 127).to(torch.int8)
|
| 108 |
+
return q, scale.to(torch.float32)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _encode_comfy_quant(conf: dict) -> torch.Tensor:
|
| 112 |
+
raw = json.dumps(conf, separators=(",", ":")).encode("utf-8")
|
| 113 |
+
return torch.tensor(list(raw), dtype=torch.uint8)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _is_boundary(mod_name: str) -> bool:
|
| 117 |
+
b = mod_name
|
| 118 |
+
for p in ("model.diffusion_model.", "diffusion_model."):
|
| 119 |
+
if b.startswith(p):
|
| 120 |
+
b = b[len(p):]
|
| 121 |
+
return b == "input_blocks.0.0" or b.startswith(("out.", "time_embed.", "add_embedding.", "label_emb."))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _load_prompts(calib_file: str | None, n: int) -> list[str]:
|
| 125 |
+
fallback = [
|
| 126 |
+
"a photo of a woman in a red coat walking through a busy city street, detailed, natural light",
|
| 127 |
+
"Close-up portrait photo of an elderly fisherman with weathered skin, soft window light",
|
| 128 |
+
"A misty alpine lake at sunrise, pine forest, snow-capped mountains reflected in the water",
|
| 129 |
+
"Isometric illustration of a cozy wizard library with floating books and warm candlelight",
|
| 130 |
+
]
|
| 131 |
+
if calib_file and os.path.isfile(calib_file):
|
| 132 |
+
with open(calib_file, encoding="utf-8") as f:
|
| 133 |
+
lines = [ln.strip() for ln in f if ln.strip()]
|
| 134 |
+
if lines:
|
| 135 |
+
fallback = lines
|
| 136 |
+
return (fallback * (n // len(fallback) + 1))[:n]
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _encode_cond(clip, prompt: str, mode: str, size: int, is_neg: bool = False):
|
| 140 |
+
tokens = clip.tokenize(prompt)
|
| 141 |
+
if mode == "refiner":
|
| 142 |
+
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
| 143 |
+
ascore = 2.5 if is_neg else 6.0
|
| 144 |
+
return [[cond, {"pooled_output": pooled, "aesthetic_score": ascore, "width": size, "height": size}]]
|
| 145 |
+
return clip.encode_from_tokens_scheduled(tokens)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _sample_mode(patcher, pos, neg, lat0, seed: int, mode: str, steps: int, callback=None):
|
| 149 |
+
import comfy.sample as comfy_sample
|
| 150 |
+
import comfy.samplers as comfy_samplers
|
| 151 |
+
|
| 152 |
+
noise = comfy_sample.prepare_noise(lat0, seed, None)
|
| 153 |
+
if mode == "turbo":
|
| 154 |
+
timesteps = torch.flip(torch.arange(1, 11) * 100 - 1, (0,))[:steps]
|
| 155 |
+
sigmas = patcher.get_model_object("model_sampling").sigma(timesteps)
|
| 156 |
+
sigmas = torch.cat([sigmas, sigmas.new_zeros([1])])
|
| 157 |
+
sampler = comfy_samplers.sampler_object("euler_ancestral")
|
| 158 |
+
return comfy_sample.sample_custom(
|
| 159 |
+
patcher, noise, 1.0, sampler, sigmas, pos, neg, lat0,
|
| 160 |
+
callback=callback, disable_pbar=True, seed=seed,
|
| 161 |
+
)
|
| 162 |
+
if mode == "lightning":
|
| 163 |
+
cfg, sampler_name, scheduler = 1.0, "euler", "sgm_uniform"
|
| 164 |
+
elif mode == "refiner":
|
| 165 |
+
cfg, sampler_name, scheduler = 6.0, "euler", "normal"
|
| 166 |
+
else:
|
| 167 |
+
cfg, sampler_name, scheduler = 6.0, "euler", "normal"
|
| 168 |
+
return comfy_sample.sample(
|
| 169 |
+
patcher, noise, steps, cfg, sampler_name, scheduler, pos, neg, lat0,
|
| 170 |
+
denoise=1.0, disable_noise=False, force_full_denoise=False,
|
| 171 |
+
callback=callback, disable_pbar=True, seed=seed,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _make_latent(patcher, size: int, device: str):
|
| 176 |
+
import comfy.model_management as mm
|
| 177 |
+
import comfy.sample as comfy_sample
|
| 178 |
+
|
| 179 |
+
lat = torch.zeros([1, 4, size // 8, size // 8], device=mm.intermediate_device(), dtype=mm.intermediate_dtype())
|
| 180 |
+
lat = comfy_sample.fix_empty_latent_channels(patcher, lat, 8, None)
|
| 181 |
+
return lat.to(device) if lat.device.type != device else lat
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _load_ckpt(path: str, comfy_path: str):
|
| 185 |
+
import comfy.sd
|
| 186 |
+
saved = list(sys.argv)
|
| 187 |
+
sys.argv = [sys.argv[0]]
|
| 188 |
+
try:
|
| 189 |
+
out = comfy.sd.load_checkpoint_guess_config(
|
| 190 |
+
os.path.abspath(path), output_vae=False, output_clip=True, embedding_directory=None
|
| 191 |
+
)
|
| 192 |
+
finally:
|
| 193 |
+
sys.argv = saved
|
| 194 |
+
return out[0], out[1]
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def cmd_diag(args):
|
| 198 |
+
_setup_comfy(args.comfy_path)
|
| 199 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 200 |
+
torch.backends.cudnn.deterministic = True
|
| 201 |
+
torch.backends.cudnn.benchmark = False
|
| 202 |
+
|
| 203 |
+
patcher, clip = _load_ckpt(args.base, args.comfy_path)
|
| 204 |
+
net = patcher.model
|
| 205 |
+
net.to(device)
|
| 206 |
+
net.eval()
|
| 207 |
+
|
| 208 |
+
prompts = _load_prompts(args.calib_file, 1)
|
| 209 |
+
pos = _encode_cond(clip, prompts[0], args.mode, args.size, is_neg=False)
|
| 210 |
+
neg = _encode_cond(clip, "", args.mode, args.size, is_neg=True)
|
| 211 |
+
del clip
|
| 212 |
+
gc.collect()
|
| 213 |
+
torch.cuda.empty_cache()
|
| 214 |
+
|
| 215 |
+
lat0 = _make_latent(patcher, args.size, device)
|
| 216 |
+
targets = []
|
| 217 |
+
mods = {}
|
| 218 |
+
for n, m in net.named_modules():
|
| 219 |
+
w = getattr(m, "weight", None)
|
| 220 |
+
if not isinstance(w, torch.Tensor) or w.ndim != 2 or w.shape[1] < 4:
|
| 221 |
+
continue
|
| 222 |
+
if _is_boundary(n):
|
| 223 |
+
continue
|
| 224 |
+
gs = convrot_group_size_for_features(int(w.shape[1]), args.groupsize)
|
| 225 |
+
if gs is None:
|
| 226 |
+
continue
|
| 227 |
+
targets.append(n)
|
| 228 |
+
mods[n] = (m, gs)
|
| 229 |
+
if args.limit:
|
| 230 |
+
targets = targets[:args.limit]
|
| 231 |
+
|
| 232 |
+
print(f"[diag] mode={args.mode} steps={args.steps} size={args.size} linear_targets={len(targets)}", flush=True)
|
| 233 |
+
|
| 234 |
+
def run_traj():
|
| 235 |
+
xs = []
|
| 236 |
+
with torch.no_grad():
|
| 237 |
+
_sample_mode(patcher, pos, neg, lat0, args.seed, args.mode, args.steps, callback=lambda s, x0, x, t: xs.append(x.detach().float().cpu()))
|
| 238 |
+
return xs
|
| 239 |
+
|
| 240 |
+
t0 = time.perf_counter()
|
| 241 |
+
x_ref = run_traj()
|
| 242 |
+
dt = time.perf_counter() - t0
|
| 243 |
+
print(f"[diag] pristine={dt:.2f}s est_total={dt * len(targets) / 60.0:.1f} min", flush=True)
|
| 244 |
+
|
| 245 |
+
h_cache = {}
|
| 246 |
+
impacts = {}
|
| 247 |
+
t_start = time.perf_counter()
|
| 248 |
+
for idx, name in enumerate(targets, 1):
|
| 249 |
+
m, gs = mods[name]
|
| 250 |
+
w0 = m.weight.data.clone()
|
| 251 |
+
if gs not in h_cache:
|
| 252 |
+
h_cache[gs] = build_hadamard(gs, device=w0.device, dtype=torch.float32)
|
| 253 |
+
h = h_cache[gs]
|
| 254 |
+
w_rot = rotate_weight(w0.float(), h, gs)
|
| 255 |
+
q, s = quantize_int8_rowwise(w_rot)
|
| 256 |
+
w_eff = rotate_weight(q.float() * s.float(), h.T, gs)
|
| 257 |
+
m.weight.data.copy_(w_eff.to(w0.dtype))
|
| 258 |
+
try:
|
| 259 |
+
x_t = run_traj()
|
| 260 |
+
errs = []
|
| 261 |
+
for a, b in zip(x_t, x_ref):
|
| 262 |
+
af, bf = a.reshape(a.shape[0], -1), b.reshape(b.shape[0], -1)
|
| 263 |
+
errs.append(float(((af - bf) ** 2).sum() / (bf ** 2).sum()))
|
| 264 |
+
impacts[name] = sum(errs) / len(errs)
|
| 265 |
+
finally:
|
| 266 |
+
m.weight.data.copy_(w0)
|
| 267 |
+
del w0, w_rot, q, s, w_eff
|
| 268 |
+
if idx % args.progress_every == 0 or idx == len(targets):
|
| 269 |
+
el = time.perf_counter() - t_start
|
| 270 |
+
eta = el / idx * (len(targets) - idx) / 60.0
|
| 271 |
+
print(f"[diag {idx}/{len(targets)}] {name}={impacts[name]:.4e} elapsed={el/60:.1f}m eta={eta:.1f}m", flush=True)
|
| 272 |
+
|
| 273 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
|
| 274 |
+
with open(args.out, "w", encoding="utf-8") as f:
|
| 275 |
+
json.dump({
|
| 276 |
+
"mode": args.mode, "steps": args.steps, "seed": args.seed, "size": args.size,
|
| 277 |
+
"base": os.path.abspath(args.base), "unrotated_eval": True, "impacts": impacts
|
| 278 |
+
}, f, indent=1)
|
| 279 |
+
print(f"[diag] saved {args.out}", flush=True)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _collect_act_means(base: str, comfy_path: str, targets: dict, mode: str, size: int, steps: int, calib_file: str, num_samples: int, seed: int):
|
| 283 |
+
_setup_comfy(comfy_path)
|
| 284 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 285 |
+
patcher, clip = _load_ckpt(base, comfy_path)
|
| 286 |
+
net = patcher.model
|
| 287 |
+
net.to(device)
|
| 288 |
+
net.eval()
|
| 289 |
+
|
| 290 |
+
prompts = _load_prompts(calib_file, num_samples)
|
| 291 |
+
uniq_conds = {}
|
| 292 |
+
for p in set(prompts):
|
| 293 |
+
uniq_conds[p] = (
|
| 294 |
+
_encode_cond(clip, p, mode, size, is_neg=False),
|
| 295 |
+
_encode_cond(clip, "", mode, size, is_neg=True),
|
| 296 |
+
)
|
| 297 |
+
del clip
|
| 298 |
+
gc.collect()
|
| 299 |
+
torch.cuda.empty_cache()
|
| 300 |
+
|
| 301 |
+
lat0 = _make_latent(patcher, size, device)
|
| 302 |
+
h_cache = {}
|
| 303 |
+
acc = {name: None for name in targets}
|
| 304 |
+
cnt = {name: 0 for name in targets}
|
| 305 |
+
handles = []
|
| 306 |
+
mods = dict(net.named_modules())
|
| 307 |
+
|
| 308 |
+
def make_hook(name, gs):
|
| 309 |
+
def hook(_mod, inp):
|
| 310 |
+
x = inp[0] if isinstance(inp, (tuple, list)) else inp
|
| 311 |
+
if not torch.is_tensor(x) or not torch.is_floating_point(x) or x.shape[-1] % gs != 0:
|
| 312 |
+
return
|
| 313 |
+
if gs not in h_cache:
|
| 314 |
+
h_cache[gs] = build_hadamard(gs, device=x.device, dtype=torch.float32)
|
| 315 |
+
xr = rotate_activation_lastdim(x.detach().float(), h_cache[gs], gs)
|
| 316 |
+
m = xr.reshape(-1, xr.shape[-1]).mean(dim=0).cpu()
|
| 317 |
+
if acc[name] is None:
|
| 318 |
+
acc[name] = m
|
| 319 |
+
else:
|
| 320 |
+
acc[name] += m
|
| 321 |
+
cnt[name] += 1
|
| 322 |
+
return hook
|
| 323 |
+
|
| 324 |
+
for n, gs in targets.items():
|
| 325 |
+
if n in mods:
|
| 326 |
+
handles.append(mods[n].register_forward_pre_hook(make_hook(n, gs)))
|
| 327 |
+
|
| 328 |
+
print(f"[calib] mode={mode} samples={num_samples} steps={steps} targets={len(handles)}", flush=True)
|
| 329 |
+
for i, p in enumerate(prompts):
|
| 330 |
+
pos, neg = uniq_conds[p]
|
| 331 |
+
with torch.no_grad():
|
| 332 |
+
_sample_mode(patcher, pos, neg, lat0, seed + i, mode, steps)
|
| 333 |
+
if (i + 1) % 8 == 0 or (i + 1) == len(prompts):
|
| 334 |
+
print(f" [calib {i+1}/{len(prompts)}]", flush=True)
|
| 335 |
+
|
| 336 |
+
for h in handles:
|
| 337 |
+
h.remove()
|
| 338 |
+
means = {n: (acc[n] / cnt[n]) for n in targets if acc[n] is not None and cnt[n] > 0}
|
| 339 |
+
del net, patcher
|
| 340 |
+
gc.collect()
|
| 341 |
+
torch.cuda.empty_cache()
|
| 342 |
+
return means
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def cmd_convert(args):
|
| 346 |
+
with safe_open(os.path.abspath(args.base), framework="pt", device="cpu") as f:
|
| 347 |
+
raw_meta = dict(f.metadata() or {})
|
| 348 |
+
sd = {k: f.get_tensor(k) for k in f.keys()}
|
| 349 |
+
|
| 350 |
+
# Build candidate Linear list.
|
| 351 |
+
def sd_key_to_mod(mk: str) -> str:
|
| 352 |
+
return mk[len("model."):] if mk.startswith("model.diffusion_model.") else mk
|
| 353 |
+
|
| 354 |
+
def mod_to_sd_key(mod_name: str) -> str | None:
|
| 355 |
+
bare = mod_name[len("diffusion_model."):] if mod_name.startswith("diffusion_model.") else mod_name
|
| 356 |
+
for pre in ("model.diffusion_model.", "diffusion_model."):
|
| 357 |
+
if pre + bare + ".weight" in sd:
|
| 358 |
+
return pre + bare
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
if args.impact:
|
| 362 |
+
with open(args.impact, encoding="utf-8") as f:
|
| 363 |
+
imp = json.load(f)["impacts"]
|
| 364 |
+
ordered_mods = [k for k, v in sorted(imp.items(), key=lambda kv: kv[1]) if not (isinstance(v, float) and math.isnan(v))]
|
| 365 |
+
else:
|
| 366 |
+
ordered_mods = []
|
| 367 |
+
for k in sd.keys():
|
| 368 |
+
if k.endswith(".weight") and (k.startswith("model.diffusion_model.") or k.startswith("diffusion_model.")):
|
| 369 |
+
ordered_mods.append(sd_key_to_mod(k[:-len(".weight")]))
|
| 370 |
+
|
| 371 |
+
protect_set = set()
|
| 372 |
+
if args.protect_top_k > 0 and args.impact:
|
| 373 |
+
# Protect the TOP K highest-impact layers (the tail of ascending ordered_mods)
|
| 374 |
+
top_k = ordered_mods[-args.protect_top_k:]
|
| 375 |
+
protect_set.update(top_k)
|
| 376 |
+
|
| 377 |
+
plan = []
|
| 378 |
+
for mod in ordered_mods:
|
| 379 |
+
if mod in protect_set or ("diffusion_model." + mod) in protect_set:
|
| 380 |
+
continue
|
| 381 |
+
mk = mod_to_sd_key(mod)
|
| 382 |
+
if mk is None:
|
| 383 |
+
continue
|
| 384 |
+
w = sd[mk + ".weight"]
|
| 385 |
+
if w.ndim != 2 or w.dtype not in (torch.float16, torch.bfloat16, torch.float32):
|
| 386 |
+
continue
|
| 387 |
+
if _is_boundary(mk):
|
| 388 |
+
continue
|
| 389 |
+
gs = convrot_group_size_for_features(int(w.shape[1]), args.groupsize)
|
| 390 |
+
if gs is None:
|
| 391 |
+
continue
|
| 392 |
+
plan.append((mk, gs))
|
| 393 |
+
|
| 394 |
+
if args.limit_k is not None:
|
| 395 |
+
plan = plan[:args.limit_k]
|
| 396 |
+
|
| 397 |
+
mu_rot = {}
|
| 398 |
+
if args.bias_correction:
|
| 399 |
+
targets = {sd_key_to_mod(mk): gs for mk, gs in plan}
|
| 400 |
+
raw_means = _collect_act_means(
|
| 401 |
+
args.base, args.comfy_path, targets, args.mode, args.size,
|
| 402 |
+
args.calib_steps, args.calib_file, args.num_calib_samples, args.calib_seed
|
| 403 |
+
)
|
| 404 |
+
mu_rot = {mk: raw_means.get(sd_key_to_mod(mk)) for mk, _ in plan}
|
| 405 |
+
|
| 406 |
+
quant_meta_layers = {}
|
| 407 |
+
h_cache = {}
|
| 408 |
+
bias_applied = 0
|
| 409 |
+
for mk, gs in plan:
|
| 410 |
+
wk = mk + ".weight"
|
| 411 |
+
w = sd[wk]
|
| 412 |
+
if gs not in h_cache:
|
| 413 |
+
h_cache[gs] = build_hadamard(gs, device="cpu", dtype=torch.float32)
|
| 414 |
+
h = h_cache[gs]
|
| 415 |
+
w_rot = rotate_weight(w.float(), h, gs)
|
| 416 |
+
q, scale = quantize_int8_rowwise(w_rot)
|
| 417 |
+
if args.bias_correction and mk + ".bias" in sd and mu_rot.get(mk) is not None:
|
| 418 |
+
m = mu_rot[mk].float()
|
| 419 |
+
err_rot = (q.float() * scale.float()) - w_rot
|
| 420 |
+
if m.numel() == err_rot.shape[1]:
|
| 421 |
+
delta = err_rot @ m
|
| 422 |
+
bk = mk + ".bias"
|
| 423 |
+
b = sd[bk]
|
| 424 |
+
sd[bk] = (b.float() - delta.to(b.device).float()).to(b.dtype)
|
| 425 |
+
bias_applied += 1
|
| 426 |
+
del sd[wk]
|
| 427 |
+
sd[wk] = q
|
| 428 |
+
sd[mk + ".weight_scale"] = scale
|
| 429 |
+
conf = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": int(gs)}
|
| 430 |
+
sd[mk + ".comfy_quant"] = _encode_comfy_quant(conf)
|
| 431 |
+
quant_meta_layers[mk] = conf
|
| 432 |
+
|
| 433 |
+
vae_count = sum(1 for k in sd if k.startswith("first_stage_model."))
|
| 434 |
+
meta = dict(raw_meta)
|
| 435 |
+
meta["_quantization_metadata"] = json.dumps({"format_version": "1.0", "layers": quant_meta_layers}, separators=(",", ":"))
|
| 436 |
+
meta["convrot_int8"] = json.dumps({
|
| 437 |
+
"mode": args.mode, "converted_linear": len(plan), "protected_top_k": args.protect_top_k,
|
| 438 |
+
"bias_correction": bool(args.bias_correction), "bias_applied": bias_applied,
|
| 439 |
+
"vae_tensors_preserved": vae_count,
|
| 440 |
+
})
|
| 441 |
+
os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
|
| 442 |
+
save_file(sd, args.out, metadata=meta)
|
| 443 |
+
print(f"[convert] saved {args.out} ({os.path.getsize(args.out)/1e9:.2f} GB) converted_linear={len(plan)} protect_top_k={args.protect_top_k} bias_applied={bias_applied} vae_tensors={vae_count}", flush=True)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def cmd_gate(args):
|
| 447 |
+
_setup_comfy(args.comfy_path)
|
| 448 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 449 |
+
import comfy.model_management as mm
|
| 450 |
+
|
| 451 |
+
seeds = [42 + i for i in range(args.seeds)]
|
| 452 |
+
prompt = _load_prompts(args.calib_file, 1)[0]
|
| 453 |
+
|
| 454 |
+
def run_ckpt(path):
|
| 455 |
+
patcher, clip = _load_ckpt(path, args.comfy_path)
|
| 456 |
+
pos = _encode_cond(clip, prompt, args.mode, args.size, is_neg=False)
|
| 457 |
+
neg = _encode_cond(clip, "", args.mode, args.size, is_neg=True)
|
| 458 |
+
lat0 = _make_latent(patcher, args.size, "cpu")
|
| 459 |
+
res = {}
|
| 460 |
+
times = []
|
| 461 |
+
for s in seeds:
|
| 462 |
+
ts = time.perf_counter()
|
| 463 |
+
with torch.no_grad():
|
| 464 |
+
out = _sample_mode(patcher, pos, neg, lat0, s, args.mode, args.steps)
|
| 465 |
+
if torch.cuda.is_available():
|
| 466 |
+
torch.cuda.synchronize()
|
| 467 |
+
times.append(time.perf_counter() - ts)
|
| 468 |
+
res[s] = out.detach().float().cpu().flatten()
|
| 469 |
+
del patcher, clip
|
| 470 |
+
mm.unload_all_models()
|
| 471 |
+
gc.collect()
|
| 472 |
+
mm.soft_empty_cache()
|
| 473 |
+
warm = times[1:] if len(times) > 1 else times
|
| 474 |
+
return res, sum(warm) / len(warm)
|
| 475 |
+
|
| 476 |
+
ref, fp16_warm = run_ckpt(args.fp16)
|
| 477 |
+
qnt, int8_warm = run_ckpt(args.int8)
|
| 478 |
+
cos_vals = [float(torch.nn.functional.cosine_similarity(ref[s].double(), qnt[s].double(), dim=0)) for s in seeds]
|
| 479 |
+
low = sum(1 for c in cos_vals if c < 0.90)
|
| 480 |
+
print(f"[gate] seeds={len(seeds)} min_cos={min(cos_vals):.5f} mean_cos={sum(cos_vals)/len(cos_vals):.5f} max_cos={max(cos_vals):.5f} below_0.90={low} | warm fp16={fp16_warm:.2f}s int8={int8_warm:.2f}s", flush=True)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def main():
|
| 484 |
+
ap = argparse.ArgumentParser()
|
| 485 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 486 |
+
|
| 487 |
+
pd = sub.add_parser("diag")
|
| 488 |
+
pd.add_argument("--base", required=True)
|
| 489 |
+
pd.add_argument("--out", required=True)
|
| 490 |
+
pd.add_argument("--comfy-path", required=True)
|
| 491 |
+
pd.add_argument("--mode", required=True, choices=["base", "lightning", "turbo", "refiner"])
|
| 492 |
+
pd.add_argument("--steps", type=int, default=4)
|
| 493 |
+
pd.add_argument("--size", type=int, default=1024)
|
| 494 |
+
pd.add_argument("--seed", type=int, default=42)
|
| 495 |
+
pd.add_argument("--groupsize", type=int, default=256)
|
| 496 |
+
pd.add_argument("--calib-file", default=None)
|
| 497 |
+
pd.add_argument("--limit", type=int, default=None)
|
| 498 |
+
pd.add_argument("--progress-every", type=int, default=25)
|
| 499 |
+
pd.set_defaults(fn=cmd_diag)
|
| 500 |
+
|
| 501 |
+
pc = sub.add_parser("convert")
|
| 502 |
+
pc.add_argument("--base", required=True)
|
| 503 |
+
pc.add_argument("--out", required=True)
|
| 504 |
+
pc.add_argument("--comfy-path", required=True)
|
| 505 |
+
pc.add_argument("--mode", required=True, choices=["base", "lightning", "turbo", "refiner"])
|
| 506 |
+
pc.add_argument("--impact", default=None)
|
| 507 |
+
pc.add_argument("--protect-top-k", type=int, default=0)
|
| 508 |
+
pc.add_argument("--limit-k", type=int, default=None)
|
| 509 |
+
pc.add_argument("--groupsize", type=int, default=256)
|
| 510 |
+
pc.add_argument("--bias-correction", action="store_true")
|
| 511 |
+
pc.add_argument("--calib-file", default=None)
|
| 512 |
+
pc.add_argument("--num-calib-samples", type=int, default=32)
|
| 513 |
+
pc.add_argument("--calib-steps", type=int, default=25)
|
| 514 |
+
pc.add_argument("--size", type=int, default=1024)
|
| 515 |
+
pc.add_argument("--calib-seed", type=int, default=42)
|
| 516 |
+
pc.set_defaults(fn=cmd_convert)
|
| 517 |
+
|
| 518 |
+
pg = sub.add_parser("gate")
|
| 519 |
+
pg.add_argument("--fp16", required=True)
|
| 520 |
+
pg.add_argument("--int8", required=True)
|
| 521 |
+
pg.add_argument("--comfy-path", required=True)
|
| 522 |
+
pg.add_argument("--mode", required=True, choices=["base", "lightning", "turbo", "refiner"])
|
| 523 |
+
pg.add_argument("--steps", type=int, default=25)
|
| 524 |
+
pg.add_argument("--size", type=int, default=1024)
|
| 525 |
+
pg.add_argument("--seeds", type=int, default=25)
|
| 526 |
+
pg.add_argument("--calib-file", default=None)
|
| 527 |
+
pg.set_defaults(fn=cmd_gate)
|
| 528 |
+
|
| 529 |
+
args = ap.parse_args()
|
| 530 |
+
args.fn(args)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
main()
|
scripts/quantize_convrot_gptq.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build and benchmark Full INT8 (Act-Order GPTQ) and Full INT4 (Group Act-Order GPTQ) across all 4 SDXL models, keeping verified Full INT6."""
|
| 2 |
+
import functools
|
| 3 |
+
import gc
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import signal
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
print = functools.partial(print, flush=True)
|
| 14 |
+
sys.path.insert(0, os.environ.get("COMFY_PATH", "./ComfyUI"))
|
| 15 |
+
sys.path.insert(0, ".")
|
| 16 |
+
os.chdir(".")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
import safetensors.torch
|
| 21 |
+
import comfy_kitchen as ck
|
| 22 |
+
from comfy_kitchen.backends.eager.quantization import rotate_int8_convrot_weight
|
| 23 |
+
from comfy_kitchen.backends.eager.w4a8_int8 import _E4M3_MAX_FINITE_BITS, _W6_LEVELS, _assign_codes, _fit_codebook
|
| 24 |
+
from comfy_kitchen.tensor.w4a8_packed import _pack_codes
|
| 25 |
+
import convrot_pipeline as cp
|
| 26 |
+
|
| 27 |
+
cp._setup_comfy(os.environ.get("COMFY_PATH", "./ComfyUI"))
|
| 28 |
+
|
| 29 |
+
DETECTION_KEYS = {
|
| 30 |
+
"model.diffusion_model.label_emb.0.0",
|
| 31 |
+
"model.diffusion_model.input_blocks.4.1.transformer_blocks.0.attn2.to_k",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# Verified Full INT6 files when already built under out_final_<mode>/int6.safetensors
|
| 35 |
+
INT6_SOURCES = {
|
| 36 |
+
"lightning": [
|
| 37 |
+
("out_final_lightning/int6.safetensors", "work/eval_final_lightning_int6"),
|
| 38 |
+
("out_lightning/w6_full.safetensors", "work/eval_w6_full"),
|
| 39 |
+
],
|
| 40 |
+
"turbo": [
|
| 41 |
+
("out_final_turbo/int6.safetensors", "work/eval_final_turbo_int6"),
|
| 42 |
+
("out_turbo/int6.safetensors", "work/eval_turbo_int6"),
|
| 43 |
+
],
|
| 44 |
+
"refiner": [
|
| 45 |
+
("out_final_refiner/int6.safetensors", "work/eval_final_refiner_int6"),
|
| 46 |
+
("out_refiner/int6.safetensors", "work/eval_refiner_int6"),
|
| 47 |
+
],
|
| 48 |
+
"base": [
|
| 49 |
+
("out_final_base/int6.safetensors", "work/eval_final_base_int6"),
|
| 50 |
+
("out_base/int6.safetensors", "work/eval_base_int6"),
|
| 51 |
+
],
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
MODES = {
|
| 55 |
+
"lightning": {"src": "models/sdxl_lightning_4step.safetensors", "cp": 16, "cs": 4, "sz": 1024, "es": 4, "seeds": 1},
|
| 56 |
+
"turbo": {"src": "models/sd_xl_turbo_1.0_fp16.safetensors", "cp": 24, "cs": 2, "sz": 512, "es": 2, "seeds": 3},
|
| 57 |
+
"refiner": {"src": "models/sd_xl_refiner_1.0.safetensors", "base": "models/sd_xl_base_1.0.safetensors", "cp": 12, "cs": 40, "sz": 1024, "es": 40, "seeds": 1},
|
| 58 |
+
"base": {"src": "models/sd_xl_base_1.0.safetensors", "cp": 12, "cs": 12, "sz": 1024, "es": 50, "seeds": 1},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def compute_actorder_int8(w_gpu, H_cpu, cgs, damp_pct=0.005):
|
| 63 |
+
"""Full per-column Act-Order ConvRot GPTQ INT8 (int8_tensorwise)."""
|
| 64 |
+
w_rot = rotate_int8_convrot_weight(w_gpu.float().contiguous(), int(cgs)) if cgs is not None else w_gpu.float()
|
| 65 |
+
n, k = w_rot.shape
|
| 66 |
+
sc = (w_rot.abs().amax(dim=-1) / 127.0).clamp(min=1e-8)
|
| 67 |
+
|
| 68 |
+
if H_cpu is not None:
|
| 69 |
+
H = H_cpu.cuda().float()
|
| 70 |
+
dead = H.diag() <= 0
|
| 71 |
+
if dead.any():
|
| 72 |
+
H[dead, dead] = 1.0
|
| 73 |
+
w_rot[:, dead] = 0.0
|
| 74 |
+
perm = torch.argsort(H.diag(), descending=True)
|
| 75 |
+
invperm = torch.argsort(perm)
|
| 76 |
+
Hp = H[perm][:, perm]
|
| 77 |
+
Wp = w_rot[:, perm].clone()
|
| 78 |
+
U = None
|
| 79 |
+
for d in (damp_pct, 0.01, 0.05, 0.2):
|
| 80 |
+
try:
|
| 81 |
+
Hd = Hp.clone()
|
| 82 |
+
Hd.diagonal().add_(d * Hd.diag().mean().clamp(min=1e-6))
|
| 83 |
+
L_ch = torch.linalg.cholesky(Hd)
|
| 84 |
+
U = torch.linalg.cholesky(torch.cholesky_inverse(L_ch), upper=True)
|
| 85 |
+
break
|
| 86 |
+
except RuntimeError:
|
| 87 |
+
continue
|
| 88 |
+
if U is not None:
|
| 89 |
+
qp = torch.empty((n, k), device="cuda", dtype=torch.int8)
|
| 90 |
+
bs = min(128, k)
|
| 91 |
+
u_inv_all = 1.0 / U.diag().clamp(min=1e-8)
|
| 92 |
+
for c0 in range(0, k, bs):
|
| 93 |
+
c1 = min(c0 + bs, k)
|
| 94 |
+
W_blk = Wp[:, c0:c1].clone()
|
| 95 |
+
U_blk = U[c0:c1, c0:c1]
|
| 96 |
+
u_inv = u_inv_all[c0:c1]
|
| 97 |
+
Err = torch.empty_like(W_blk)
|
| 98 |
+
for j in range(c1 - c0):
|
| 99 |
+
wj = W_blk[:, j]
|
| 100 |
+
qj_int = (wj / sc).round().clamp(-127, 127)
|
| 101 |
+
qp[:, c0 + j] = qj_int.to(torch.int8)
|
| 102 |
+
err_j = (wj - qj_int * sc) * u_inv[j]
|
| 103 |
+
Err[:, j] = err_j
|
| 104 |
+
if j + 1 < c1 - c0:
|
| 105 |
+
W_blk[:, j + 1:] -= err_j.unsqueeze(1) * U_blk[j, j + 1:].unsqueeze(0)
|
| 106 |
+
if c1 < k:
|
| 107 |
+
Wp[:, c1:] -= Err @ U[c0:c1, c1:]
|
| 108 |
+
q_rot = qp[:, invperm]
|
| 109 |
+
w_deq_r = q_rot.float() * sc.unsqueeze(1)
|
| 110 |
+
w_deq = rotate_int8_convrot_weight(w_deq_r.contiguous(), int(cgs)).float() if cgs is not None else w_deq_r
|
| 111 |
+
return q_rot.cpu(), sc.unsqueeze(1).cpu(), w_deq
|
| 112 |
+
|
| 113 |
+
q_rot = (w_rot / sc.unsqueeze(1)).round().clamp(-127, 127).to(torch.int8)
|
| 114 |
+
w_deq_r = q_rot.float() * sc.unsqueeze(1)
|
| 115 |
+
w_deq = rotate_int8_convrot_weight(w_deq_r.contiguous(), int(cgs)).float() if cgs is not None else w_deq_r
|
| 116 |
+
return q_rot.cpu(), sc.unsqueeze(1).cpu(), w_deq
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def compute_actorder_w4(w_gpu, H_cpu, ulp_radius=5, damp_pct=0.005):
|
| 120 |
+
"""Group-preserving Act-Order ConvRot GPTQ INT4 (asym_w4a8_int8, g16)."""
|
| 121 |
+
gs, cgs, bits = 16, 256, 4
|
| 122 |
+
n, k = w_gpu.shape
|
| 123 |
+
groups = k // gs
|
| 124 |
+
w_rot = rotate_int8_convrot_weight(w_gpu.float().contiguous(), cgs)
|
| 125 |
+
|
| 126 |
+
gw = w_rot.view(n, groups, gs)
|
| 127 |
+
gscale = gw.abs().amax(dim=-1, keepdim=True).clamp(min=1e-8)
|
| 128 |
+
norm = gw / gscale
|
| 129 |
+
cb_t = _fit_codebook(norm, levels=16, iterations=40, sample_size=500000)
|
| 130 |
+
cb_t, _ = torch.sort(cb_t)
|
| 131 |
+
lt = cb_t
|
| 132 |
+
q_idx = _assign_codes(norm, lt)
|
| 133 |
+
|
| 134 |
+
for _ in range(6):
|
| 135 |
+
ql = lt[q_idx]
|
| 136 |
+
gscale = ((gw * ql).sum(-1, keepdim=True) / (ql * ql).sum(-1, keepdim=True).clamp(min=1e-8)).clamp(min=1e-8)
|
| 137 |
+
q_idx = _assign_codes(gw / gscale, lt)
|
| 138 |
+
|
| 139 |
+
shifted = lt[q_idx] * gscale
|
| 140 |
+
sc = (shifted.abs().amax(dim=(1, 2)) / 127.0).clamp(min=1e-8)
|
| 141 |
+
|
| 142 |
+
H = H_cpu.cuda().float()
|
| 143 |
+
dead = H.diag() <= 0
|
| 144 |
+
W = w_rot.clone()
|
| 145 |
+
if dead.any():
|
| 146 |
+
H[dead, dead] = 1.0
|
| 147 |
+
W[:, dead] = 0.0
|
| 148 |
+
|
| 149 |
+
diag_g = H.diag().view(groups, gs)
|
| 150 |
+
g_perm = torch.argsort(diag_g.mean(dim=1), descending=True)
|
| 151 |
+
inv_g_perm = torch.argsort(g_perm)
|
| 152 |
+
in_perm = torch.argsort(diag_g[g_perm], dim=1, descending=True)
|
| 153 |
+
perm = (g_perm.unsqueeze(1) * gs + in_perm).reshape(-1)
|
| 154 |
+
invperm = torch.argsort(perm)
|
| 155 |
+
|
| 156 |
+
Hp = H[perm][:, perm]
|
| 157 |
+
Wp = W[:, perm].clone()
|
| 158 |
+
U = None
|
| 159 |
+
for d in (damp_pct, 0.01, 0.03, 0.1, 0.25):
|
| 160 |
+
try:
|
| 161 |
+
Hd = Hp.clone()
|
| 162 |
+
Hd.diagonal().add_(d * Hd.diag().mean().clamp(min=1e-6))
|
| 163 |
+
L_ch = torch.linalg.cholesky(Hd)
|
| 164 |
+
U = torch.linalg.cholesky(torch.cholesky_inverse(L_ch), upper=True)
|
| 165 |
+
break
|
| 166 |
+
except RuntimeError:
|
| 167 |
+
continue
|
| 168 |
+
assert U is not None
|
| 169 |
+
|
| 170 |
+
sr_p = torch.empty((n, groups), device="cuda", dtype=torch.float8_e4m3fn)
|
| 171 |
+
idx_p = torch.empty((n, groups, gs), device="cuda", dtype=torch.int32)
|
| 172 |
+
u_inv_all = 1.0 / U.diag().clamp(min=1e-8)
|
| 173 |
+
deltas = torch.arange(-ulp_radius, ulp_radius + 1, device="cuda", dtype=torch.int32)
|
| 174 |
+
row_idx = torch.arange(n, device="cuda")
|
| 175 |
+
L = lt.numel()
|
| 176 |
+
|
| 177 |
+
for gb in range(groups):
|
| 178 |
+
c0 = gb * gs
|
| 179 |
+
c1 = c0 + gs
|
| 180 |
+
W_blk = Wp[:, c0:c1].clone()
|
| 181 |
+
U_blk = U[c0:c1, c0:c1]
|
| 182 |
+
u_inv_g = u_inv_all[c0:c1]
|
| 183 |
+
|
| 184 |
+
gs_est = W_blk.abs().amax(dim=1, keepdim=True).clamp(min=1e-8)
|
| 185 |
+
qi = _assign_codes(W_blk / gs_est, lt)
|
| 186 |
+
for _ in range(2):
|
| 187 |
+
ql = lt[qi]
|
| 188 |
+
gs_est = ((W_blk * ql).sum(-1, keepdim=True) / (ql * ql).sum(-1, keepdim=True).clamp(min=1e-8)).clamp(min=1e-8)
|
| 189 |
+
qi = _assign_codes(W_blk / gs_est, lt)
|
| 190 |
+
sr_init_g = (gs_est.squeeze(-1) / sc).to(torch.float8_e4m3fn)
|
| 191 |
+
|
| 192 |
+
w_imp = (u_inv_g * u_inv_g).view(1, 1, gs)
|
| 193 |
+
raw_g = sr_init_g.view(torch.uint8).to(torch.int32)
|
| 194 |
+
cands_f = (raw_g.unsqueeze(0) + deltas.view(-1, 1)).clamp(1, _E4M3_MAX_FINITE_BITS).to(torch.uint8).view(torch.float8_e4m3fn).float()
|
| 195 |
+
lv_c = (lt.view(1, 1, L) * cands_f.unsqueeze(-1)).round_().clamp_(-127, 127)
|
| 196 |
+
target_g = (W_blk / sc.unsqueeze(1)).unsqueeze(0).expand(cands_f.shape[0], n, gs).contiguous()
|
| 197 |
+
pos = torch.searchsorted(lv_c, target_g)
|
| 198 |
+
lo = (pos - 1).clamp(0, L - 1)
|
| 199 |
+
hi = pos.clamp(0, L - 1)
|
| 200 |
+
vlo = torch.gather(lv_c, 2, lo)
|
| 201 |
+
vhi = torch.gather(lv_c, 2, hi)
|
| 202 |
+
v_ch = torch.where((target_g - vhi).abs() < (target_g - vlo).abs(), vhi, vlo)
|
| 203 |
+
err_c = ((v_ch - target_g).pow_(2) * w_imp).sum(dim=-1)
|
| 204 |
+
best_c = err_c.argmin(dim=0)
|
| 205 |
+
sr_g_1d = cands_f[best_c, row_idx].to(torch.float8_e4m3fn)
|
| 206 |
+
sr_p[:, gb] = sr_g_1d
|
| 207 |
+
q_levels = lv_c[best_c, row_idx] * sc.unsqueeze(1)
|
| 208 |
+
|
| 209 |
+
Err_blk = torch.empty_like(W_blk)
|
| 210 |
+
for j in range(gs):
|
| 211 |
+
wj = W_blk[:, j]
|
| 212 |
+
best_i = (wj.unsqueeze(1) - q_levels).abs().argmin(dim=1)
|
| 213 |
+
idx_p[:, gb, j] = best_i
|
| 214 |
+
qj = q_levels[row_idx, best_i]
|
| 215 |
+
err_j = (wj - qj) * u_inv_g[j]
|
| 216 |
+
Err_blk[:, j] = err_j
|
| 217 |
+
if j + 1 < gs:
|
| 218 |
+
W_blk[:, j + 1:] -= err_j.unsqueeze(1) * U_blk[j, j + 1:].unsqueeze(0)
|
| 219 |
+
|
| 220 |
+
if c1 < k:
|
| 221 |
+
Wp[:, c1:] -= Err_blk @ U[c0:c1, c1:]
|
| 222 |
+
|
| 223 |
+
sr_out = sr_p[:, inv_g_perm].contiguous()
|
| 224 |
+
idx_out = idx_p.reshape(n, k)[:, invperm]
|
| 225 |
+
packed = _pack_codes(idx_out, bits)
|
| 226 |
+
w_deq = ck.dequantize_w4a8_int8_weight(packed, sr_out, sc, codebook=cb_t, group_size=16, convrot_groupsize=256, output_dtype=torch.float32)
|
| 227 |
+
return packed.cpu(), sr_out.cpu(), sc.float().contiguous().cpu(), cb_t.cpu(), w_deq
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def compute_inorder_w6(w_gpu, H_cpu, ulp_radius=4, damp_pct=0.01):
|
| 231 |
+
"""ConvRot GPTQ INT6 (w6a8_int8, g16) with ALS + through-grid FP8 scale search."""
|
| 232 |
+
gs, cgs, bits = 16, 256, 6
|
| 233 |
+
n, k = w_gpu.shape
|
| 234 |
+
groups = k // gs
|
| 235 |
+
w_rot = rotate_int8_convrot_weight(w_gpu.float().contiguous(), cgs)
|
| 236 |
+
|
| 237 |
+
lt = torch.arange(-_W6_LEVELS, _W6_LEVELS + 1, device="cuda", dtype=torch.float32)
|
| 238 |
+
gw = w_rot.view(n, groups, gs)
|
| 239 |
+
gscale = (gw.abs().amax(dim=-1, keepdim=True) / _W6_LEVELS).clamp(min=1e-8)
|
| 240 |
+
q_idx = (gw / gscale).round().clamp(-_W6_LEVELS, _W6_LEVELS).to(torch.int32) + _W6_LEVELS
|
| 241 |
+
for _ in range(5):
|
| 242 |
+
ql = lt[q_idx]
|
| 243 |
+
gscale = ((gw * ql).sum(-1, keepdim=True) / (ql * ql).sum(-1, keepdim=True).clamp(min=1e-8)).clamp(min=1e-8)
|
| 244 |
+
q_idx = (gw / gscale).round().clamp(-_W6_LEVELS, _W6_LEVELS).to(torch.int32) + _W6_LEVELS
|
| 245 |
+
sc = ((lt[q_idx] * gscale).abs().amax(dim=(1, 2)) / 127.0).clamp(min=1e-8)
|
| 246 |
+
|
| 247 |
+
W = w_rot.clone()
|
| 248 |
+
H = H_cpu.cuda().float()
|
| 249 |
+
dead = H.diag() <= 0
|
| 250 |
+
if dead.any():
|
| 251 |
+
H[dead, dead] = 1.0
|
| 252 |
+
W[:, dead] = 0.0
|
| 253 |
+
|
| 254 |
+
U = None
|
| 255 |
+
for d in (damp_pct, 0.03, 0.1, 0.25):
|
| 256 |
+
try:
|
| 257 |
+
Hd = H.clone()
|
| 258 |
+
Hd.diagonal().add_(d * Hd.diag().mean().clamp(min=1e-6))
|
| 259 |
+
L_ch = torch.linalg.cholesky(Hd)
|
| 260 |
+
U = torch.linalg.cholesky(torch.cholesky_inverse(L_ch), upper=True)
|
| 261 |
+
break
|
| 262 |
+
except RuntimeError:
|
| 263 |
+
continue
|
| 264 |
+
assert U is not None
|
| 265 |
+
|
| 266 |
+
sr_out = torch.empty((n, groups), device="cuda", dtype=torch.float8_e4m3fn)
|
| 267 |
+
idx_out = torch.empty((n, groups, gs), device="cuda", dtype=torch.int32)
|
| 268 |
+
u_inv_all = 1.0 / U.diag().clamp(min=1e-8)
|
| 269 |
+
deltas = torch.arange(-ulp_radius, ulp_radius + 1, device="cuda", dtype=torch.int32)
|
| 270 |
+
row_idx = torch.arange(n, device="cuda")
|
| 271 |
+
L = lt.numel()
|
| 272 |
+
|
| 273 |
+
for g in range(groups):
|
| 274 |
+
c0 = g * gs
|
| 275 |
+
c1 = c0 + gs
|
| 276 |
+
W_blk = W[:, c0:c1].clone()
|
| 277 |
+
U_blk = U[c0:c1, c0:c1]
|
| 278 |
+
u_inv_g = u_inv_all[c0:c1]
|
| 279 |
+
sr_init_g = ((W_blk.abs().amax(dim=1) / _W6_LEVELS).clamp(min=1e-8) / sc).to(torch.float8_e4m3fn)
|
| 280 |
+
w_imp = (u_inv_g * u_inv_g).view(1, 1, gs)
|
| 281 |
+
raw_g = sr_init_g.view(torch.uint8).to(torch.int32)
|
| 282 |
+
cands_f = (raw_g.unsqueeze(0) + deltas.view(-1, 1)).clamp(1, _E4M3_MAX_FINITE_BITS).to(torch.uint8).view(torch.float8_e4m3fn).float()
|
| 283 |
+
lv_c = (lt.view(1, 1, L) * cands_f.unsqueeze(-1)).round_().clamp_(-127, 127)
|
| 284 |
+
target_g = (W_blk / sc.unsqueeze(1)).unsqueeze(0).expand(cands_f.shape[0], n, gs).contiguous()
|
| 285 |
+
pos = torch.searchsorted(lv_c, target_g)
|
| 286 |
+
lo = (pos - 1).clamp(0, L - 1)
|
| 287 |
+
hi = pos.clamp(0, L - 1)
|
| 288 |
+
vlo = torch.gather(lv_c, 2, lo)
|
| 289 |
+
vhi = torch.gather(lv_c, 2, hi)
|
| 290 |
+
v_ch = torch.where((target_g - vhi).abs() < (target_g - vlo).abs(), vhi, vlo)
|
| 291 |
+
best_c = (((v_ch - target_g).pow_(2) * w_imp).sum(dim=-1)).argmin(dim=0)
|
| 292 |
+
sr_out[:, g] = cands_f[best_c, row_idx].to(torch.float8_e4m3fn)
|
| 293 |
+
q_levels = lv_c[best_c, row_idx] * sc.unsqueeze(1)
|
| 294 |
+
Err_blk = torch.empty_like(W_blk)
|
| 295 |
+
for j in range(gs):
|
| 296 |
+
wj = W_blk[:, j]
|
| 297 |
+
best_i = (wj.unsqueeze(1) - q_levels).abs().argmin(dim=1)
|
| 298 |
+
idx_out[:, g, j] = best_i
|
| 299 |
+
err_j = (wj - q_levels[row_idx, best_i]) * u_inv_g[j]
|
| 300 |
+
Err_blk[:, j] = err_j
|
| 301 |
+
if j + 1 < gs:
|
| 302 |
+
W_blk[:, j + 1:] -= err_j.unsqueeze(1) * U_blk[j, j + 1:].unsqueeze(0)
|
| 303 |
+
if c1 < k:
|
| 304 |
+
W[:, c1:] -= Err_blk @ U[c0:c1, c1:]
|
| 305 |
+
|
| 306 |
+
packed = _pack_codes((idx_out + 1).view(n, k), bits)
|
| 307 |
+
w_deq = ck.dequantize_w4a8_int8_weight(packed, sr_out, sc, codebook=None, group_size=16, convrot_groupsize=256, output_dtype=torch.float32)
|
| 308 |
+
return packed.cpu(), sr_out.cpu(), sc.float().contiguous().cpu(), w_deq
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def build_mode(mode: str):
|
| 312 |
+
cfg = MODES[mode]
|
| 313 |
+
src_ckpt = cfg["src"]
|
| 314 |
+
final_dir = f"out_final_{mode}"
|
| 315 |
+
os.makedirs(final_dir, exist_ok=True)
|
| 316 |
+
|
| 317 |
+
# Copy verified INT6 checkpoint + eval dir when present (else build INT6 below)
|
| 318 |
+
need_int6 = True
|
| 319 |
+
i6_ev_dst = f"work/eval_final_{mode}_int6"
|
| 320 |
+
for i6_src, i6_ev_src in INT6_SOURCES[mode]:
|
| 321 |
+
if os.path.exists(i6_src) and os.path.exists(f"{i6_ev_src}/summary.json"):
|
| 322 |
+
shutil.copy2(i6_src, f"{final_dir}/int6.safetensors")
|
| 323 |
+
if not os.path.exists(f"{i6_ev_dst}/summary.json"):
|
| 324 |
+
shutil.copytree(i6_ev_src, i6_ev_dst, dirs_exist_ok=True)
|
| 325 |
+
need_int6 = False
|
| 326 |
+
break
|
| 327 |
+
print(f"[{mode}] need_int6={need_int6}")
|
| 328 |
+
|
| 329 |
+
print(f"\n=== BUILDING FINAL 3 TIERS FOR {mode.upper()} ===")
|
| 330 |
+
sd = safetensors.torch.load_file(src_ckpt, device="cpu")
|
| 331 |
+
targets = {}
|
| 332 |
+
for k, v in sd.items():
|
| 333 |
+
if k.startswith("model.diffusion_model.") and k.endswith(".weight"):
|
| 334 |
+
b = k[:-7]
|
| 335 |
+
if v.dim() == 2 and not cp._is_boundary(b):
|
| 336 |
+
targets[b] = v.shape
|
| 337 |
+
|
| 338 |
+
prompts = cp._load_prompts("scripts/calib_prompts.txt", cfg["cp"])
|
| 339 |
+
base_stage_lats = None
|
| 340 |
+
if mode == "refiner":
|
| 341 |
+
import comfy.sample as comfy_sample
|
| 342 |
+
bp, bclip = cp._load_ckpt(cfg["base"], os.environ.get("COMFY_PATH", "./ComfyUI"))
|
| 343 |
+
bp.model.to("cuda").eval()
|
| 344 |
+
lat0_b = cp._make_latent(bp, cfg["sz"], "cuda")
|
| 345 |
+
neg_b = cp._encode_cond(bclip, "", "base", cfg["sz"], False)
|
| 346 |
+
pos_bs = [cp._encode_cond(bclip, p, "base", cfg["sz"], False) for p in prompts]
|
| 347 |
+
base_stage_lats = []
|
| 348 |
+
split = cfg["cs"] * 4 // 5
|
| 349 |
+
with torch.no_grad():
|
| 350 |
+
for i, pb in enumerate(pos_bs):
|
| 351 |
+
noise = comfy_sample.prepare_noise(lat0_b, 42 + i)
|
| 352 |
+
blat = comfy_sample.sample(bp, noise, cfg["cs"], 6.0, "euler", "normal", pb, neg_b, lat0_b, denoise=1.0, start_step=0, last_step=split, disable_pbar=True, seed=42 + i)
|
| 353 |
+
base_stage_lats.append(blat.cpu())
|
| 354 |
+
del bp, bclip, lat0_b, neg_b, pos_bs
|
| 355 |
+
gc.collect()
|
| 356 |
+
torch.cuda.empty_cache()
|
| 357 |
+
|
| 358 |
+
patcher, clip = cp._load_ckpt(src_ckpt, os.environ.get("COMFY_PATH", "./ComfyUI"))
|
| 359 |
+
conds = [(cp._encode_cond(clip, p, mode, cfg["sz"], False), cp._encode_cond(clip, "", mode, cfg["sz"], True)) for p in prompts]
|
| 360 |
+
del clip
|
| 361 |
+
gc.collect()
|
| 362 |
+
torch.cuda.empty_cache()
|
| 363 |
+
|
| 364 |
+
net = patcher.model
|
| 365 |
+
net.to("cuda").eval()
|
| 366 |
+
unet = net.diffusion_model
|
| 367 |
+
lat0 = cp._make_latent(patcher, cfg["sz"], "cuda")
|
| 368 |
+
|
| 369 |
+
mu_stats = {}
|
| 370 |
+
hooks = []
|
| 371 |
+
for bname in targets:
|
| 372 |
+
mod = unet.get_submodule(bname[len("model.diffusion_model."):])
|
| 373 |
+
in_k = targets[bname][1]
|
| 374 |
+
cgs = cp.convrot_group_size_for_features(in_k)
|
| 375 |
+
st = {
|
| 376 |
+
"sum": torch.zeros(in_k, device="cuda", dtype=torch.float64),
|
| 377 |
+
"cnt": 0,
|
| 378 |
+
"H": torch.zeros((in_k, in_k), device="cuda", dtype=torch.float32) if cgs is not None else None,
|
| 379 |
+
"cgs": cgs,
|
| 380 |
+
}
|
| 381 |
+
mu_stats[bname] = st
|
| 382 |
+
def make_hook(s):
|
| 383 |
+
def hook(_m, inp, _out):
|
| 384 |
+
x = inp[0].detach()
|
| 385 |
+
if x.dim() > 2:
|
| 386 |
+
x = x.reshape(-1, x.shape[-1])
|
| 387 |
+
s["sum"].add_(x.sum(dim=0, dtype=torch.float64))
|
| 388 |
+
s["cnt"] += x.shape[0]
|
| 389 |
+
if s["H"] is not None:
|
| 390 |
+
xr = rotate_int8_convrot_weight(x.float().contiguous(), int(s["cgs"]))
|
| 391 |
+
s["H"].addmm_(xr.t(), xr)
|
| 392 |
+
return hook
|
| 393 |
+
hooks.append(mod.register_forward_hook(make_hook(st)))
|
| 394 |
+
|
| 395 |
+
t0 = time.perf_counter()
|
| 396 |
+
with torch.no_grad():
|
| 397 |
+
if mode == "refiner":
|
| 398 |
+
import comfy.sample as comfy_sample
|
| 399 |
+
split = cfg["cs"] * 4 // 5
|
| 400 |
+
for i, ((pos, neg), blat) in enumerate(zip(conds, base_stage_lats)):
|
| 401 |
+
bl = blat.to("cuda")
|
| 402 |
+
znoise = torch.zeros(bl.size(), dtype=bl.dtype, layout=bl.layout, device="cpu")
|
| 403 |
+
comfy_sample.sample(patcher, znoise, cfg["cs"], 6.0, "euler", "normal", pos, neg, bl, denoise=1.0, disable_noise=True, start_step=split, last_step=cfg["cs"], force_full_denoise=True, disable_pbar=True, seed=42 + i)
|
| 404 |
+
else:
|
| 405 |
+
for i, (pos, neg) in enumerate(conds):
|
| 406 |
+
cp._sample_mode(patcher, pos, neg, lat0, 42 + i, mode, cfg["cs"])
|
| 407 |
+
for h in hooks:
|
| 408 |
+
h.remove()
|
| 409 |
+
|
| 410 |
+
mu_x, H_rot = {}, {}
|
| 411 |
+
for bname, st in mu_stats.items():
|
| 412 |
+
cnt = max(1, st["cnt"])
|
| 413 |
+
mu_x[bname] = (st["sum"] / cnt).cpu().float()
|
| 414 |
+
if st["H"] is not None:
|
| 415 |
+
H_rot[bname] = (st["H"] / cnt).cpu().float()
|
| 416 |
+
del mu_stats, unet, net, patcher, conds, lat0, base_stage_lats
|
| 417 |
+
gc.collect()
|
| 418 |
+
torch.cuda.empty_cache()
|
| 419 |
+
print(f"[{mode}] Calibrated in {time.perf_counter()-t0:.1f}s")
|
| 420 |
+
|
| 421 |
+
sd_int8, sd_int4 = {}, {}
|
| 422 |
+
sd_int6 = {} if need_int6 else None
|
| 423 |
+
t_q = time.perf_counter()
|
| 424 |
+
for k, v in sd.items():
|
| 425 |
+
if not k.startswith("model.diffusion_model."):
|
| 426 |
+
sd_int8[k] = v
|
| 427 |
+
sd_int4[k] = v
|
| 428 |
+
if need_int6:
|
| 429 |
+
sd_int6[k] = v
|
| 430 |
+
continue
|
| 431 |
+
if k.endswith(".weight") and k[:-7] in targets:
|
| 432 |
+
bname = k[:-7]
|
| 433 |
+
w_gpu = v.to(device="cuda", dtype=torch.float32)
|
| 434 |
+
cgs = cp.convrot_group_size_for_features(w_gpu.shape[1])
|
| 435 |
+
|
| 436 |
+
# 1. Full Act-Order GPTQ INT8 (all targets!)
|
| 437 |
+
qw8, qs8, wd8 = compute_actorder_int8(w_gpu, H_rot.get(bname), cgs)
|
| 438 |
+
sd_int8[k] = qw8
|
| 439 |
+
sd_int8[f"{bname}.weight_scale"] = qs8
|
| 440 |
+
conf8 = {"format": "int8_tensorwise"}
|
| 441 |
+
if cgs is not None:
|
| 442 |
+
conf8.update({"convrot": True, "convrot_groupsize": int(cgs)})
|
| 443 |
+
sd_int8[f"{bname}.comfy_quant"] = cp._encode_comfy_quant(conf8)
|
| 444 |
+
|
| 445 |
+
# 2. Full Group Act-Order GPTQ INT4 (K%256==0 & non-detection -> asym_w4a8_int8; rest int8)
|
| 446 |
+
is_packed_ok = (w_gpu.shape[1] % 256 == 0) and (bname not in DETECTION_KEYS)
|
| 447 |
+
if is_packed_ok:
|
| 448 |
+
q4, sr4, sc4, cb4, wd4 = compute_actorder_w4(w_gpu, H_rot[bname])
|
| 449 |
+
sd_int4[k] = q4
|
| 450 |
+
sd_int4[f"{bname}.weight_s_rel"] = sr4
|
| 451 |
+
sd_int4[f"{bname}.weight_s_channel"] = sc4
|
| 452 |
+
sd_int4[f"{bname}.weight_codebook"] = cb4
|
| 453 |
+
sd_int4[f"{bname}.comfy_quant"] = cp._encode_comfy_quant({"format": "asym_w4a8_int8", "group_size": 16, "convrot": True, "convrot_groupsize": 256})
|
| 454 |
+
else:
|
| 455 |
+
wd4 = wd8
|
| 456 |
+
sd_int4[k] = qw8
|
| 457 |
+
sd_int4[f"{bname}.weight_scale"] = qs8
|
| 458 |
+
sd_int4[f"{bname}.comfy_quant"] = cp._encode_comfy_quant(conf8)
|
| 459 |
+
|
| 460 |
+
if need_int6:
|
| 461 |
+
if is_packed_ok:
|
| 462 |
+
q6, sr6, sc6, wd6 = compute_inorder_w6(w_gpu, H_rot[bname])
|
| 463 |
+
sd_int6[k] = q6
|
| 464 |
+
sd_int6[f"{bname}.weight_s_rel"] = sr6
|
| 465 |
+
sd_int6[f"{bname}.weight_s_channel"] = sc6
|
| 466 |
+
sd_int6[f"{bname}.comfy_quant"] = cp._encode_comfy_quant({"format": "w6a8_int8", "group_size": 16, "convrot": True, "convrot_groupsize": 256})
|
| 467 |
+
else:
|
| 468 |
+
wd6 = wd8
|
| 469 |
+
sd_int6[k] = qw8
|
| 470 |
+
sd_int6[f"{bname}.weight_scale"] = qs8
|
| 471 |
+
sd_int6[f"{bname}.comfy_quant"] = cp._encode_comfy_quant(conf8)
|
| 472 |
+
|
| 473 |
+
bkey = f"{bname}.bias"
|
| 474 |
+
if bkey in sd:
|
| 475 |
+
ob = sd[bkey].to(device="cuda", dtype=torch.float32)
|
| 476 |
+
mx = mu_x[bname].cuda()
|
| 477 |
+
sd_int8[bkey] = (ob - (wd8 - w_gpu) @ mx).to(sd[bkey].dtype).cpu()
|
| 478 |
+
sd_int4[bkey] = (ob - (wd4 - w_gpu) @ mx).to(sd[bkey].dtype).cpu()
|
| 479 |
+
if need_int6:
|
| 480 |
+
sd_int6[bkey] = (ob - (wd6 - w_gpu) @ mx).to(sd[bkey].dtype).cpu()
|
| 481 |
+
elif not k.endswith(".bias") or k[:-5] not in targets:
|
| 482 |
+
sd_int8[k] = v
|
| 483 |
+
sd_int4[k] = v
|
| 484 |
+
if need_int6:
|
| 485 |
+
sd_int6[k] = v
|
| 486 |
+
|
| 487 |
+
del H_rot, mu_x, sd
|
| 488 |
+
gc.collect()
|
| 489 |
+
torch.cuda.empty_cache()
|
| 490 |
+
|
| 491 |
+
safetensors.torch.save_file(sd_int8, f"{final_dir}/int8.safetensors")
|
| 492 |
+
safetensors.torch.save_file(sd_int4, f"{final_dir}/int4.safetensors")
|
| 493 |
+
del sd_int8, sd_int4
|
| 494 |
+
if need_int6:
|
| 495 |
+
safetensors.torch.save_file(sd_int6, f"{final_dir}/int6.safetensors")
|
| 496 |
+
del sd_int6
|
| 497 |
+
print(f"[{mode}] Saved tiers in {time.perf_counter()-t_q:.1f}s")
|
| 498 |
+
|
| 499 |
+
eval_tiers = ("int8", "int6", "int4") if need_int6 else ("int8", "int4")
|
| 500 |
+
for tier in eval_tiers:
|
| 501 |
+
ev_dir = f"work/eval_final_{mode}_{tier}"
|
| 502 |
+
os.makedirs(ev_dir, exist_ok=True)
|
| 503 |
+
cmd = [
|
| 504 |
+
sys.executable, "scripts/verify_sdxl_quant.py",
|
| 505 |
+
"--mode", mode, "--fp16", src_ckpt, "--quant", f"{final_dir}/{tier}.safetensors",
|
| 506 |
+
"--out", ev_dir, "--cache-ref", f"work/cache_ref_{mode}", "--comfy-path", os.environ.get("COMFY_PATH", "./ComfyUI"),
|
| 507 |
+
"--steps", str(cfg["es"]), "--size", str(cfg["sz"]), "--seeds", str(cfg["seeds"]),
|
| 508 |
+
]
|
| 509 |
+
if mode == "refiner":
|
| 510 |
+
cmd += ["--base-fp16", cfg["base"]]
|
| 511 |
+
subprocess.run(cmd, check=True)
|
| 512 |
+
|
| 513 |
+
# Print clean 3-tier summary
|
| 514 |
+
for tier in ("int8", "int6", "int4"):
|
| 515 |
+
s = json.load(open(f"work/eval_final_{mode}_{tier}/summary.json"))["summary"]
|
| 516 |
+
sz = os.path.getsize(f"{final_dir}/{tier}.safetensors")
|
| 517 |
+
print(f"FINAL {mode:9s} {tier:4s} | {sz/1e9:.2f}GB ({sz/(1024**3):.2f}GiB) | q={s['timing']['quant']['quantized_layers']}/{s['timing']['quant']['total_layers']} | Cos={s['q_cos']['mean']:.5f} (min {s['q_cos']['min']:.5f}) SSIM={s['q_ssim']['mean']:.5f} (min {s['q_ssim']['min']:.5f}) PSNR={s['q_psnr']['mean']:.2f}dB (min {s['q_psnr']['min']:.2f}) | warm={s['timing']['quant']['warm_mean_s']:.2f}s")
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
if __name__ == "__main__":
|
| 521 |
+
targets = sys.argv[1:] or ["lightning", "turbo", "refiner", "base"]
|
| 522 |
+
for m in targets:
|
| 523 |
+
build_mode(m)
|
scripts/verify_sdxl_quant.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare an FP16 SDXL-family checkpoint with a quantized copy using STOCK ComfyUI.
|
| 2 |
+
|
| 3 |
+
Runs standard SDXL ComfyUI verification recipes on an unmodified ComfyUI v0.45.0 install. For calibration it also
|
| 4 |
+
renders a BF16 copy of the same FP16 weights: BF16 is treated as "no visible loss", so the
|
| 5 |
+
quantized file should stay close to the BF16-vs-FP16 distance.
|
| 6 |
+
|
| 7 |
+
Usage:
|
| 8 |
+
python verify_sdxl_quant.py --mode base|lightning|turbo|refiner --fp16 F --quant Q --out DIR
|
| 9 |
+
[--comfy-path DIR] [--base-fp16 B] [--steps N] [--size 1024] [--seeds 3]
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import gc
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
DEFAULT_COMFY = os.environ.get("COMFY_PATH", "./ComfyUI")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _bootstrap_comfy(comfy_path: str):
|
| 22 |
+
root = os.path.abspath(comfy_path)
|
| 23 |
+
sys.path.insert(0, root)
|
| 24 |
+
os.chdir(root)
|
| 25 |
+
global np, torch, Image, structural_similarity, peak_signal_noise_ratio
|
| 26 |
+
global mm, QuantizedTensor, comfy
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
from PIL import Image
|
| 30 |
+
from skimage.metrics import structural_similarity, peak_signal_noise_ratio
|
| 31 |
+
import comfy.model_management as mm
|
| 32 |
+
import comfy.sample
|
| 33 |
+
import comfy.samplers
|
| 34 |
+
import comfy.sd
|
| 35 |
+
import comfy.utils
|
| 36 |
+
from comfy.quant_ops import QuantizedTensor
|
| 37 |
+
|
| 38 |
+
PROMPTS = [
|
| 39 |
+
"Close-up portrait photo of an elderly fisherman with weathered skin and a grey beard, soft window light, 85mm",
|
| 40 |
+
"A misty alpine lake at sunrise, pine forest, snow-capped mountains reflected in the water, landscape photography",
|
| 41 |
+
"A vintage neon sign that says \"OPEN 24 HOURS\" on a rainy city street at night, reflections on wet asphalt",
|
| 42 |
+
"Macro photo of a red fox's fur and amber eye, extremely detailed, shallow depth of field",
|
| 43 |
+
"Isometric illustration of a cozy wizard's library with floating books and warm candlelight, digital art",
|
| 44 |
+
"A gourmet burger with melted cheese and sesame bun on a wooden board, food photography, studio lighting",
|
| 45 |
+
"Futuristic glass skyscraper in a desert city, golden hour, architectural photography, wide angle",
|
| 46 |
+
"Watercolor painting of a hummingbird drinking from a purple flower, loose brush strokes, white paper",
|
| 47 |
+
]
|
| 48 |
+
SEEDS = [42, 1337, 987654]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load(path, dtype=None):
|
| 52 |
+
opts = {"dtype": dtype} if dtype is not None else {}
|
| 53 |
+
model, clip, vae, _ = comfy.sd.load_checkpoint_guess_config(
|
| 54 |
+
path, output_vae=True, output_clip=True, embedding_directory=None, model_options=opts)
|
| 55 |
+
return model, clip, vae
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def count_quant(model):
|
| 59 |
+
q = t = 0
|
| 60 |
+
for _, m in model.model.diffusion_model.named_modules():
|
| 61 |
+
w = getattr(m, "weight", None)
|
| 62 |
+
if isinstance(w, torch.Tensor) and w.ndim >= 2:
|
| 63 |
+
t += 1
|
| 64 |
+
if isinstance(w, QuantizedTensor) or getattr(m, "quant_format", None):
|
| 65 |
+
q += 1
|
| 66 |
+
return q, t
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def encode(clip, text):
|
| 70 |
+
tokens = clip.tokenize(text)
|
| 71 |
+
return clip.encode_from_tokens_scheduled(tokens)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def encode_refiner(clip, text, ascore, w, h):
|
| 75 |
+
tokens = clip.tokenize(text)
|
| 76 |
+
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
|
| 77 |
+
return [[cond, {"pooled_output": pooled, "aesthetic_score": ascore, "width": w, "height": h}]]
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def empty_latent(model, size):
|
| 81 |
+
lat = torch.zeros([1, 4, size // 8, size // 8])
|
| 82 |
+
return comfy.sample.fix_empty_latent_channels(model, lat)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def ksample(model, pos, neg, latent, seed, steps, cfg, scheduler, start=None, last=None,
|
| 86 |
+
disable_noise=False, force_full=False):
|
| 87 |
+
if disable_noise:
|
| 88 |
+
noise = torch.zeros(latent.size(), dtype=latent.dtype, layout=latent.layout, device="cpu")
|
| 89 |
+
else:
|
| 90 |
+
noise = comfy.sample.prepare_noise(latent, seed)
|
| 91 |
+
return comfy.sample.sample(model, noise, steps, cfg, "euler", scheduler, pos, neg, latent,
|
| 92 |
+
denoise=1.0, disable_noise=disable_noise, start_step=start,
|
| 93 |
+
last_step=last, force_full_denoise=force_full, seed=seed)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def turbo_sample(model, pos, neg, latent, seed, steps):
|
| 97 |
+
timesteps = torch.flip(torch.arange(1, 11) * 100 - 1, (0,))[:steps]
|
| 98 |
+
sigmas = model.get_model_object("model_sampling").sigma(timesteps)
|
| 99 |
+
sigmas = torch.cat([sigmas, sigmas.new_zeros([1])])
|
| 100 |
+
sampler = comfy.samplers.sampler_object("euler_ancestral")
|
| 101 |
+
noise = comfy.sample.prepare_noise(latent, seed)
|
| 102 |
+
return comfy.sample.sample_custom(model, noise, 1.0, sampler, sigmas, pos, neg, latent, seed=seed)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def run_set(path, args, dtype=None, base_stage=None):
|
| 106 |
+
"""Render every prompt/seed. Returns ({key: latent}, vae, timing_dict)."""
|
| 107 |
+
model, clip, vae = load(path, dtype)
|
| 108 |
+
q, t = count_quant(model)
|
| 109 |
+
print(f"[load] {os.path.basename(path)} dtype={dtype} quantized_layers={q}/{t}", flush=True)
|
| 110 |
+
out = {}
|
| 111 |
+
times = []
|
| 112 |
+
t0 = time.time()
|
| 113 |
+
for pi, prompt in enumerate(PROMPTS):
|
| 114 |
+
if args.mode == "refiner":
|
| 115 |
+
pos = encode_refiner(clip, prompt, 6.0, args.size, args.size)
|
| 116 |
+
neg = encode_refiner(clip, "", 2.5, args.size, args.size)
|
| 117 |
+
else:
|
| 118 |
+
pos, neg = encode(clip, prompt), encode(clip, "")
|
| 119 |
+
for seed in SEEDS[: args.seeds]:
|
| 120 |
+
key = f"p{pi}_s{seed}"
|
| 121 |
+
ts = time.perf_counter()
|
| 122 |
+
if args.mode == "base":
|
| 123 |
+
lat = ksample(model, pos, neg, empty_latent(model, args.size), seed, args.steps, 6.0, "normal")
|
| 124 |
+
elif args.mode == "lightning":
|
| 125 |
+
lat = ksample(model, pos, neg, empty_latent(model, args.size), seed, 4, 1.0, "sgm_uniform")
|
| 126 |
+
elif args.mode == "turbo":
|
| 127 |
+
lat = turbo_sample(model, pos, neg, empty_latent(model, args.size), seed, args.steps)
|
| 128 |
+
else: # refiner stage on top of a fixed FP16 base stage
|
| 129 |
+
split = args.steps * 4 // 5
|
| 130 |
+
lat = ksample(model, pos, neg, base_stage[key], seed, args.steps, 6.0, "normal",
|
| 131 |
+
start=split, last=args.steps, disable_noise=True, force_full=True)
|
| 132 |
+
torch.cuda.synchronize() if torch.cuda.is_available() else None
|
| 133 |
+
times.append(time.perf_counter() - ts)
|
| 134 |
+
out[key] = lat.cpu()
|
| 135 |
+
total_s = time.time() - t0
|
| 136 |
+
warm = times[1:] if len(times) > 1 else times
|
| 137 |
+
warm_mean = float(np.mean(warm)) if warm else 0.0
|
| 138 |
+
print(f"[time] {len(out)} renders in {total_s:.1f}s (warm_mean={warm_mean:.2f}s/img)", flush=True)
|
| 139 |
+
del model, clip
|
| 140 |
+
return out, vae, {"quantized_layers": q, "total_layers": t, "total_s": total_s, "warm_mean_s": warm_mean}
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def base_stage_latents(base_path, args):
|
| 144 |
+
model, clip, _ = load(base_path)
|
| 145 |
+
split = args.steps * 4 // 5
|
| 146 |
+
out = {}
|
| 147 |
+
for pi, prompt in enumerate(PROMPTS):
|
| 148 |
+
pos, neg = encode(clip, prompt), encode(clip, "")
|
| 149 |
+
for seed in SEEDS[: args.seeds]:
|
| 150 |
+
out[f"p{pi}_s{seed}"] = ksample(model, pos, neg, empty_latent(model, args.size), seed,
|
| 151 |
+
args.steps, 6.0, "normal", start=0, last=split).cpu()
|
| 152 |
+
del model, clip
|
| 153 |
+
free()
|
| 154 |
+
return out
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def free():
|
| 158 |
+
mm.unload_all_models()
|
| 159 |
+
gc.collect()
|
| 160 |
+
mm.soft_empty_cache()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def decode(vae, lat):
|
| 164 |
+
with torch.inference_mode():
|
| 165 |
+
img = vae.decode(lat)
|
| 166 |
+
return img[0].detach().float().clamp(0, 1).cpu().numpy()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def cosine(a, b):
|
| 170 |
+
a, b = a.flatten().double(), b.flatten().double()
|
| 171 |
+
return float(torch.nn.functional.cosine_similarity(a, b, dim=0))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def main():
|
| 175 |
+
ap = argparse.ArgumentParser()
|
| 176 |
+
ap.add_argument("--mode", required=True, choices=["base", "lightning", "turbo", "refiner"])
|
| 177 |
+
ap.add_argument("--fp16", required=True)
|
| 178 |
+
ap.add_argument("--quant", required=True)
|
| 179 |
+
ap.add_argument("--comfy-path", default=DEFAULT_COMFY)
|
| 180 |
+
ap.add_argument("--base-fp16", default=None, help="SDXL Base, required for --mode refiner")
|
| 181 |
+
ap.add_argument("--out", required=True)
|
| 182 |
+
ap.add_argument("--cache-ref", default=None, help="Cache FP16/BF16 reference latents here across runs")
|
| 183 |
+
ap.add_argument("--steps", type=int, default=None)
|
| 184 |
+
ap.add_argument("--size", type=int, default=1024)
|
| 185 |
+
ap.add_argument("--seeds", type=int, default=3)
|
| 186 |
+
ap.add_argument("--no-bf16", action="store_true")
|
| 187 |
+
args = ap.parse_args()
|
| 188 |
+
_bootstrap_comfy(args.comfy_path)
|
| 189 |
+
args.steps = args.steps or {"base": 50, "lightning": 4, "turbo": 2, "refiner": 40}[args.mode]
|
| 190 |
+
os.makedirs(args.out, exist_ok=True)
|
| 191 |
+
|
| 192 |
+
cache_file = os.path.join(args.cache_ref, "ref_cache.pt") if args.cache_ref else None
|
| 193 |
+
if cache_file and os.path.isfile(cache_file):
|
| 194 |
+
cached = torch.load(cache_file, map_location="cpu", weights_only=False)
|
| 195 |
+
base_stage = cached.get("base_stage")
|
| 196 |
+
ref, t_ref = cached["ref"], cached["t_ref"]
|
| 197 |
+
bf16, t_bf16 = cached.get("bf16"), cached.get("t_bf16")
|
| 198 |
+
_, _, vae = load(args.fp16)
|
| 199 |
+
free()
|
| 200 |
+
else:
|
| 201 |
+
base_stage = base_stage_latents(args.base_fp16, args) if args.mode == "refiner" else None
|
| 202 |
+
ref, vae, t_ref = run_set(args.fp16, args, base_stage=base_stage)
|
| 203 |
+
free()
|
| 204 |
+
bf16, t_bf16 = None, None
|
| 205 |
+
if not args.no_bf16:
|
| 206 |
+
bf16, _, t_bf16 = run_set(args.fp16, args, dtype=torch.bfloat16, base_stage=base_stage)
|
| 207 |
+
free()
|
| 208 |
+
if cache_file:
|
| 209 |
+
os.makedirs(args.cache_ref, exist_ok=True)
|
| 210 |
+
torch.save({"base_stage": base_stage, "ref": ref, "t_ref": t_ref, "bf16": bf16, "t_bf16": t_bf16}, cache_file)
|
| 211 |
+
|
| 212 |
+
quant, _, t_quant = run_set(args.quant, args, base_stage=base_stage)
|
| 213 |
+
free()
|
| 214 |
+
|
| 215 |
+
rows = []
|
| 216 |
+
for key in ref:
|
| 217 |
+
a = decode(vae, ref[key])
|
| 218 |
+
b = decode(vae, quant[key])
|
| 219 |
+
row = {"key": key,
|
| 220 |
+
"q_cos": float(cosine(ref[key], quant[key])),
|
| 221 |
+
"q_ssim": float(structural_similarity(a, b, channel_axis=2, data_range=1.0)),
|
| 222 |
+
"q_psnr": float(peak_signal_noise_ratio(a, b, data_range=1.0))}
|
| 223 |
+
panels = [a, b]
|
| 224 |
+
if bf16 is not None:
|
| 225 |
+
c = decode(vae, bf16[key])
|
| 226 |
+
row.update(b_cos=float(cosine(ref[key], bf16[key])),
|
| 227 |
+
b_ssim=float(structural_similarity(a, c, channel_axis=2, data_range=1.0)),
|
| 228 |
+
b_psnr=float(peak_signal_noise_ratio(a, c, data_range=1.0)))
|
| 229 |
+
panels.append(c)
|
| 230 |
+
rows.append(row)
|
| 231 |
+
grid = np.concatenate(panels, axis=1)
|
| 232 |
+
Image.fromarray((grid * 255).round().astype(np.uint8)).save(os.path.join(args.out, f"{key}.png"))
|
| 233 |
+
print(json.dumps({k: (round(v, 5) if isinstance(v, float) else v) for k, v in row.items()}), flush=True)
|
| 234 |
+
|
| 235 |
+
def stats(name):
|
| 236 |
+
vals = [r[name] for r in rows if name in r]
|
| 237 |
+
return {"mean": float(np.mean(vals)), "min": float(np.min(vals))} if vals else None
|
| 238 |
+
|
| 239 |
+
summary = {k: stats(k) for k in ("q_cos", "q_ssim", "q_psnr", "b_cos", "b_ssim", "b_psnr")}
|
| 240 |
+
summary.update(mode=args.mode, fp16=args.fp16, quant=args.quant, steps=args.steps,
|
| 241 |
+
size=args.size, renders=len(rows),
|
| 242 |
+
fp16_bytes=os.path.getsize(args.fp16), quant_bytes=os.path.getsize(args.quant),
|
| 243 |
+
timing={"fp16": t_ref, "bf16": t_bf16, "quant": t_quant})
|
| 244 |
+
with open(os.path.join(args.out, "summary.json"), "w") as f:
|
| 245 |
+
json.dump({"summary": summary, "rows": rows}, f, indent=1)
|
| 246 |
+
print("SUMMARY " + json.dumps(summary), flush=True)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
main()
|
sdxl-lightning-4step-int4-convrot.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:78bd846a245583df0658fc3794e0c13a8ebb9f8682ac56c7dde944dce85afcfb
|
| 3 |
+
size 3772875825
|
sdxl-lightning-4step-int6-convrot.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a9cea1c43da44c431468ceb63e588f7dea32d6f67a6d5422110624a381f5e241
|
| 3 |
+
size 4313382791
|
sdxl-lightning-4step-int8-convrot.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7184dccfdeffb0619a09f2146619f0d300892b2c41ac6d1acbb7316315c77c8b
|
| 3 |
+
size 4718756459
|