├── LICENSE ├── NOTICE ├── README.md ├── config ├── ac_ds_4gpu_zero0.yaml ├── ac_ds_8gpu_zero0.yaml └── zero0.json ├── pipeline.py ├── qualitative_imgs.jpg ├── requirements.txt ├── train.py └── train.sh /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2025 AIDC-AI 2 | This project incorporates components from the Open Source Software below. 3 | The original copyright notices and the licenses under which we received such components are set forth below for informational purposes. 4 | 5 | Open Source Software Licensed under the BSD-3-Clause License: 6 | -------------------------------------------------------------------- 7 | 1. scipy https://pypi.org/project/scipy 8 | 2. xformers 0.0.28 https://pypi.org/project/xformers 9 | Copyright (c) 2017 - 2022 NVIDIA CORPORATION AFFILIATES. All rights reserved. 10 | Copyright (c) Facebook; Inc. and its affiliates 11 | 3. pandas https://pypi.org/project/pandas 12 | Terms of the BSD-3-Clause: 13 | -------------------------------------------------------------------- 14 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 15 | 16 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 19 | 20 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 21 | 22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | 24 | 25 | 26 | Open Source Software Licensed under the Apache-2.0 License: 27 | -------------------------------------------------------------------- 28 | 1. accelerate 0.20.2 https://pypi.org/project/accelerate 29 | 2. transformers 4.30.2 https://pypi.org/project/transformers 30 | Copyright 2018- The Hugging Face team. All rights reserved. 31 | 3. deepspeed 0.14.5 https://pypi.org/project/deepspeed 32 | Copyright (c) Microsoft Corporation.. 33 | Copyright (c) Microsoft Corporation. 34 | 4. diffusers 0.20.0 https://pypi.org/project/diffusers 35 | 5. datasets https://pypi.org/project/datasets 36 | 6. safetensors https://pypi.org/project/safetensors 37 | Terms of the Apache-2.0: 38 | -------------------------------------------------------------------- 39 | Apache License 40 | Version 2.0, January 2004 41 | http://www.apache.org/licenses/ 42 | 43 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 44 | 45 | 1. Definitions. 46 | 47 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 48 | 49 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 50 | 51 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 52 | 53 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 54 | 55 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 56 | 57 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 58 | 59 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 60 | 61 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 62 | 63 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 64 | 65 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 70 | 71 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 72 | 73 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 74 | 75 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 76 | 77 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 78 | 79 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 80 | 81 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 82 | 83 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 84 | 85 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 86 | 87 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 88 | 89 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 90 | 91 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 92 | 93 | END OF TERMS AND CONDITIONS 94 | 95 | APPENDIX: How to apply the Apache License to your work. 96 | 97 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 98 | 99 | Copyright [yyyy] [name of copyright owner] 100 | 101 | Licensed under the Apache License, Version 2.0 (the "License"); 102 | you may not use this file except in compliance with the License. 103 | You may obtain a copy of the License at 104 | 105 | http://www.apache.org/licenses/LICENSE-2.0 106 | 107 | Unless required by applicable law or agreed to in writing, software 108 | distributed under the License is distributed on an "AS IS" BASIS, 109 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 110 | See the License for the specific language governing permissions and 111 | limitations under the License. 112 | 113 | 114 | 115 | Open Source Software Licensed under the MIT License: 116 | -------------------------------------------------------------------- 117 | 1. bitsandbytes https://pypi.org/project/bitsandbytes 118 | 2. pyyaml https://pypi.org/project/pyyaml 119 | Terms of the MIT: 120 | -------------------------------------------------------------------- 121 | MIT License 122 | 123 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 124 | 125 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 126 | 127 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CHATS: Combining Human-Aligned Optimization and Test-Time Sampling for Text-to-Image Generation (ICML2025) 2 | 3 |

4 | 📝 Paper • 💡 知乎 • 🤗 HF Repo • 🖼️ Demo 5 |

6 | 7 | CHATS is a next-generation framework that unifies human preference alignment with classifier-free guidance by modeling both preferred and dispreferred distributions and using a proxy-prompt-based sampling strategy for superior text–image alignment, fidelity, and aesthetic consistency. See the images generated below for examples. 8 | 9 | 10 |
11 | CHATS results 12 |
Generation examples using CHATS (cf. Fig.1 in our paper).
13 |
14 | 15 | --- 16 | 17 | ## 🚀 Key Features 18 | 19 | - **Human-Aligned Fine-Tuning with CFG Integration** 20 | We integrate human preference alignment with classifier-free guidance sampling into a unified framework. 21 | 22 | - **Proxy-Prompt Sampling** 23 | Leverage useful signals from both preferred and dispreferred distributions at test time. 24 | 25 | - **Data Efficiency** 26 | State-of-the-art results across benchmarks with minimal fine-tuning effort on a small, high-quality dataset. 27 | 28 | - **Plug-and-Play** 29 | Compatible with any diffusion backbone and existing guidance methods. 30 | 31 | --- 32 | 33 | ## 📦 Installation 34 | 35 | ```bash 36 | git clone https://github.com/AIDC-AI/CHATS.git 37 | cd CHATS 38 | pip install -r requirements.txt 39 | 40 | ``` 41 | 42 | ## 📂 Model Checkpoints 43 | 44 | We provide pretrained CHATS checkpoints on SDXL for easy download and evaluation: 45 | 46 | - **Model Repository**: [![Hugging Face](https://img.shields.io/badge/Hugging%20Face-CHATS-blue?logo=Huggingface)](https://huggingface.co/AIDC-AI/CHATS) 47 | 48 | 49 | ## 🛠️ Quick Start 50 | 51 | ```python 52 | import torch 53 | from pipeline import ChatsSDXLPipeline 54 | 55 | # Load CHATS-SDXL pipeline 56 | pipe = ChatsSDXLPipeline.from_pretrained( 57 | "AIDC-AI/CHATS", 58 | torch_dtype=torch.bfloat16 59 | ) 60 | pipe.to("cuda") 61 | 62 | # Generate images 63 | images = pipe( 64 | prompt=["A serene mountain lake at sunset"], 65 | num_inference_steps=50, 66 | guidance_scale=5, 67 | seed=0 68 | ) 69 | 70 | # Save outputs 71 | for i, img in enumerate(images): 72 | img.save(f"output_{i}.png") 73 | ``` 74 | 75 | ## 🏋️ Training 76 | 77 | To train CHATS from scratch or fine-tune on your own data, run: 78 | 79 | ```bash 80 | accelerate launch --config_file=config/ac_ds_8gpu_zero0.yaml train.py \ 81 | --pretrained_model_name_or_path=stabilityai/stable-diffusion-xl-base-1.0 \ 82 | --pretrained_vae_model_name_or_path=madebyollin/sdxl-vae-fp16-fix \ 83 | --resolution=1024 \ 84 | --dataloader_num_workers 16 \ 85 | --train_batch_size=1 \ 86 | --gradient_accumulation_steps=16 \ 87 | --max_train_steps=6000 \ 88 | --learning_rate=3e-09 --scale_lr --lr_scheduler=constant_with_warmup --lr_warmup_steps=100 \ 89 | --mixed_precision=bf16 \ 90 | --allow_tf32 \ 91 | --checkpointing_steps=100 \ 92 | --output_dir=output \ 93 | --resume_from_checkpoint latest \ 94 | --use_adafactor \ 95 | --gradient_checkpointing \ 96 | --dataset_name=data-is-better-together/open-image-preferences-v1-binarized \ 97 | ``` 98 | 99 | ### Args: 100 | - config_file: This DeepSpeed parameter allows you to specify the configuration file. If you wish to adjust the number of GPUs used for training, simply change the value of **num_processes** in the ac_ds_xgpu_zero0.yaml file to reflect the desired GPU count. 101 | - pretrained_model_name_or_path: name or patch of unet model to load 102 | - pretrained_vae_model_name_or_path: name or patch of vae model to load 103 | - max_train_steps: max steps to train 104 | - output: output dir 105 | - dataset_name: the huggingface sufix of the selected dataset (e.g. OIP) 106 | 107 | 108 | 109 | ## 📚 Citation 110 | 111 | If you use CHATS, please cite our ICML 2025 paper: 112 | 113 | ```bibtex 114 | @inproceedings{fu2025chats, 115 | title={CHATS: Combining Human-Aligned Optimization and Test-Time Sampling for Text-to-Image Generation}, 116 | author={Fu, Minghao and Wang, Guo-Hua and Cao, Liangfu and Chen, Qing-Guo and Xu, Zhao and Luo, Weihua and Zhang, Kaifu}, 117 | booktitle={International Conference on Machine Learning (ICML)}, 118 | year={2025} 119 | } 120 | ``` 121 | 122 | ## 🙏 Acknowledgments 123 | 124 | The code is built upon [DiffusionDPO](https://github.com/SalesforceAIResearch/DiffusionDPO), [Diffusers](https://github.com/huggingface/diffusers), and [Transformers](https://github.com/huggingface/transformers). 125 | 126 | ## 📄 License 127 | 128 | The project is released under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0, SPDX-License-identifier: Apache-2.0). 129 | 130 | ## 🚨 Disclaimer 131 | 132 | We used compliance checking algorithms during the training process, to ensure the compliance of the trained model to the best of our ability. Due to complex data and the diversity of language model usage scenarios, we cannot guarantee that the model is completely free of copyright issues or improper content. If you believe anything infringes on your rights or generates improper content, please contact us, and we will promptly address the matter. 133 | -------------------------------------------------------------------------------- /config/ac_ds_4gpu_zero0.yaml: -------------------------------------------------------------------------------- 1 | compute_environment: LOCAL_MACHINE 2 | deepspeed_config: 3 | deepspeed_multinode_launcher: standard 4 | deepspeed_config_file: config/zero0.json 5 | zero3_init_flag: false 6 | distributed_type: DEEPSPEED 7 | downcast_bf16: 'no' 8 | main_training_function: main 9 | rdzv_backend: static 10 | same_network: true 11 | tpu_env: [] 12 | tpu_use_cluster: false 13 | tpu_use_sudo: false 14 | use_cpu: false 15 | num_processes: 4 16 | -------------------------------------------------------------------------------- /config/ac_ds_8gpu_zero0.yaml: -------------------------------------------------------------------------------- 1 | compute_environment: LOCAL_MACHINE 2 | deepspeed_config: 3 | deepspeed_multinode_launcher: standard 4 | deepspeed_config_file: config/zero0.json 5 | zero3_init_flag: false 6 | distributed_type: DEEPSPEED 7 | downcast_bf16: 'no' 8 | main_training_function: main 9 | rdzv_backend: static 10 | same_network: true 11 | tpu_env: [] 12 | tpu_use_cluster: false 13 | tpu_use_sudo: false 14 | use_cpu: false 15 | num_processes: 8 -------------------------------------------------------------------------------- /config/zero0.json: -------------------------------------------------------------------------------- 1 | { 2 | "fp16": { 3 | "enabled": false 4 | }, 5 | "bf16": { 6 | "enabled": "auto" 7 | }, 8 | "zero_optimization": { 9 | "stage": 0, 10 | "allgather_partitions": true, 11 | "allgather_bucket_size": 5e8, 12 | "overlap_comm": true, 13 | "reduce_scatter": true, 14 | "reduce_bucket_size": 5e8, 15 | "contiguous_gradients": true 16 | }, 17 | "gradient_accumulation_steps": "auto", 18 | "gradient_clipping": "auto", 19 | "steps_per_print": 2000, 20 | "train_batch_size": "auto", 21 | "train_micro_batch_size_per_gpu": 1, 22 | "wall_clock_breakdown": false, 23 | "compile": { 24 | "disable": false, 25 | "backend": "inductor" 26 | } 27 | } -------------------------------------------------------------------------------- /pipeline.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | # Copyright (C) 2025 AIDC-AI 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from typing import Optional, Union, List, Dict, Any 18 | 19 | import math 20 | import os 21 | import torch 22 | import torch.nn as nn 23 | from diffusers import DiffusionPipeline, EulerDiscreteScheduler, SchedulerMixin 24 | from diffusers.models import AutoencoderKL, UNet2DConditionModel 25 | from diffusers.configuration_utils import ConfigMixin, register_to_config 26 | from diffusers.utils import logging 27 | from PIL import Image 28 | 29 | from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer 30 | 31 | def get_noise( 32 | num_samples: int, 33 | channel: int, 34 | height: int, 35 | width: int, 36 | device: torch.device, 37 | dtype: torch.dtype, 38 | seed: int, 39 | ): 40 | return torch.randn( 41 | num_samples, 42 | channel, 43 | # allow for packing 44 | 2 * math.ceil(height / 16), 45 | 2 * math.ceil(width / 16), 46 | device=device, 47 | dtype=dtype, 48 | generator=torch.Generator(device=device).manual_seed(seed), 49 | ) 50 | 51 | class ChatsSDXLPipeline(DiffusionPipeline, ConfigMixin): 52 | 53 | @register_to_config 54 | def __init__( 55 | self, 56 | unet_win: nn.Module, 57 | unet_lose: nn.Module, 58 | text_encoder: CLIPTextModel, 59 | text_encoder_two: CLIPTextModelWithProjection, 60 | tokenizer: CLIPTokenizer, 61 | tokenizer_two: CLIPTokenizer, 62 | vae: AutoencoderKL, 63 | scheduler: SchedulerMixin 64 | ): 65 | super().__init__() 66 | 67 | self.register_modules( 68 | unet_win=unet_win, 69 | unet_lose=unet_lose, 70 | text_encoder=text_encoder, 71 | text_encoder_two=text_encoder_two, 72 | tokenizer=tokenizer, 73 | tokenizer_two=tokenizer_two, 74 | vae=vae, 75 | scheduler=scheduler 76 | ) 77 | 78 | 79 | @classmethod 80 | def from_pretrained( 81 | cls, 82 | pretrained_model_name_or_path: Union[str, os.PathLike], 83 | **kwargs, 84 | ) -> "ChatsSDXLPipeline": 85 | 86 | return super().from_pretrained(pretrained_model_name_or_path, **kwargs) 87 | 88 | def save_pretrained(self, save_directory: Union[str, os.PathLike]): 89 | super().save_pretrained(save_directory) 90 | 91 | @torch.no_grad() 92 | def encode_text(self, tokenizers, text_encoders, prompt): 93 | prompt_embeds_list = [] 94 | 95 | with torch.no_grad(): 96 | for tokenizer, text_encoder in zip(tokenizers, text_encoders): 97 | text_inputs = tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt",) 98 | text_input_ids = text_inputs.input_ids 99 | prompt_embeds = text_encoder(text_input_ids.to(self.unet_win.device), output_hidden_states=True) 100 | pooled_prompt_embeds = prompt_embeds[0] 101 | prompt_embeds = prompt_embeds.hidden_states[-2] 102 | prompt_embeds_list.append(prompt_embeds) 103 | 104 | prompt_embeds = torch.concat(prompt_embeds_list, dim=-1) 105 | prompt_embeds = prompt_embeds.to(dtype=text_encoders[-1].dtype, device=text_encoders[-1].device) 106 | 107 | return prompt_embeds, pooled_prompt_embeds 108 | 109 | @torch.no_grad() 110 | def __call__( 111 | self, 112 | prompt: Union[str, List[str]], 113 | num_inference_steps: int = 50, 114 | guidance_scale: float = 7.5, 115 | latents: torch.FloatTensor = None, 116 | height: int = 1024, 117 | width: int = 1024, 118 | seed: int = 0, 119 | alpha: float=0.5 120 | ): 121 | if isinstance(prompt, str): 122 | prompt = [prompt] 123 | 124 | device = self.unet_win.device 125 | 126 | tokenizers = [self.tokenizer, self.tokenizer_two] 127 | text_encoders = [self.text_encoder, self.text_encoder_two] 128 | 129 | prompt_embeds, pooled_prompt_embeds = self.encode_text(tokenizers, text_encoders, prompt) 130 | negative_prompt_embeds, negative_pooled_prompt_embeds = self.encode_text(tokenizers, text_encoders, "") 131 | 132 | self.scheduler.set_timesteps(num_inference_steps, device=device) 133 | timesteps = self.scheduler.timesteps 134 | 135 | bs = len(prompt) 136 | channel = self.vae.config.latent_channels 137 | height = 16 * (height // 16) 138 | width = 16 * (width // 16) 139 | 140 | # prepare input 141 | latents = get_noise( 142 | bs, 143 | channel, 144 | height, 145 | width, 146 | device=device, 147 | dtype=self.unet_win.dtype, 148 | seed=seed, 149 | ) 150 | latents = latents * self.scheduler.init_noise_sigma 151 | 152 | add_time_ids = torch.tensor([height, width, 0, 0, height, width], dtype=latents.dtype, device=device)[None, :].repeat(latents.size(0), 1) 153 | 154 | for i, t in enumerate(timesteps): 155 | latent_model_input = self.scheduler.scale_model_input(latents, t) 156 | 157 | added_cond_kwargs_win = {"text_embeds": pooled_prompt_embeds, "time_ids": add_time_ids} 158 | added_cond_kwargs_lose = {"text_embeds": pooled_prompt_embeds * (-alpha) + negative_pooled_prompt_embeds * (1. + alpha), "time_ids": add_time_ids} 159 | 160 | pred_win = self.unet_win(latent_model_input, t, encoder_hidden_states=prompt_embeds, added_cond_kwargs=added_cond_kwargs_win, return_dict=False)[0] 161 | pred_lose = self.unet_lose(latent_model_input, t, encoder_hidden_states=prompt_embeds * (-alpha) + negative_prompt_embeds * (1. + alpha), added_cond_kwargs=added_cond_kwargs_lose, return_dict=False)[0] 162 | 163 | noise_pred = pred_win + guidance_scale * (pred_win - pred_lose) 164 | latents = self.scheduler.step(noise_pred, t, latents, generator=None, return_dict=False)[0] 165 | 166 | x = latents.float() 167 | 168 | with torch.no_grad(): 169 | with torch.autocast(device_type=device.type, dtype=torch.float32): 170 | if hasattr(self.vae.config, 'scaling_factor') and self.vae.config.scaling_factor is not None: 171 | x = x / self.vae.config.scaling_factor 172 | if hasattr(self.vae.config, 'shift_factor') and self.vae.config.shift_factor is not None: 173 | x = x + self.vae.config.shift_factor 174 | x = self.vae.decode(x, return_dict=False)[0] 175 | 176 | # bring into PIL format and save 177 | x = (x / 2 + 0.5).clamp(0, 1) 178 | x = x.cpu().permute(0, 2, 3, 1).float().numpy() 179 | images = (x * 255).round().astype("uint8") 180 | pil_images = [Image.fromarray(image) for image in images] 181 | 182 | return pil_images 183 | -------------------------------------------------------------------------------- /qualitative_imgs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AIDC-AI/CHATS/687644119a3202987e0bc17df02e1e6f97b0841c/qualitative_imgs.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | transformers==4.44.2 2 | accelerate==0.31.0 3 | deepspeed==0.14.5 4 | numpy==1.24.3 5 | diffusers 6 | datasets 7 | requests 8 | fastapi 9 | scipy 10 | pandas 11 | xformers 12 | ftfy 13 | Jinja2 14 | bitsandbytes 15 | safetensors 16 | pyyaml 17 | pillow==10.3.0 18 | --extra-index-url https://download.pytorch.org/whl/cu124 19 | torch==2.4.1 20 | torchvision==0.19.1 21 | torchaudio==2.4.1 -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | # Copyright (C) 2025 AIDC-AI 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import argparse 18 | import io 19 | import logging 20 | import math 21 | import os 22 | import random 23 | import shutil 24 | import sys 25 | from pathlib import Path 26 | import torch.nn as nn 27 | 28 | import accelerate 29 | import datasets 30 | import numpy as np 31 | from PIL import Image 32 | import torch 33 | import torch.nn.functional as F 34 | import torch.utils.checkpoint 35 | import transformers 36 | from accelerate import Accelerator 37 | from accelerate.logging import get_logger 38 | from accelerate.state import AcceleratorState 39 | from accelerate.utils import ProjectConfiguration, set_seed 40 | from datasets import load_dataset 41 | from huggingface_hub import create_repo, upload_folder 42 | from packaging import version 43 | from torchvision import transforms 44 | from tqdm.auto import tqdm 45 | from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer 46 | from transformers.utils import ContextManagers 47 | from diffusers.utils.torch_utils import is_compiled_module 48 | from accelerate.utils import DistributedType, ProjectConfiguration, set_seed 49 | 50 | import diffusers 51 | from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel, StableDiffusionXLPipeline 52 | from diffusers.optimization import get_scheduler 53 | from diffusers.utils import check_min_version, deprecate, is_wandb_available, make_image_grid 54 | from diffusers.utils.import_utils import is_xformers_available 55 | 56 | import functools 57 | from torchvision.transforms.functional import crop 58 | from transformers import AutoTokenizer 59 | from datasets import load_dataset 60 | 61 | 62 | # Will error if the minimal version of diffusers is not installed. Remove at your own risks. 63 | check_min_version("0.20.0") 64 | 65 | logger = get_logger(__name__, log_level="INFO") 66 | 67 | def parse_args(): 68 | parser = argparse.ArgumentParser(description="Simple example of a training script.") 69 | parser.add_argument( 70 | "--pretrained_model_name_or_path", 71 | type=str, 72 | default=None, 73 | required=True, 74 | help="Path to pretrained model or model identifier from huggingface.co/models.", 75 | ) 76 | parser.add_argument( 77 | "--pretrained_vae_model_name_or_path", 78 | type=str, 79 | default=None, 80 | help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.", 81 | ) 82 | parser.add_argument( 83 | "--revision", 84 | type=str, 85 | default=None, 86 | required=False, 87 | help="Revision of pretrained model identifier from huggingface.co/models.", 88 | ) 89 | parser.add_argument( 90 | "--output_dir", 91 | type=str, 92 | default="output", 93 | help="The output directory where the model predictions and checkpoints will be written.", 94 | ) 95 | parser.add_argument("--seed", type=int, default=None, 96 | # was random for submission, need to test that not distributing same noise etc across devices 97 | help="A seed for reproducible training.") 98 | parser.add_argument( 99 | "--resolution", 100 | type=int, 101 | default=None, 102 | help=( 103 | "The resolution for input images, all the images in the dataset will be resized to this" 104 | " resolution" 105 | ), 106 | ) 107 | parser.add_argument( 108 | "--train_batch_size", type=int, default=1, help="Batch size (per device) for the training dataloader." 109 | ) 110 | parser.add_argument( 111 | "--num_train_epochs", type=int, default=100 112 | ) 113 | parser.add_argument( 114 | "--max_train_steps", 115 | type=int, 116 | default=2000, 117 | help="Total number of training steps to perform. If provided, overrides num_train_epochs.", 118 | ) 119 | parser.add_argument( 120 | "--gradient_accumulation_steps", 121 | type=int, 122 | default=1, 123 | help="Number of updates steps to accumulate before performing a backward/update pass.", 124 | ) 125 | parser.add_argument( 126 | "--gradient_checkpointing", 127 | action="store_true", 128 | help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.", 129 | ) 130 | parser.add_argument( 131 | "--learning_rate", 132 | type=float, 133 | default=1e-8, 134 | help="Initial learning rate (after the potential warmup period) to use.", 135 | ) 136 | parser.add_argument( 137 | "--scale_lr", 138 | action="store_true", 139 | default=False, 140 | help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.", 141 | ) 142 | parser.add_argument( 143 | "--lr_scheduler", 144 | type=str, 145 | default="constant_with_warmup", 146 | help=( 147 | 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",' 148 | ' "constant", "constant_with_warmup"]' 149 | ), 150 | ) 151 | parser.add_argument( 152 | "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler." 153 | ) 154 | parser.add_argument( 155 | "--use_adafactor", action="store_true", help="Whether or not to use adafactor (should save mem)" 156 | ) 157 | # Bram Note: Haven't looked @ this yet 158 | parser.add_argument( 159 | "--allow_tf32", 160 | action="store_true", 161 | help=( 162 | "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see" 163 | " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices" 164 | ), 165 | ) 166 | parser.add_argument( 167 | "--dataloader_num_workers", 168 | type=int, 169 | default=0, 170 | help=( 171 | "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process." 172 | ), 173 | ) 174 | parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.") 175 | parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.") 176 | parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.") 177 | parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer") 178 | parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.") 179 | parser.add_argument( 180 | "--hub_model_id", 181 | type=str, 182 | default=None, 183 | help="The name of the repository to keep in sync with the local `output_dir`.", 184 | ) 185 | parser.add_argument( 186 | "--logging_dir", 187 | type=str, 188 | default="logs", 189 | help=( 190 | "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to" 191 | " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***." 192 | ), 193 | ) 194 | parser.add_argument( 195 | "--mixed_precision", 196 | type=str, 197 | default="fp16", 198 | choices=["no", "fp16", "bf16"], 199 | help=( 200 | "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >=" 201 | " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the" 202 | " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config." 203 | ), 204 | ) 205 | parser.add_argument( 206 | "--report_to", 207 | type=str, 208 | default="tensorboard", 209 | help=( 210 | 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`' 211 | ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.' 212 | ), 213 | ) 214 | parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank") 215 | parser.add_argument( 216 | "--checkpointing_steps", 217 | type=int, 218 | default=500, 219 | help=( 220 | "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming" 221 | " training using `--resume_from_checkpoint`." 222 | ), 223 | ) 224 | parser.add_argument( 225 | "--resume_from_checkpoint", 226 | type=str, 227 | default=None, 228 | help=( 229 | "Whether training should be resumed from a previous checkpoint. Use a path saved by" 230 | ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.' 231 | ), 232 | ) 233 | 234 | ## CHATS 235 | parser.add_argument("--beta_dpo", type=float, default=1000, help="The beta DPO temperature controlling strength of KL penalty") 236 | parser.add_argument( 237 | "--puncond", 238 | type=float, 239 | default=0.5, 240 | help="Probability of prompts for lose model to be zero", 241 | ) 242 | parser.add_argument( 243 | "--hard_skip_resume", action="store_true", help="Load weights etc. but don't iter through loader for loader resume, useful b/c resume takes forever" 244 | ) 245 | parser.add_argument( 246 | "--dataset_name", 247 | type=str, 248 | default=None, 249 | help=( 250 | "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private," 251 | " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem," 252 | " or to a folder containing files that 🤗 Datasets can understand." 253 | ), 254 | ) 255 | parser.add_argument( 256 | "--split", type=str, default='train', help="Datasplit" 257 | ) 258 | parser.add_argument( 259 | "--project_name", 260 | type=str, 261 | default="CHATS training", 262 | ) 263 | 264 | args = parser.parse_args() 265 | env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) 266 | if env_local_rank != -1 and env_local_rank != args.local_rank: 267 | args.local_rank = env_local_rank 268 | 269 | ## SDXL 270 | print("Running CHATS-SDXL") 271 | if args.resolution is None: 272 | args.resolution = 1024 273 | 274 | return args 275 | 276 | DATASET_NAME_MAPPING = { 277 | "data-is-better-together/open-image-preferences-v1-binarized": ("chosen", "rejected", "prompt"), 278 | } 279 | 280 | 281 | # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt 282 | def encode_prompt_sdxl(batch, text_encoders, tokenizers, proportion_empty_prompts, caption_column, is_train=True): 283 | prompt_embeds_list = [] 284 | prompt_batch = batch[caption_column] 285 | 286 | captions = [] 287 | for caption in prompt_batch: 288 | if random.random() < proportion_empty_prompts: 289 | captions.append("") 290 | elif isinstance(caption, str): 291 | captions.append(caption) 292 | elif isinstance(caption, (list, np.ndarray)): 293 | # take a random caption if there are multiple 294 | captions.append(random.choice(caption) if is_train else caption[0]) 295 | 296 | with torch.no_grad(): 297 | for tokenizer, text_encoder in zip(tokenizers, text_encoders): 298 | text_inputs = tokenizer( 299 | captions, 300 | padding="max_length", 301 | max_length=tokenizer.model_max_length, 302 | truncation=True, 303 | return_tensors="pt", 304 | ) 305 | text_input_ids = text_inputs.input_ids 306 | prompt_embeds = text_encoder( 307 | text_input_ids.to('cuda'), 308 | output_hidden_states=True, 309 | ) 310 | 311 | # We are only ALWAYS interested in the pooled output of the final text encoder 312 | pooled_prompt_embeds = prompt_embeds[0] 313 | prompt_embeds = prompt_embeds.hidden_states[-2] 314 | bs_embed, seq_len, _ = prompt_embeds.shape 315 | prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1) 316 | prompt_embeds_list.append(prompt_embeds) 317 | 318 | prompt_embeds = torch.concat(prompt_embeds_list, dim=-1) 319 | pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1) 320 | return {"prompt_embeds": prompt_embeds, "pooled_prompt_embeds": pooled_prompt_embeds} 321 | 322 | 323 | 324 | 325 | def main(): 326 | 327 | args = parse_args() 328 | 329 | #### START ACCELERATOR BOILERPLATE ### 330 | logging_dir = os.path.join(args.output_dir, args.logging_dir) 331 | 332 | accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir) 333 | 334 | accelerator = Accelerator( 335 | gradient_accumulation_steps=args.gradient_accumulation_steps, 336 | mixed_precision=args.mixed_precision, 337 | log_with=args.report_to, 338 | project_config=accelerator_project_config, 339 | ) 340 | 341 | # Make one log on every process with the configuration for debugging. 342 | logging.basicConfig( 343 | format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", 344 | datefmt="%m/%d/%Y %H:%M:%S", 345 | level=logging.INFO, 346 | ) 347 | logger.info(accelerator.state, main_process_only=False) 348 | if accelerator.is_local_main_process: 349 | datasets.utils.logging.set_verbosity_warning() 350 | transformers.utils.logging.set_verbosity_warning() 351 | diffusers.utils.logging.set_verbosity_info() 352 | else: 353 | datasets.utils.logging.set_verbosity_error() 354 | transformers.utils.logging.set_verbosity_error() 355 | diffusers.utils.logging.set_verbosity_error() 356 | 357 | # If passed along, set the training seed now. 358 | if args.seed is not None: 359 | set_seed(args.seed + accelerator.process_index) # added in + term, untested 360 | 361 | # Handle the repository creation 362 | if accelerator.is_main_process: 363 | if args.output_dir is not None: 364 | os.makedirs(args.output_dir, exist_ok=True) 365 | ### END ACCELERATOR BOILERPLATE 366 | 367 | 368 | ### START DIFFUSION BOILERPLATE ### 369 | # Load scheduler, tokenizer and models. 370 | noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler") 371 | 372 | # Load the tokenizers 373 | tokenizer_one = AutoTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, use_fast=False) 374 | tokenizer_two = AutoTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer_2", revision=args.revision, use_fast=False) 375 | 376 | 377 | # Not sure if we're hitting this at all 378 | def deepspeed_zero_init_disabled_context_manager(): 379 | """ 380 | returns either a context list that includes one that will disable zero.Init or an empty context list 381 | """ 382 | deepspeed_plugin = AcceleratorState().deepspeed_plugin if accelerate.state.is_initialized() else None 383 | if deepspeed_plugin is None: 384 | return [] 385 | 386 | return [deepspeed_plugin.zero3_init_context_manager(enable=False)] 387 | 388 | 389 | # BRAM NOTE: We're not using deepspeed currently so not sure it'll work. Could be good to add though! 390 | # 391 | # Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3. 392 | # For this to work properly all models must be run through `accelerate.prepare`. But accelerate 393 | # will try to assign the same optimizer with the same weights to all models during 394 | # `deepspeed.initialize`, which of course doesn't work. 395 | # 396 | # For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2 397 | # frozen models from being partitioned during `zero.Init` which gets called during 398 | # `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding 399 | # across multiple gpus and only UNet2DConditionModel will get ZeRO sharded. 400 | with ContextManagers(deepspeed_zero_init_disabled_context_manager()): 401 | # SDXL has two text encoders 402 | text_encoder_one = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision) 403 | text_encoder_two = CLIPTextModelWithProjection.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision) 404 | 405 | text_encoders = [text_encoder_one, text_encoder_two] 406 | tokenizers = [tokenizer_one, tokenizer_two] 407 | 408 | # Can custom-select VAE (used in original SDXL tuning) 409 | vae = AutoencoderKL.from_pretrained(args.pretrained_vae_model_name_or_path, subfolder=None, revision=args.revision) 410 | ref_unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision) 411 | 412 | 413 | unet_win = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision) 414 | unet_lose = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision) 415 | unet = nn.ModuleDict({"win" : unet_win, "lose" : unet_lose}) 416 | 417 | 418 | # Freeze vae, text_encoder(s), reference unet 419 | vae.requires_grad_(False) 420 | text_encoder_one.requires_grad_(False) 421 | text_encoder_two.requires_grad_(False) 422 | ref_unet.requires_grad_(False) 423 | 424 | print(sum([p.numel() for p in unet.parameters() if p.requires_grad]) / 1000000, 'M parameters') 425 | 426 | # xformers efficient attention 427 | if is_xformers_available(): 428 | import xformers 429 | 430 | xformers_version = version.parse(xformers.__version__) 431 | if xformers_version == version.parse("0.0.16"): 432 | logger.warn( 433 | "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details." 434 | ) 435 | unet["win"].enable_xformers_memory_efficient_attention() 436 | unet["lose"].enable_xformers_memory_efficient_attention() 437 | else: 438 | raise ValueError("xformers is not available. Make sure it is installed correctly") 439 | 440 | 441 | def unwrap_model(model): 442 | model = accelerator.unwrap_model(model) 443 | model = model._orig_mod if is_compiled_module(model) else model 444 | return model 445 | 446 | def save_model_hook(models, weights, output_dir): 447 | if accelerator.is_main_process: 448 | 449 | torch.save(unwrap_model(unet).state_dict(), os.path.join(output_dir, "unet_model_weights.pth")) 450 | 451 | for i, model in enumerate(models): 452 | 453 | if len(weights) > 0: 454 | weights.pop() 455 | 456 | def load_model_hook(models, input_dir): 457 | 458 | if os.path.exists(os.path.join(input_dir, "unet_model_weights.pth")): 459 | state_dict = torch.load(os.path.join(input_dir, "unet_model_weights.pth")) 460 | else: 461 | raise NotImplementedError 462 | 463 | unwrap_model(unet).load_state_dict(state_dict) 464 | for _ in range(len(models)): 465 | model = models.pop() 466 | 467 | accelerator.register_save_state_pre_hook(save_model_hook) 468 | accelerator.register_load_state_pre_hook(load_model_hook) 469 | 470 | if args.gradient_checkpointing: 471 | print("Enabling gradient checkpointing") 472 | unet["win"].enable_gradient_checkpointing() 473 | unet["lose"].enable_gradient_checkpointing() 474 | 475 | if args.allow_tf32: 476 | torch.backends.cuda.matmul.allow_tf32 = True 477 | 478 | if args.scale_lr: 479 | args.learning_rate = ( 480 | args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes 481 | ) 482 | 483 | params_to_optimize = [p for p in unet.parameters() if p.requires_grad] 484 | for n, p in unet.named_parameters(): 485 | if p.requires_grad: 486 | print(n) 487 | 488 | if args.use_adafactor: 489 | optimizer = transformers.Adafactor(params_to_optimize, 490 | lr=args.learning_rate, 491 | weight_decay=args.adam_weight_decay, 492 | clip_threshold=1.0, 493 | scale_parameter=False, 494 | relative_step=False) 495 | else: 496 | optimizer = torch.optim.AdamW( 497 | params_to_optimize, 498 | lr=args.learning_rate, 499 | betas=(args.adam_beta1, args.adam_beta2), 500 | weight_decay=args.adam_weight_decay, 501 | eps=args.adam_epsilon, 502 | ) 503 | 504 | # load dataset 505 | dataset = load_dataset(args.dataset_name) 506 | 507 | dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None) 508 | 509 | image_column_win = dataset_columns[0] 510 | image_column_lose = dataset_columns[1] 511 | caption_column = dataset_columns[2] 512 | 513 | # Preprocessing the datasets. 514 | train_transforms = transforms.Compose( 515 | [ 516 | transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR), 517 | transforms.CenterCrop(args.resolution), 518 | transforms.ToTensor(), 519 | transforms.Normalize([0.5], [0.5]), 520 | ] 521 | ) 522 | 523 | #### START PREPROCESSING/COLLATION #### 524 | def preprocess_train(examples): 525 | all_pixel_values = [] 526 | for col_name in [image_column_win, image_column_lose]: 527 | images = [Image.open(io.BytesIO(im_bytes['bytes'])).convert("RGB") for im_bytes in examples[col_name]] 528 | pixel_values = [train_transforms(image) for image in images] 529 | all_pixel_values.append(pixel_values) 530 | im_tup_iterator = zip(*all_pixel_values) 531 | combined_pixel_values = [] 532 | for im_tup in im_tup_iterator: 533 | combined_im = torch.cat(im_tup, dim=0) 534 | combined_pixel_values.append(combined_im) 535 | examples["pixel_values"] = combined_pixel_values 536 | return examples 537 | 538 | def collate_fn(examples): 539 | pixel_values = torch.stack([example["pixel_values"] for example in examples]) 540 | pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float() 541 | return_d = {"pixel_values": pixel_values} 542 | return_d[caption_column] = [example[caption_column] for example in examples] 543 | 544 | return return_d 545 | 546 | #### END PREPROCESSING/COLLATION #### 547 | 548 | # Set the training transforms 549 | train_dataset = dataset[args.split].with_transform(preprocess_train) 550 | 551 | 552 | train_dataloader = torch.utils.data.DataLoader( 553 | train_dataset, 554 | shuffle=True, 555 | collate_fn=collate_fn, 556 | batch_size=args.train_batch_size, 557 | num_workers=args.dataloader_num_workers, 558 | pin_memory=True, 559 | ) 560 | 561 | # Scheduler and math around the number of training steps. 562 | overrode_max_train_steps = False 563 | num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) 564 | if args.max_train_steps is None: 565 | args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch 566 | overrode_max_train_steps = True 567 | 568 | lr_scheduler = get_scheduler( 569 | args.lr_scheduler, 570 | optimizer=optimizer, 571 | num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes, 572 | num_training_steps=args.max_train_steps * accelerator.num_processes, 573 | ) 574 | 575 | 576 | #### START ACCELERATOR PREP #### 577 | unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( 578 | unet, optimizer, train_dataloader, lr_scheduler 579 | ) 580 | 581 | # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision 582 | # as these weights are only used for inference, keeping weights in full precision is not required. 583 | weight_dtype = torch.float32 584 | if accelerator.mixed_precision == "fp16": 585 | weight_dtype = torch.float16 586 | args.mixed_precision = accelerator.mixed_precision 587 | elif accelerator.mixed_precision == "bf16": 588 | weight_dtype = torch.bfloat16 589 | args.mixed_precision = accelerator.mixed_precision 590 | 591 | 592 | # Move text_encode and vae to cpu and cast to weight_dtype 593 | vae.to(accelerator.device, dtype=weight_dtype) 594 | text_encoder_one.to(accelerator.device, dtype=weight_dtype) 595 | text_encoder_two.to(accelerator.device, dtype=weight_dtype) 596 | ref_unet.to(accelerator.device, dtype=weight_dtype) 597 | 598 | # Offload to cpu to redue the GPU memory consumption 599 | vae = accelerate.cpu_offload(vae) 600 | text_encoder_one = accelerate.cpu_offload(text_encoder_one) 601 | text_encoder_two = accelerate.cpu_offload(text_encoder_two) 602 | ref_unet = accelerate.cpu_offload(ref_unet) 603 | 604 | 605 | # We need to recalculate our total training steps as the size of the training dataloader may have changed. 606 | num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) 607 | if overrode_max_train_steps: 608 | args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch 609 | args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) 610 | 611 | if accelerator.is_main_process: 612 | tracker_config = dict(vars(args)) 613 | accelerator.init_trackers(args.project_name, tracker_config) 614 | 615 | # Training initialization 616 | total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps 617 | 618 | logger.info("***** Running training *****") 619 | logger.info(f" Num examples = {len(dataset)}") 620 | logger.info(f" Num Epochs = {args.num_train_epochs}") 621 | logger.info(f" Instantaneous batch size per device = {args.train_batch_size}") 622 | logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") 623 | logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") 624 | logger.info(f" Total optimization steps = {args.max_train_steps}") 625 | global_step = 0 626 | first_epoch = 0 627 | 628 | 629 | # Potentially load in the weights and states from a previous save 630 | if args.resume_from_checkpoint: 631 | if args.resume_from_checkpoint != "latest": 632 | path = os.path.basename(args.resume_from_checkpoint) 633 | else: 634 | # Get the most recent checkpoint 635 | dirs = os.listdir(args.output_dir) 636 | dirs = [d for d in dirs if d.startswith("checkpoint")] 637 | dirs = sorted(dirs, key=lambda x: int(x.split("-")[1])) 638 | path = dirs[-1] if len(dirs) > 0 else None 639 | 640 | if path is None: 641 | accelerator.print( 642 | f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run." 643 | ) 644 | args.resume_from_checkpoint = None 645 | else: 646 | accelerator.print(f"Resuming from checkpoint {path}") 647 | accelerator.load_state(os.path.join(args.output_dir, path)) 648 | global_step = int(path.split("-")[1]) 649 | 650 | resume_global_step = global_step * args.gradient_accumulation_steps 651 | first_epoch = global_step // num_update_steps_per_epoch 652 | resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps) 653 | 654 | 655 | # Bram Note: This was pretty janky to wrangle to look proper but works to my liking now 656 | progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process) 657 | progress_bar.set_description("Steps") 658 | 659 | 660 | #### START MAIN TRAINING LOOP ##### 661 | for epoch in range(first_epoch, args.num_train_epochs): 662 | unet.train() 663 | unwrap_unet = accelerator.unwrap_model(unet) 664 | for step, batch in enumerate(train_dataloader): 665 | # Skip steps until we reach the resumed step 666 | if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step and (not args.hard_skip_resume): 667 | if step % args.gradient_accumulation_steps == 0: 668 | print(f"Dummy processing step {step}, will start training at {resume_step}") 669 | continue 670 | with accelerator.accumulate(unet): 671 | 672 | feed_pixel_values = torch.cat(batch["pixel_values"].chunk(2, dim=1)) 673 | 674 | with torch.no_grad(): 675 | latents = vae.encode(feed_pixel_values.to(weight_dtype)).latent_dist.sample() 676 | latents = latents * vae.config.scaling_factor 677 | 678 | noise = torch.randn_like(latents) 679 | 680 | bsz = latents.shape[0] 681 | 682 | timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device) 683 | timesteps = timesteps.long() 684 | 685 | timesteps = timesteps.chunk(2)[0].repeat(2) 686 | noise = noise.chunk(2)[0].repeat(2, 1, 1, 1) 687 | 688 | 689 | noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps) 690 | 691 | with torch.no_grad(): 692 | add_time_ids = torch.tensor([args.resolution, 693 | args.resolution, 694 | 0, 695 | 0, 696 | args.resolution, 697 | args.resolution], 698 | dtype=weight_dtype, 699 | device=accelerator.device)[None, :].repeat(timesteps.size(0), 1) 700 | prompt_batch = encode_prompt_sdxl(batch, 701 | text_encoders, 702 | tokenizers, 703 | 0.0, 704 | caption_column='prompt', 705 | is_train=True, 706 | ) 707 | 708 | prompt_batch["prompt_embeds"] = prompt_batch["prompt_embeds"].repeat(2, 1, 1) 709 | prompt_batch["pooled_prompt_embeds"] = prompt_batch["pooled_prompt_embeds"].repeat(2, 1) 710 | unet_added_conditions = {"time_ids": add_time_ids, "text_embeds": prompt_batch["pooled_prompt_embeds"]} 711 | #### END PREP BATCH #### 712 | 713 | assert noise_scheduler.config.prediction_type == "epsilon" 714 | target = noise 715 | 716 | # Make the prediction from the model we're learning 717 | model_batch_args = (noisy_latents, timesteps, prompt_batch["prompt_embeds"]) 718 | 719 | model_batch_args_win = list(_arg.chunk(2)[0] for _arg in model_batch_args) 720 | model_batch_args_lose = list(_arg.chunk(2)[1] for _arg in model_batch_args) 721 | 722 | null_prompt_flag = False 723 | if random.uniform(0, 1) < args.puncond: 724 | null_prompt_flag = True 725 | 726 | if null_prompt_flag: 727 | model_batch_args_lose[-1] = torch.zeros_like(model_batch_args_lose[-1]) 728 | 729 | added_cond_kwargs = unet_added_conditions 730 | 731 | assert added_cond_kwargs is not None 732 | added_cond_kwargs_win = {k : v.chunk(2)[0] for k,v in added_cond_kwargs.items()} 733 | added_cond_kwargs_lose = {k : v.chunk(2)[1] for k,v in added_cond_kwargs.items()} 734 | if null_prompt_flag: 735 | added_cond_kwargs_lose['text_embeds'] = torch.zeros_like(added_cond_kwargs_lose['text_embeds']) 736 | 737 | model_pred_win = unwrap_unet["win"]( 738 | *model_batch_args_win, 739 | added_cond_kwargs = added_cond_kwargs_win 740 | ).sample 741 | 742 | model_pred_lose = unwrap_unet["lose"]( 743 | *model_batch_args_lose, 744 | added_cond_kwargs = added_cond_kwargs_lose 745 | ).sample 746 | 747 | model_losses_w = (model_pred_win - target.chunk(2)[0]).pow(2).mean(dim=[1,2,3]) 748 | model_losses_l = (model_pred_lose - target.chunk(2)[1]).pow(2).mean(dim=[1,2,3]) 749 | 750 | ref_model_batch_args = [torch.cat([win_arg, lose_arg], dim=0) for win_arg, lose_arg in zip(model_batch_args_win, model_batch_args_lose)] 751 | ref_model_added_cond_kwargs = {k : torch.cat([added_cond_kwargs_win[k], added_cond_kwargs_lose[k]], dim=0) for k in added_cond_kwargs} 752 | 753 | ref_pred = ref_unet( 754 | *ref_model_batch_args, 755 | added_cond_kwargs = ref_model_added_cond_kwargs 756 | ).sample.detach() 757 | 758 | ref_losses = (ref_pred - target).pow(2).mean(dim=[1,2,3]) 759 | ref_losses_w, ref_losses_l = ref_losses.chunk(2) 760 | 761 | 762 | win_diff = model_losses_w - ref_losses_w 763 | lose_diff = model_losses_l - ref_losses_l 764 | 765 | scale_term = -1.0 * args.beta_dpo 766 | inside_term = scale_term * (win_diff + lose_diff) 767 | loss = -1 * F.logsigmoid(inside_term).mean() 768 | 769 | 770 | #### for log 771 | win_diff_loss = win_diff.mean() 772 | lose_diff_loss = lose_diff.mean() 773 | total_diff_loss = (win_diff + lose_diff).mean() 774 | raw_model_loss = ((model_losses_w + model_losses_l) / 2.0).mean() 775 | raw_ref_loss = ref_losses.mean() 776 | 777 | 778 | accumulated_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item() 779 | avg_win_diff_loss = accelerator.gather(win_diff_loss.repeat(args.train_batch_size)).mean().item() 780 | avg_lose_diff_loss = accelerator.gather(lose_diff_loss.repeat(args.train_batch_size)).mean().item() 781 | avg_total_diff_loss = accelerator.gather(total_diff_loss.repeat(args.train_batch_size)).mean().item() 782 | avg_raw_model_loss = accelerator.gather(raw_model_loss.repeat(args.train_batch_size)).mean().item() 783 | avg_raw_ref_loss = accelerator.gather(raw_ref_loss.repeat(args.train_batch_size)).mean().item() 784 | 785 | 786 | # Backpropagate 787 | accelerator.backward(loss) 788 | if accelerator.sync_gradients: 789 | if not args.use_adafactor: # Adafactor does itself, maybe could do here to cut down on code 790 | accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm) 791 | optimizer.step() 792 | lr_scheduler.step() 793 | optimizer.zero_grad() 794 | 795 | # Checks if the accelerator has just performed an optimization step, if so do "end of batch" logging 796 | if accelerator.sync_gradients: 797 | progress_bar.update(1) 798 | global_step += 1 799 | 800 | if accelerator.is_main_process or accelerator.distributed_type == DistributedType.DEEPSPEED: 801 | if global_step % args.checkpointing_steps == 0: 802 | 803 | save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}") 804 | try: 805 | accelerator.save_state(save_path) 806 | except FileExistsError as e: 807 | logger.info(e) 808 | logger.info(f"Saved state to {save_path}") 809 | 810 | if torch.distributed.is_initialized(): 811 | torch.distributed.barrier() 812 | 813 | logs = {"accumulated_loss": accumulated_loss, 814 | "lr": lr_scheduler.get_last_lr()[0], 815 | "avg_win_diff_loss " : avg_win_diff_loss, 816 | "avg_lose_diff_loss" : avg_lose_diff_loss, 817 | "avg_total_diff_loss" : avg_total_diff_loss, 818 | "avg_raw_model_loss" : avg_raw_model_loss, 819 | "avg_raw_ref_loss" : avg_raw_ref_loss 820 | } 821 | progress_bar.set_postfix(**logs) 822 | accelerator.log(logs, step=global_step) 823 | 824 | if global_step >= args.max_train_steps: 825 | break 826 | 827 | accelerator.wait_for_everyone() 828 | accelerator.end_training() 829 | 830 | 831 | if __name__ == "__main__": 832 | main() 833 | -------------------------------------------------------------------------------- /train.sh: -------------------------------------------------------------------------------- 1 | 2 | 3 | accelerate launch --config_file=config/ac_ds_8gpu_zero0.yaml train.py \ 4 | --pretrained_model_name_or_path=stabilityai/stable-diffusion-xl-base-1.0 \ 5 | --pretrained_vae_model_name_or_path=madebyollin/sdxl-vae-fp16-fix \ 6 | --resolution=1024 \ 7 | --dataloader_num_workers 16 \ 8 | --train_batch_size=1 \ 9 | --gradient_accumulation_steps=16 \ 10 | --max_train_steps=6000 \ 11 | --learning_rate=3e-09 --scale_lr --lr_scheduler=constant_with_warmup --lr_warmup_steps=100 \ 12 | --mixed_precision=bf16 \ 13 | --allow_tf32 \ 14 | --checkpointing_steps=200 \ 15 | --output_dir=output \ 16 | --resume_from_checkpoint latest \ 17 | --use_adafactor \ 18 | --gradient_checkpointing \ 19 | --dataset_name=data-is-better-together/open-image-preferences-v1-binarized \ --------------------------------------------------------------------------------