AdithyaSK HF Staff commited on
Commit
53e23fa
·
verified ·
1 Parent(s): 991dcfc

Stage Harbor release files 95501-96000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/README.md +339 -0
  2. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/README_sdxl.md +285 -0
  3. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements.txt +8 -0
  4. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements_flax.txt +9 -0
  5. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements_sdxl.txt +8 -0
  6. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/test_text_to_image.py +365 -0
  7. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/test_text_to_image_lora.py +300 -0
  8. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image.py +1169 -0
  9. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_flax.py +620 -0
  10. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_lora.py +1039 -0
  11. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_lora_sdxl.py +1342 -0
  12. tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_sdxl.py +1370 -0
  13. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/README.md +153 -0
  14. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/README_sdxl.md +47 -0
  15. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/requirements.txt +6 -0
  16. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/requirements_flax.txt +8 -0
  17. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/test_textual_inversion.py +152 -0
  18. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/test_textual_inversion_sdxl.py +152 -0
  19. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion.py +1024 -0
  20. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion_flax.py +681 -0
  21. tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion_sdxl.py +1140 -0
  22. tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/README.md +165 -0
  23. tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/requirements.txt +3 -0
  24. tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/test_unconditional.py +130 -0
  25. tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/train_unconditional.py +749 -0
  26. tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/README.md +127 -0
  27. tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/discriminator.py +48 -0
  28. tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/requirements.txt +8 -0
  29. tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/test_vqgan.py +401 -0
  30. tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/train_vqgan.py +1067 -0
  31. tasks/tasksmith-ee553a5e62c1/environment/source/pyproject.toml +32 -0
  32. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/__init__.py +0 -0
  33. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/change_naming_configs_and_checkpoints.py +113 -0
  34. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/conversion_ldm_uncond.py +56 -0
  35. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_ace_step_to_diffusers.py +454 -0
  36. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_amused.py +523 -0
  37. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_anima_to_diffusers.py +316 -0
  38. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_motion_lora_to_diffusers.py +69 -0
  39. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_motion_module_to_diffusers.py +62 -0
  40. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_sparsectrl_to_diffusers.py +83 -0
  41. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_anyflow_to_diffusers.py +160 -0
  42. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_asymmetric_vqgan_to_diffusers.py +184 -0
  43. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_aura_flow_to_diffusers.py +131 -0
  44. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_blipdiffusion_to_diffusers.py +344 -0
  45. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogvideox_to_diffusers.py +346 -0
  46. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview3_to_diffusers.py +242 -0
  47. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview4_to_diffusers.py +254 -0
  48. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview4_to_diffusers_megatron.py +384 -0
  49. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_consistency_decoder.py +1131 -0
  50. tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_consistency_to_diffusers.py +315 -0
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/README.md ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion text-to-image fine-tuning
2
+
3
+ The `train_text_to_image.py` script shows how to fine-tune stable diffusion model on your own dataset.
4
+
5
+ ___Note___:
6
+
7
+ ___This script is experimental. The script fine-tunes the whole model and often times the model overfits and runs into issues like catastrophic forgetting. It's recommended to try different hyperparameters to get the best result on your dataset.___
8
+
9
+
10
+ ## Running locally with PyTorch
11
+ ### Installing the dependencies
12
+
13
+ Before running the scripts, make sure to install the library's training dependencies:
14
+
15
+ **Important**
16
+
17
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
18
+ ```bash
19
+ git clone https://github.com/huggingface/diffusers
20
+ cd diffusers
21
+ pip install .
22
+ ```
23
+
24
+ Then cd in the example folder and run
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ ```
28
+
29
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
30
+
31
+ ```bash
32
+ accelerate config
33
+ ```
34
+
35
+ Note also that we use PEFT library as backend for LoRA training, make sure to have `peft>=0.6.0` installed in your environment.
36
+
37
+ ### Naruto example
38
+
39
+ You need to accept the model license before downloading or using the weights. In this example we'll use model version `v1-4`, so you'll need to visit [its card](https://huggingface.co/CompVis/stable-diffusion-v1-4), read the license and tick the checkbox if you agree.
40
+
41
+ You have to be a registered user in 🤗 Hugging Face Hub, and you'll also need to use an access token for the code to work. For more information on access tokens, please refer to [this section of the documentation](https://huggingface.co/docs/hub/security-tokens).
42
+
43
+ Run the following command to authenticate your token
44
+
45
+ ```bash
46
+ hf auth login
47
+ ```
48
+
49
+ If you have already cloned the repo, then you won't need to go through these steps.
50
+
51
+ <br>
52
+
53
+ #### Hardware
54
+ With `gradient_checkpointing` and `mixed_precision` it should be possible to fine tune the model on a single 24GB GPU. For higher `batch_size` and faster training it's better to use GPUs with >30GB memory.
55
+
56
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
57
+ <!-- accelerate_snippet_start -->
58
+ ```bash
59
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
60
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
61
+
62
+ accelerate launch --mixed_precision="fp16" train_text_to_image.py \
63
+ --pretrained_model_name_or_path=$MODEL_NAME \
64
+ --dataset_name=$DATASET_NAME \
65
+ --use_ema \
66
+ --resolution=512 --center_crop --random_flip \
67
+ --train_batch_size=1 \
68
+ --gradient_accumulation_steps=4 \
69
+ --gradient_checkpointing \
70
+ --max_train_steps=15000 \
71
+ --learning_rate=1e-05 \
72
+ --max_grad_norm=1 \
73
+ --lr_scheduler="constant" --lr_warmup_steps=0 \
74
+ --output_dir="sd-naruto-model"
75
+ ```
76
+ <!-- accelerate_snippet_end -->
77
+
78
+
79
+ To run on your own training files prepare the dataset according to the format required by `datasets`, you can find the instructions for how to do that in this [document](https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder-with-metadata).
80
+ If you wish to use custom loading logic, you should modify the script, we have left pointers for that in the training script.
81
+
82
+ ```bash
83
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
84
+ export TRAIN_DIR="path_to_your_dataset"
85
+
86
+ accelerate launch --mixed_precision="fp16" train_text_to_image.py \
87
+ --pretrained_model_name_or_path=$MODEL_NAME \
88
+ --train_data_dir=$TRAIN_DIR \
89
+ --use_ema \
90
+ --resolution=512 --center_crop --random_flip \
91
+ --train_batch_size=1 \
92
+ --gradient_accumulation_steps=4 \
93
+ --gradient_checkpointing \
94
+ --max_train_steps=15000 \
95
+ --learning_rate=1e-05 \
96
+ --max_grad_norm=1 \
97
+ --lr_scheduler="constant" --lr_warmup_steps=0 \
98
+ --output_dir="sd-naruto-model"
99
+ ```
100
+
101
+
102
+ Once the training is finished the model will be saved in the `output_dir` specified in the command. In this example it's `sd-naruto-model`. To load the fine-tuned model for inference just pass that path to `StableDiffusionPipeline`
103
+
104
+ ```python
105
+ import torch
106
+ from diffusers import StableDiffusionPipeline
107
+
108
+ model_path = "path_to_saved_model"
109
+ pipe = StableDiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
110
+ pipe.to("cuda")
111
+
112
+ image = pipe(prompt="yoda").images[0]
113
+ image.save("yoda-naruto.png")
114
+ ```
115
+
116
+ Checkpoints only save the unet, so to run inference from a checkpoint, just load the unet
117
+
118
+ ```python
119
+ import torch
120
+ from diffusers import StableDiffusionPipeline, UNet2DConditionModel
121
+
122
+ model_path = "path_to_saved_model"
123
+ unet = UNet2DConditionModel.from_pretrained(model_path + "/checkpoint-<N>/unet", torch_dtype=torch.float16)
124
+
125
+ pipe = StableDiffusionPipeline.from_pretrained("<initial model>", unet=unet, torch_dtype=torch.float16)
126
+ pipe.to("cuda")
127
+
128
+ image = pipe(prompt="yoda").images[0]
129
+ image.save("yoda-naruto.png")
130
+ ```
131
+
132
+ #### Training with multiple GPUs
133
+
134
+ `accelerate` allows for seamless multi-GPU training. Follow the instructions [here](https://huggingface.co/docs/accelerate/basic_tutorials/launch)
135
+ for running distributed training with `accelerate`. Here is an example command:
136
+
137
+ ```bash
138
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
139
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
140
+
141
+ accelerate launch --mixed_precision="fp16" --multi_gpu train_text_to_image.py \
142
+ --pretrained_model_name_or_path=$MODEL_NAME \
143
+ --dataset_name=$DATASET_NAME \
144
+ --use_ema \
145
+ --resolution=512 --center_crop --random_flip \
146
+ --train_batch_size=1 \
147
+ --gradient_accumulation_steps=4 \
148
+ --gradient_checkpointing \
149
+ --max_train_steps=15000 \
150
+ --learning_rate=1e-05 \
151
+ --max_grad_norm=1 \
152
+ --lr_scheduler="constant" --lr_warmup_steps=0 \
153
+ --output_dir="sd-naruto-model"
154
+ ```
155
+
156
+
157
+ #### Training with Min-SNR weighting
158
+
159
+ We support training with the Min-SNR weighting strategy proposed in [Efficient Diffusion Training via Min-SNR Weighting Strategy](https://huggingface.co/papers/2303.09556) which helps to achieve faster convergence
160
+ by rebalancing the loss. In order to use it, one needs to set the `--snr_gamma` argument. The recommended
161
+ value when using it is 5.0.
162
+
163
+ You can find [this project on Weights and Biases](https://wandb.ai/sayakpaul/text2image-finetune-minsnr) that compares the loss surfaces of the following setups:
164
+
165
+ * Training without the Min-SNR weighting strategy
166
+ * Training with the Min-SNR weighting strategy (`snr_gamma` set to 5.0)
167
+ * Training with the Min-SNR weighting strategy (`snr_gamma` set to 1.0)
168
+
169
+ For our small Narutos dataset, the effects of Min-SNR weighting strategy might not appear to be pronounced, but for larger datasets, we believe the effects will be more pronounced.
170
+
171
+ Also, note that in this example, we either predict `epsilon` (i.e., the noise) or the `v_prediction`. For both of these cases, the formulation of the Min-SNR weighting strategy that we have used holds.
172
+
173
+
174
+ #### Training with EMA weights
175
+
176
+ Through the `EMAModel` class, we support a convenient method of tracking an exponential moving average of model parameters. This helps to smooth out noise in model parameter updates and generally improves model performance. If enabled with the `--use_ema` argument, the final model checkpoint that is saved at the end of training will use the EMA weights.
177
+
178
+ EMA weights require an additional full-precision copy of the model parameters to be stored in memory, but otherwise have very little performance overhead. `--foreach_ema` can be used to further reduce the overhead. If you are short on VRAM and still want to use EMA weights, you can store them in CPU RAM by using the `--offload_ema` argument. This will keep the EMA weights in pinned CPU memory during the training step. Then, once every model parameter update, it will transfer the EMA weights back to the GPU which can then update the parameters on the GPU, before sending them back to the CPU. Both of these transfers are set up as non-blocking, so CUDA devices should be able to overlap this transfer with other computations. With sufficient bandwidth between the host and device and a sufficiently long gap between model parameter updates, storing EMA weights in CPU RAM should have no additional performance overhead, as long as no other calls force synchronization.
179
+
180
+ #### Training with DREAM
181
+
182
+ We support training epsilon (noise) prediction models using the [DREAM (Diffusion Rectification and Estimation-Adaptive Models) strategy](https://huggingface.co/papers/2312.00210). DREAM claims to increase model fidelity for the performance cost of an extra grad-less unet `forward` step in the training loop. You can turn on DREAM training by using the `--dream_training` argument. The `--dream_detail_preservation` argument controls the detail preservation variable p and is the default of 1 from the paper.
183
+
184
+
185
+
186
+ ## Training with LoRA
187
+
188
+ Low-Rank Adaption of Large Language Models was first introduced by Microsoft in [LoRA: Low-Rank Adaptation of Large Language Models](https://huggingface.co/papers/2106.09685) by *Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen*.
189
+
190
+ In a nutshell, LoRA allows adapting pretrained models by adding pairs of rank-decomposition matrices to existing weights and **only** training those newly added weights. This has a couple of advantages:
191
+
192
+ - Previous pretrained weights are kept frozen so that model is not prone to [catastrophic forgetting](https://www.pnas.org/doi/10.1073/pnas.1611835114).
193
+ - Rank-decomposition matrices have significantly fewer parameters than original model, which means that trained LoRA weights are easily portable.
194
+ - LoRA attention layers allow to control to which extent the model is adapted toward new training images via a `scale` parameter.
195
+
196
+ [cloneofsimo](https://github.com/cloneofsimo) was the first to try out LoRA training for Stable Diffusion in the popular [lora](https://github.com/cloneofsimo/lora) GitHub repository.
197
+
198
+ With LoRA, it's possible to fine-tune Stable Diffusion on a custom image-caption pair dataset
199
+ on consumer GPUs like Tesla T4, Tesla V100.
200
+
201
+ ### Training
202
+
203
+ First, you need to set up your development environment as is explained in the [installation section](#installing-the-dependencies). Make sure to set the `MODEL_NAME` and `DATASET_NAME` environment variables. Here, we will use [Stable Diffusion v1-4](https://hf.co/CompVis/stable-diffusion-v1-4) and the [Narutos dataset](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions).
204
+
205
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
206
+
207
+ **___Note: It is quite useful to monitor the training progress by regularly generating sample images during training. [Weights and Biases](https://docs.wandb.ai/quickstart) is a nice solution to easily see generating images during training. All you need to do is to run `pip install wandb` before training to automatically log images.___**
208
+
209
+ ```bash
210
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
211
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
212
+ ```
213
+
214
+ For this example we want to directly store the trained LoRA embeddings on the Hub, so
215
+ we need to be logged in and add the `--push_to_hub` flag.
216
+
217
+ ```bash
218
+ hf auth login
219
+ ```
220
+
221
+ Now we can start training!
222
+
223
+ ```bash
224
+ accelerate launch --mixed_precision="fp16" train_text_to_image_lora.py \
225
+ --pretrained_model_name_or_path=$MODEL_NAME \
226
+ --dataset_name=$DATASET_NAME --caption_column="text" \
227
+ --resolution=512 --random_flip \
228
+ --train_batch_size=1 \
229
+ --num_train_epochs=100 --checkpointing_steps=5000 \
230
+ --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
231
+ --seed=42 \
232
+ --output_dir="sd-naruto-model-lora" \
233
+ --validation_prompt="cute dragon creature" --report_to="wandb"
234
+ ```
235
+
236
+ The above command will also run inference as fine-tuning progresses and log the results to Weights and Biases.
237
+
238
+ **___Note: When using LoRA we can use a much higher learning rate compared to non-LoRA fine-tuning. Here we use *1e-4* instead of the usual *1e-5*. Also, by using LoRA, it's possible to run `train_text_to_image_lora.py` in consumer GPUs like T4 or V100.___**
239
+
240
+ The final LoRA embedding weights have been uploaded to [sayakpaul/sd-model-finetuned-lora-t4](https://huggingface.co/sayakpaul/sd-model-finetuned-lora-t4). **___Note: [The final weights](https://huggingface.co/sayakpaul/sd-model-finetuned-lora-t4/blob/main/pytorch_lora_weights.bin) are only 3 MB in size, which is orders of magnitudes smaller than the original model.___**
241
+
242
+ You can check some inference samples that were logged during the course of the fine-tuning process [here](https://wandb.ai/sayakpaul/text2image-fine-tune/runs/q4lc0xsw).
243
+
244
+ ### Inference
245
+
246
+ Once you have trained a model using above command, the inference can be done simply using the `StableDiffusionPipeline` after loading the trained LoRA weights. You
247
+ need to pass the `output_dir` for loading the LoRA weights which, in this case, is `sd-naruto-model-lora`.
248
+
249
+ ```python
250
+ from diffusers import StableDiffusionPipeline
251
+ import torch
252
+
253
+ model_path = "sayakpaul/sd-model-finetuned-lora-t4"
254
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
255
+ pipe.unet.load_attn_procs(model_path)
256
+ pipe.to("cuda")
257
+
258
+ prompt = "A naruto with green eyes and red legs."
259
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
260
+ image.save("naruto.png")
261
+ ```
262
+
263
+ If you are loading the LoRA parameters from the Hub and if the Hub repository has
264
+ a `base_model` tag (such as [this](https://huggingface.co/sayakpaul/sd-model-finetuned-lora-t4/blob/main/README.md?code=true#L4)), then
265
+ you can do:
266
+
267
+ ```py
268
+ from huggingface_hub.repocard import RepoCard
269
+
270
+ lora_model_id = "sayakpaul/sd-model-finetuned-lora-t4"
271
+ card = RepoCard.load(lora_model_id)
272
+ base_model_id = card.data.to_dict()["base_model"]
273
+
274
+ pipe = StableDiffusionPipeline.from_pretrained(base_model_id, torch_dtype=torch.float16)
275
+ ...
276
+ ```
277
+
278
+ ## Training with Flax/JAX
279
+
280
+ For faster training on TPUs and GPUs you can leverage the flax training example. Follow the instructions above to get the model and dataset before running the script.
281
+
282
+ **___Note: The flax example doesn't yet support features like gradient checkpoint, gradient accumulation etc, so to use flax for faster training we will need >30GB cards or TPU v3.___**
283
+
284
+
285
+ Before running the scripts, make sure to install the library's training dependencies:
286
+
287
+ ```bash
288
+ pip install -U -r requirements_flax.txt
289
+ ```
290
+
291
+ ```bash
292
+ export MODEL_NAME="duongna/stable-diffusion-v1-4-flax"
293
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
294
+
295
+ python train_text_to_image_flax.py \
296
+ --pretrained_model_name_or_path=$MODEL_NAME \
297
+ --dataset_name=$DATASET_NAME \
298
+ --resolution=512 --center_crop --random_flip \
299
+ --train_batch_size=1 \
300
+ --mixed_precision="fp16" \
301
+ --max_train_steps=15000 \
302
+ --learning_rate=1e-05 \
303
+ --max_grad_norm=1 \
304
+ --output_dir="sd-naruto-model"
305
+ ```
306
+
307
+ To run on your own training files prepare the dataset according to the format required by `datasets`, you can find the instructions for how to do that in this [document](https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder-with-metadata).
308
+ If you wish to use custom loading logic, you should modify the script, we have left pointers for that in the training script.
309
+
310
+ ```bash
311
+ export MODEL_NAME="duongna/stable-diffusion-v1-4-flax"
312
+ export TRAIN_DIR="path_to_your_dataset"
313
+
314
+ python train_text_to_image_flax.py \
315
+ --pretrained_model_name_or_path=$MODEL_NAME \
316
+ --train_data_dir=$TRAIN_DIR \
317
+ --resolution=512 --center_crop --random_flip \
318
+ --train_batch_size=1 \
319
+ --mixed_precision="fp16" \
320
+ --max_train_steps=15000 \
321
+ --learning_rate=1e-05 \
322
+ --max_grad_norm=1 \
323
+ --output_dir="sd-naruto-model"
324
+ ```
325
+
326
+ ### Training with xFormers:
327
+
328
+ You can enable memory efficient attention by [installing xFormers](https://huggingface.co/docs/diffusers/main/en/optimization/xformers) and passing the `--enable_xformers_memory_efficient_attention` argument to the script.
329
+
330
+ xFormers training is not available for Flax/JAX.
331
+
332
+ **Note**:
333
+
334
+ According to [this issue](https://github.com/huggingface/diffusers/issues/2234#issuecomment-1416931212), xFormers `v0.0.16` cannot be used for training in some GPUs. If you observe that problem, please install a development version as indicated in that comment.
335
+
336
+ ## Stable Diffusion XL
337
+
338
+ * We support fine-tuning the UNet shipped in [Stable Diffusion XL](https://huggingface.co/papers/2307.01952) via the `train_text_to_image_sdxl.py` script. Please refer to the docs [here](./README_sdxl.md).
339
+ * We also support fine-tuning of the UNet and Text Encoder shipped in [Stable Diffusion XL](https://huggingface.co/papers/2307.01952) with LoRA via the `train_text_to_image_lora_sdxl.py` script. Please refer to the docs [here](./README_sdxl.md).
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/README_sdxl.md ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion XL text-to-image fine-tuning
2
+
3
+ The `train_text_to_image_sdxl.py` script shows how to fine-tune Stable Diffusion XL (SDXL) on your own dataset.
4
+
5
+ 🚨 This script is experimental. The script fine-tunes the whole model and often times the model overfits and runs into issues like catastrophic forgetting. It's recommended to try different hyperparameters to get the best result on your dataset. 🚨
6
+
7
+ ## Running locally with PyTorch
8
+
9
+ ### Installing the dependencies
10
+
11
+ Before running the scripts, make sure to install the library's training dependencies:
12
+
13
+ **Important**
14
+
15
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
16
+
17
+ ```bash
18
+ git clone https://github.com/huggingface/diffusers
19
+ cd diffusers
20
+ pip install -e .
21
+ ```
22
+
23
+ Then cd in the `examples/text_to_image` folder and run
24
+ ```bash
25
+ pip install -r requirements_sdxl.txt
26
+ ```
27
+
28
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
29
+
30
+ ```bash
31
+ accelerate config
32
+ ```
33
+
34
+ Or for a default accelerate configuration without answering questions about your environment
35
+
36
+ ```bash
37
+ accelerate config default
38
+ ```
39
+
40
+ Or if your environment doesn't support an interactive shell (e.g., a notebook)
41
+
42
+ ```python
43
+ from accelerate.utils import write_basic_config
44
+ write_basic_config()
45
+ ```
46
+
47
+ When running `accelerate config`, if we specify torch compile mode to True there can be dramatic speedups.
48
+ Note also that we use PEFT library as backend for LoRA training, make sure to have `peft>=0.6.0` installed in your environment.
49
+
50
+ ### Training
51
+
52
+ ```bash
53
+ export MODEL_NAME="stabilityai/stable-diffusion-xl-base-1.0"
54
+ export VAE_NAME="madebyollin/sdxl-vae-fp16-fix"
55
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
56
+
57
+ accelerate launch train_text_to_image_sdxl.py \
58
+ --pretrained_model_name_or_path=$MODEL_NAME \
59
+ --pretrained_vae_model_name_or_path=$VAE_NAME \
60
+ --dataset_name=$DATASET_NAME \
61
+ --enable_xformers_memory_efficient_attention \
62
+ --resolution=512 --center_crop --random_flip \
63
+ --proportion_empty_prompts=0.2 \
64
+ --train_batch_size=1 \
65
+ --gradient_accumulation_steps=4 --gradient_checkpointing \
66
+ --max_train_steps=10000 \
67
+ --use_8bit_adam \
68
+ --learning_rate=1e-06 --lr_scheduler="constant" --lr_warmup_steps=0 \
69
+ --mixed_precision="fp16" \
70
+ --report_to="wandb" \
71
+ --validation_prompt="a cute Sundar Pichai creature" --validation_epochs 5 \
72
+ --checkpointing_steps=5000 \
73
+ --output_dir="sdxl-naruto-model" \
74
+ --push_to_hub
75
+ ```
76
+
77
+ **Notes**:
78
+
79
+ * The `train_text_to_image_sdxl.py` script pre-computes text embeddings and the VAE encodings and keeps them in memory. While for smaller datasets like [`lambdalabs/naruto-blip-captions`](https://hf.co/datasets/lambdalabs/naruto-blip-captions), it might not be a problem, it can definitely lead to memory problems when the script is used on a larger dataset. For those purposes, you would want to serialize these pre-computed representations to disk separately and load them during the fine-tuning process. Refer to [this PR](https://github.com/huggingface/diffusers/pull/4505) for a more in-depth discussion.
80
+ * The training script is compute-intensive and may not run on a consumer GPU like Tesla T4.
81
+ * The training command shown above performs intermediate quality validation in between the training epochs and logs the results to Weights and Biases. `--report_to`, `--validation_prompt`, and `--validation_epochs` are the relevant CLI arguments here.
82
+ * SDXL's VAE is known to suffer from numerical instability issues. This is why we also expose a CLI argument namely `--pretrained_vae_model_name_or_path` that lets you specify the location of a better VAE (such as [this one](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)).
83
+
84
+ ### Inference
85
+
86
+ ```python
87
+ from diffusers import DiffusionPipeline
88
+ import torch
89
+
90
+ model_path = "you-model-id-goes-here" # <-- change this
91
+ pipe = DiffusionPipeline.from_pretrained(model_path, torch_dtype=torch.float16)
92
+ pipe.to("cuda")
93
+
94
+ prompt = "A naruto with green eyes and red legs."
95
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
96
+ image.save("naruto.png")
97
+ ```
98
+
99
+ ### Inference in Pytorch XLA
100
+ ```python
101
+ from diffusers import DiffusionPipeline
102
+ import torch
103
+ import torch_xla.core.xla_model as xm
104
+
105
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
106
+ pipe = DiffusionPipeline.from_pretrained(model_id)
107
+
108
+ device = xm.xla_device()
109
+ pipe.to(device)
110
+
111
+ prompt = "A naruto with green eyes and red legs."
112
+ start = time()
113
+ image = pipe(prompt, num_inference_steps=inference_steps).images[0]
114
+ print(f'Compilation time is {time()-start} sec')
115
+ image.save("naruto.png")
116
+
117
+ start = time()
118
+ image = pipe(prompt, num_inference_steps=inference_steps).images[0]
119
+ print(f'Inference time is {time()-start} sec after compilation')
120
+ ```
121
+
122
+ Note: There is a warmup step in PyTorch XLA. This takes longer because of
123
+ compilation and optimization. To see the real benefits of Pytorch XLA and
124
+ speedup, we need to call the pipe again on the input with the same length
125
+ as the original prompt to reuse the optimized graph and get the performance
126
+ boost.
127
+
128
+ ## LoRA training example for Stable Diffusion XL (SDXL)
129
+
130
+ Low-Rank Adaption of Large Language Models was first introduced by Microsoft in [LoRA: Low-Rank Adaptation of Large Language Models](https://huggingface.co/papers/2106.09685) by *Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen*.
131
+
132
+ In a nutshell, LoRA allows adapting pretrained models by adding pairs of rank-decomposition matrices to existing weights and **only** training those newly added weights. This has a couple of advantages:
133
+
134
+ - Previous pretrained weights are kept frozen so that model is not prone to [catastrophic forgetting](https://www.pnas.org/doi/10.1073/pnas.1611835114).
135
+ - Rank-decomposition matrices have significantly fewer parameters than original model, which means that trained LoRA weights are easily portable.
136
+ - LoRA attention layers allow to control to which extent the model is adapted toward new training images via a `scale` parameter.
137
+
138
+ [cloneofsimo](https://github.com/cloneofsimo) was the first to try out LoRA training for Stable Diffusion in the popular [lora](https://github.com/cloneofsimo/lora) GitHub repository.
139
+
140
+ With LoRA, it's possible to fine-tune Stable Diffusion on a custom image-caption pair dataset
141
+ on consumer GPUs like Tesla T4, Tesla V100.
142
+
143
+ ### Training
144
+
145
+ First, you need to set up your development environment as is explained in the [installation section](#installing-the-dependencies). Make sure to set the `MODEL_NAME` and `DATASET_NAME` environment variables and, optionally, the `VAE_NAME` variable. Here, we will use [Stable Diffusion XL 1.0-base](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) and the [Narutos dataset](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions).
146
+
147
+ **___Note: It is quite useful to monitor the training progress by regularly generating sample images during training. [Weights and Biases](https://docs.wandb.ai/quickstart) is a nice solution to easily see generating images during training. All you need to do is to run `pip install wandb` before training to automatically log images.___**
148
+
149
+ ```bash
150
+ export MODEL_NAME="stabilityai/stable-diffusion-xl-base-1.0"
151
+ export VAE_NAME="madebyollin/sdxl-vae-fp16-fix"
152
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
153
+ ```
154
+
155
+ For this example we want to directly store the trained LoRA embeddings on the Hub, so
156
+ we need to be logged in and add the `--push_to_hub` flag.
157
+
158
+ ```bash
159
+ hf auth login
160
+ ```
161
+
162
+ Now we can start training!
163
+
164
+ ```bash
165
+ accelerate launch train_text_to_image_lora_sdxl.py \
166
+ --pretrained_model_name_or_path=$MODEL_NAME \
167
+ --pretrained_vae_model_name_or_path=$VAE_NAME \
168
+ --dataset_name=$DATASET_NAME --caption_column="text" \
169
+ --resolution=1024 --random_flip \
170
+ --train_batch_size=1 \
171
+ --num_train_epochs=2 --checkpointing_steps=500 \
172
+ --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
173
+ --mixed_precision="fp16" \
174
+ --seed=42 \
175
+ --output_dir="sd-naruto-model-lora-sdxl" \
176
+ --validation_prompt="cute dragon creature" --report_to="wandb" \
177
+ --push_to_hub
178
+ ```
179
+
180
+ The above command will also run inference as fine-tuning progresses and log the results to Weights and Biases.
181
+
182
+ **Notes**:
183
+
184
+ * SDXL's VAE is known to suffer from numerical instability issues. This is why we also expose a CLI argument namely `--pretrained_vae_model_name_or_path` that lets you specify the location of a better VAE (such as [this one](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)).
185
+
186
+
187
+ ### Using DeepSpeed
188
+ Using DeepSpeed one can reduce the consumption of GPU memory, enabling the training of models on GPUs with smaller memory sizes. DeepSpeed is capable of offloading model parameters to the machine's memory, or it can distribute parameters, gradients, and optimizer states across multiple GPUs. This allows for the training of larger models under the same hardware configuration.
189
+
190
+ First, you need to use the `accelerate config` command to choose to use DeepSpeed, or manually use the accelerate config file to set up DeepSpeed.
191
+
192
+ Here is an example of a config file for using DeepSpeed. For more detailed explanations of the configuration, you can refer to this [link](https://huggingface.co/docs/accelerate/usage_guides/deepspeed).
193
+ ```yaml
194
+ compute_environment: LOCAL_MACHINE
195
+ debug: true
196
+ deepspeed_config:
197
+ gradient_accumulation_steps: 1
198
+ gradient_clipping: 1.0
199
+ offload_optimizer_device: none
200
+ offload_param_device: none
201
+ zero3_init_flag: false
202
+ zero_stage: 2
203
+ distributed_type: DEEPSPEED
204
+ downcast_bf16: 'no'
205
+ machine_rank: 0
206
+ main_training_function: main
207
+ mixed_precision: fp16
208
+ num_machines: 1
209
+ num_processes: 1
210
+ rdzv_backend: static
211
+ same_network: true
212
+ tpu_env: []
213
+ tpu_use_cluster: false
214
+ tpu_use_sudo: false
215
+ use_cpu: false
216
+ ```
217
+ You need to save the mentioned configuration as an `accelerate_config.yaml` file. Then, you need to input the path of your `accelerate_config.yaml` file into the `ACCELERATE_CONFIG_FILE` parameter. This way you can use DeepSpeed to train your SDXL model in LoRA. Additionally, you can use DeepSpeed to train other SD models in this way.
218
+
219
+ ```shell
220
+ export MODEL_NAME="stabilityai/stable-diffusion-xl-base-1.0"
221
+ export VAE_NAME="madebyollin/sdxl-vae-fp16-fix"
222
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
223
+ export ACCELERATE_CONFIG_FILE="your accelerate_config.yaml"
224
+
225
+ accelerate launch --config_file $ACCELERATE_CONFIG_FILE train_text_to_image_lora_sdxl.py \
226
+ --pretrained_model_name_or_path=$MODEL_NAME \
227
+ --pretrained_vae_model_name_or_path=$VAE_NAME \
228
+ --dataset_name=$DATASET_NAME --caption_column="text" \
229
+ --resolution=1024 \
230
+ --train_batch_size=1 \
231
+ --num_train_epochs=2 \
232
+ --checkpointing_steps=2 \
233
+ --learning_rate=1e-04 \
234
+ --lr_scheduler="constant" \
235
+ --lr_warmup_steps=0 \
236
+ --mixed_precision="fp16" \
237
+ --max_train_steps=20 \
238
+ --validation_epochs=20 \
239
+ --seed=1234 \
240
+ --output_dir="sd-naruto-model-lora-sdxl" \
241
+ --validation_prompt="cute dragon creature"
242
+ ```
243
+
244
+
245
+ ### Finetuning the text encoder and UNet
246
+
247
+ The script also allows you to finetune the `text_encoder` along with the `unet`.
248
+
249
+ 🚨 Training the text encoder requires additional memory.
250
+
251
+ Pass the `--train_text_encoder` argument to the training script to enable finetuning the `text_encoder` and `unet`:
252
+
253
+ ```bash
254
+ accelerate launch train_text_to_image_lora_sdxl.py \
255
+ --pretrained_model_name_or_path=$MODEL_NAME \
256
+ --dataset_name=$DATASET_NAME --caption_column="text" \
257
+ --resolution=1024 --random_flip \
258
+ --train_batch_size=1 \
259
+ --num_train_epochs=2 --checkpointing_steps=500 \
260
+ --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
261
+ --seed=42 \
262
+ --output_dir="sd-naruto-model-lora-sdxl-txt" \
263
+ --train_text_encoder \
264
+ --validation_prompt="cute dragon creature" --report_to="wandb" \
265
+ --push_to_hub
266
+ ```
267
+
268
+ ### Inference
269
+
270
+ Once you have trained a model using above command, the inference can be done simply using the `DiffusionPipeline` after loading the trained LoRA weights. You
271
+ need to pass the `output_dir` for loading the LoRA weights which, in this case, is `sd-naruto-model-lora-sdxl`.
272
+
273
+ ```python
274
+ from diffusers import DiffusionPipeline
275
+ import torch
276
+
277
+ model_path = "takuoko/sd-naruto-model-lora-sdxl"
278
+ pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16)
279
+ pipe.to("cuda")
280
+ pipe.load_lora_weights(model_path)
281
+
282
+ prompt = "A naruto with green eyes and red legs."
283
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
284
+ image.save("naruto.png")
285
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ datasets>=2.19.1
5
+ ftfy
6
+ tensorboard
7
+ Jinja2
8
+ peft>=0.17.0
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements_flax.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ transformers>=4.25.1
2
+ datasets
3
+ flax
4
+ optax
5
+ torch
6
+ torchvision
7
+ ftfy
8
+ tensorboard
9
+ Jinja2
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/requirements_sdxl.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.22.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ ftfy
5
+ tensorboard
6
+ Jinja2
7
+ datasets
8
+ peft>=0.17.0
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/test_text_to_image.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
18
+ import os
19
+ import shutil
20
+ import sys
21
+ import tempfile
22
+
23
+ from diffusers import DiffusionPipeline, UNet2DConditionModel # noqa: E402
24
+
25
+
26
+ sys.path.append("..")
27
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
28
+
29
+
30
+ logging.basicConfig(level=logging.DEBUG)
31
+
32
+ logger = logging.getLogger()
33
+ stream_handler = logging.StreamHandler(sys.stdout)
34
+ logger.addHandler(stream_handler)
35
+
36
+
37
+ class TextToImage(ExamplesTestsAccelerate):
38
+ def test_text_to_image(self):
39
+ with tempfile.TemporaryDirectory() as tmpdir:
40
+ test_args = f"""
41
+ examples/text_to_image/train_text_to_image.py
42
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-pipe
43
+ --dataset_name hf-internal-testing/dummy_image_text_data
44
+ --resolution 64
45
+ --center_crop
46
+ --random_flip
47
+ --train_batch_size 1
48
+ --gradient_accumulation_steps 1
49
+ --max_train_steps 2
50
+ --learning_rate 5.0e-04
51
+ --scale_lr
52
+ --lr_scheduler constant
53
+ --lr_warmup_steps 0
54
+ --output_dir {tmpdir}
55
+ """.split()
56
+
57
+ run_command(self._launch_args + test_args)
58
+ # save_pretrained smoke test
59
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "unet", "diffusion_pytorch_model.safetensors")))
60
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "scheduler", "scheduler_config.json")))
61
+
62
+ def test_text_to_image_checkpointing(self):
63
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
64
+ prompt = "a prompt"
65
+
66
+ with tempfile.TemporaryDirectory() as tmpdir:
67
+ # Run training script with checkpointing
68
+ # max_train_steps == 4, checkpointing_steps == 2
69
+ # Should create checkpoints at steps 2, 4
70
+
71
+ initial_run_args = f"""
72
+ examples/text_to_image/train_text_to_image.py
73
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
74
+ --dataset_name hf-internal-testing/dummy_image_text_data
75
+ --resolution 64
76
+ --center_crop
77
+ --random_flip
78
+ --train_batch_size 1
79
+ --gradient_accumulation_steps 1
80
+ --max_train_steps 4
81
+ --learning_rate 5.0e-04
82
+ --scale_lr
83
+ --lr_scheduler constant
84
+ --lr_warmup_steps 0
85
+ --output_dir {tmpdir}
86
+ --checkpointing_steps=2
87
+ --seed=0
88
+ """.split()
89
+
90
+ run_command(self._launch_args + initial_run_args)
91
+
92
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
93
+ pipe(prompt, num_inference_steps=1)
94
+
95
+ # check checkpoint directories exist
96
+ self.assertEqual(
97
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
98
+ {"checkpoint-2", "checkpoint-4"},
99
+ )
100
+
101
+ # check can run an intermediate checkpoint
102
+ unet = UNet2DConditionModel.from_pretrained(tmpdir, subfolder="checkpoint-2/unet")
103
+ pipe = DiffusionPipeline.from_pretrained(pretrained_model_name_or_path, unet=unet, safety_checker=None)
104
+ pipe(prompt, num_inference_steps=1)
105
+
106
+ # Remove checkpoint 2 so that we can check only later checkpoints exist after resuming
107
+ shutil.rmtree(os.path.join(tmpdir, "checkpoint-2"))
108
+
109
+ # Run training script for 2 total steps resuming from checkpoint 4
110
+
111
+ resume_run_args = f"""
112
+ examples/text_to_image/train_text_to_image.py
113
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
114
+ --dataset_name hf-internal-testing/dummy_image_text_data
115
+ --resolution 64
116
+ --center_crop
117
+ --random_flip
118
+ --train_batch_size 1
119
+ --gradient_accumulation_steps 1
120
+ --max_train_steps 2
121
+ --learning_rate 5.0e-04
122
+ --scale_lr
123
+ --lr_scheduler constant
124
+ --lr_warmup_steps 0
125
+ --output_dir {tmpdir}
126
+ --checkpointing_steps=1
127
+ --resume_from_checkpoint=checkpoint-4
128
+ --seed=0
129
+ """.split()
130
+
131
+ run_command(self._launch_args + resume_run_args)
132
+
133
+ # check can run new fully trained pipeline
134
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
135
+ pipe(prompt, num_inference_steps=1)
136
+
137
+ # no checkpoint-2 -> check old checkpoints do not exist
138
+ # check new checkpoints exist
139
+ self.assertEqual(
140
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
141
+ {"checkpoint-4", "checkpoint-5"},
142
+ )
143
+
144
+ def test_text_to_image_checkpointing_use_ema(self):
145
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
146
+ prompt = "a prompt"
147
+
148
+ with tempfile.TemporaryDirectory() as tmpdir:
149
+ # Run training script with checkpointing
150
+ # max_train_steps == 4, checkpointing_steps == 2
151
+ # Should create checkpoints at steps 2, 4
152
+
153
+ initial_run_args = f"""
154
+ examples/text_to_image/train_text_to_image.py
155
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
156
+ --dataset_name hf-internal-testing/dummy_image_text_data
157
+ --resolution 64
158
+ --center_crop
159
+ --random_flip
160
+ --train_batch_size 1
161
+ --gradient_accumulation_steps 1
162
+ --max_train_steps 4
163
+ --learning_rate 5.0e-04
164
+ --scale_lr
165
+ --lr_scheduler constant
166
+ --lr_warmup_steps 0
167
+ --output_dir {tmpdir}
168
+ --checkpointing_steps=2
169
+ --use_ema
170
+ --seed=0
171
+ """.split()
172
+
173
+ run_command(self._launch_args + initial_run_args)
174
+
175
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
176
+ pipe(prompt, num_inference_steps=2)
177
+
178
+ # check checkpoint directories exist
179
+ self.assertEqual(
180
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
181
+ {"checkpoint-2", "checkpoint-4"},
182
+ )
183
+
184
+ # check can run an intermediate checkpoint
185
+ unet = UNet2DConditionModel.from_pretrained(tmpdir, subfolder="checkpoint-2/unet")
186
+ pipe = DiffusionPipeline.from_pretrained(pretrained_model_name_or_path, unet=unet, safety_checker=None)
187
+ pipe(prompt, num_inference_steps=1)
188
+
189
+ # Remove checkpoint 2 so that we can check only later checkpoints exist after resuming
190
+ shutil.rmtree(os.path.join(tmpdir, "checkpoint-2"))
191
+
192
+ # Run training script for 2 total steps resuming from checkpoint 4
193
+
194
+ resume_run_args = f"""
195
+ examples/text_to_image/train_text_to_image.py
196
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
197
+ --dataset_name hf-internal-testing/dummy_image_text_data
198
+ --resolution 64
199
+ --center_crop
200
+ --random_flip
201
+ --train_batch_size 1
202
+ --gradient_accumulation_steps 1
203
+ --max_train_steps 2
204
+ --learning_rate 5.0e-04
205
+ --scale_lr
206
+ --lr_scheduler constant
207
+ --lr_warmup_steps 0
208
+ --output_dir {tmpdir}
209
+ --checkpointing_steps=1
210
+ --resume_from_checkpoint=checkpoint-4
211
+ --use_ema
212
+ --seed=0
213
+ """.split()
214
+
215
+ run_command(self._launch_args + resume_run_args)
216
+
217
+ # check can run new fully trained pipeline
218
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
219
+ pipe(prompt, num_inference_steps=1)
220
+
221
+ # no checkpoint-2 -> check old checkpoints do not exist
222
+ # check new checkpoints exist
223
+ self.assertEqual(
224
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
225
+ {"checkpoint-4", "checkpoint-5"},
226
+ )
227
+
228
+ def test_text_to_image_checkpointing_checkpoints_total_limit(self):
229
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
230
+ prompt = "a prompt"
231
+
232
+ with tempfile.TemporaryDirectory() as tmpdir:
233
+ # Run training script with checkpointing
234
+ # max_train_steps == 6, checkpointing_steps == 2, checkpoints_total_limit == 2
235
+ # Should create checkpoints at steps 2, 4, 6
236
+ # with checkpoint at step 2 deleted
237
+
238
+ initial_run_args = f"""
239
+ examples/text_to_image/train_text_to_image.py
240
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
241
+ --dataset_name hf-internal-testing/dummy_image_text_data
242
+ --resolution 64
243
+ --center_crop
244
+ --random_flip
245
+ --train_batch_size 1
246
+ --gradient_accumulation_steps 1
247
+ --max_train_steps 6
248
+ --learning_rate 5.0e-04
249
+ --scale_lr
250
+ --lr_scheduler constant
251
+ --lr_warmup_steps 0
252
+ --output_dir {tmpdir}
253
+ --checkpointing_steps=2
254
+ --checkpoints_total_limit=2
255
+ --seed=0
256
+ """.split()
257
+
258
+ run_command(self._launch_args + initial_run_args)
259
+
260
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
261
+ pipe(prompt, num_inference_steps=1)
262
+
263
+ # check checkpoint directories exist
264
+ # checkpoint-2 should have been deleted
265
+ self.assertEqual({x for x in os.listdir(tmpdir) if "checkpoint" in x}, {"checkpoint-4", "checkpoint-6"})
266
+
267
+ def test_text_to_image_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
268
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
269
+ prompt = "a prompt"
270
+
271
+ with tempfile.TemporaryDirectory() as tmpdir:
272
+ # Run training script with checkpointing
273
+ # max_train_steps == 4, checkpointing_steps == 2
274
+ # Should create checkpoints at steps 2, 4
275
+
276
+ initial_run_args = f"""
277
+ examples/text_to_image/train_text_to_image.py
278
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
279
+ --dataset_name hf-internal-testing/dummy_image_text_data
280
+ --resolution 64
281
+ --center_crop
282
+ --random_flip
283
+ --train_batch_size 1
284
+ --gradient_accumulation_steps 1
285
+ --max_train_steps 4
286
+ --learning_rate 5.0e-04
287
+ --scale_lr
288
+ --lr_scheduler constant
289
+ --lr_warmup_steps 0
290
+ --output_dir {tmpdir}
291
+ --checkpointing_steps=2
292
+ --seed=0
293
+ """.split()
294
+
295
+ run_command(self._launch_args + initial_run_args)
296
+
297
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
298
+ pipe(prompt, num_inference_steps=1)
299
+
300
+ # check checkpoint directories exist
301
+ self.assertEqual(
302
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
303
+ {"checkpoint-2", "checkpoint-4"},
304
+ )
305
+
306
+ # resume and we should try to checkpoint at 6, where we'll have to remove
307
+ # checkpoint-2 and checkpoint-4 instead of just a single previous checkpoint
308
+
309
+ resume_run_args = f"""
310
+ examples/text_to_image/train_text_to_image.py
311
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
312
+ --dataset_name hf-internal-testing/dummy_image_text_data
313
+ --resolution 64
314
+ --center_crop
315
+ --random_flip
316
+ --train_batch_size 1
317
+ --gradient_accumulation_steps 1
318
+ --max_train_steps 8
319
+ --learning_rate 5.0e-04
320
+ --scale_lr
321
+ --lr_scheduler constant
322
+ --lr_warmup_steps 0
323
+ --output_dir {tmpdir}
324
+ --checkpointing_steps=2
325
+ --resume_from_checkpoint=checkpoint-4
326
+ --checkpoints_total_limit=2
327
+ --seed=0
328
+ """.split()
329
+
330
+ run_command(self._launch_args + resume_run_args)
331
+
332
+ pipe = DiffusionPipeline.from_pretrained(tmpdir, safety_checker=None)
333
+ pipe(prompt, num_inference_steps=1)
334
+
335
+ # check checkpoint directories exist
336
+ self.assertEqual(
337
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
338
+ {"checkpoint-6", "checkpoint-8"},
339
+ )
340
+
341
+
342
+ class TextToImageSDXL(ExamplesTestsAccelerate):
343
+ def test_text_to_image_sdxl(self):
344
+ with tempfile.TemporaryDirectory() as tmpdir:
345
+ test_args = f"""
346
+ examples/text_to_image/train_text_to_image_sdxl.py
347
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-xl-pipe
348
+ --dataset_name hf-internal-testing/dummy_image_text_data
349
+ --resolution 64
350
+ --center_crop
351
+ --random_flip
352
+ --train_batch_size 1
353
+ --gradient_accumulation_steps 1
354
+ --max_train_steps 2
355
+ --learning_rate 5.0e-04
356
+ --scale_lr
357
+ --lr_scheduler constant
358
+ --lr_warmup_steps 0
359
+ --output_dir {tmpdir}
360
+ """.split()
361
+
362
+ run_command(self._launch_args + test_args)
363
+ # save_pretrained smoke test
364
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "unet", "diffusion_pytorch_model.safetensors")))
365
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "scheduler", "scheduler_config.json")))
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/test_text_to_image_lora.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
18
+ import os
19
+ import sys
20
+ import tempfile
21
+
22
+ import safetensors
23
+
24
+ from diffusers import DiffusionPipeline # noqa: E402
25
+
26
+
27
+ sys.path.append("..")
28
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
29
+
30
+
31
+ logging.basicConfig(level=logging.DEBUG)
32
+
33
+ logger = logging.getLogger()
34
+ stream_handler = logging.StreamHandler(sys.stdout)
35
+ logger.addHandler(stream_handler)
36
+
37
+
38
+ class TextToImageLoRA(ExamplesTestsAccelerate):
39
+ def test_text_to_image_lora_sdxl_checkpointing_checkpoints_total_limit(self):
40
+ prompt = "a prompt"
41
+ pipeline_path = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
42
+
43
+ with tempfile.TemporaryDirectory() as tmpdir:
44
+ # Run training script with checkpointing
45
+ # max_train_steps == 6, checkpointing_steps == 2, checkpoints_total_limit == 2
46
+ # Should create checkpoints at steps 2, 4, 6
47
+ # with checkpoint at step 2 deleted
48
+
49
+ initial_run_args = f"""
50
+ examples/text_to_image/train_text_to_image_lora_sdxl.py
51
+ --pretrained_model_name_or_path {pipeline_path}
52
+ --dataset_name hf-internal-testing/dummy_image_text_data
53
+ --resolution 64
54
+ --train_batch_size 1
55
+ --gradient_accumulation_steps 1
56
+ --max_train_steps 6
57
+ --learning_rate 5.0e-04
58
+ --scale_lr
59
+ --lr_scheduler constant
60
+ --lr_warmup_steps 0
61
+ --output_dir {tmpdir}
62
+ --checkpointing_steps=2
63
+ --checkpoints_total_limit=2
64
+ """.split()
65
+
66
+ run_command(self._launch_args + initial_run_args)
67
+
68
+ pipe = DiffusionPipeline.from_pretrained(pipeline_path)
69
+ pipe.load_lora_weights(tmpdir)
70
+ pipe(prompt, num_inference_steps=1)
71
+
72
+ # check checkpoint directories exist
73
+ # checkpoint-2 should have been deleted
74
+ self.assertEqual({x for x in os.listdir(tmpdir) if "checkpoint" in x}, {"checkpoint-4", "checkpoint-6"})
75
+
76
+ def test_text_to_image_lora_checkpointing_checkpoints_total_limit(self):
77
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
78
+ prompt = "a prompt"
79
+
80
+ with tempfile.TemporaryDirectory() as tmpdir:
81
+ # Run training script with checkpointing
82
+ # max_train_steps == 6, checkpointing_steps == 2, checkpoints_total_limit == 2
83
+ # Should create checkpoints at steps 2, 4, 6
84
+ # with checkpoint at step 2 deleted
85
+
86
+ initial_run_args = f"""
87
+ examples/text_to_image/train_text_to_image_lora.py
88
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
89
+ --dataset_name hf-internal-testing/dummy_image_text_data
90
+ --resolution 64
91
+ --center_crop
92
+ --random_flip
93
+ --train_batch_size 1
94
+ --gradient_accumulation_steps 1
95
+ --max_train_steps 6
96
+ --learning_rate 5.0e-04
97
+ --scale_lr
98
+ --lr_scheduler constant
99
+ --lr_warmup_steps 0
100
+ --output_dir {tmpdir}
101
+ --checkpointing_steps=2
102
+ --checkpoints_total_limit=2
103
+ --seed=0
104
+ --num_validation_images=0
105
+ """.split()
106
+
107
+ run_command(self._launch_args + initial_run_args)
108
+
109
+ pipe = DiffusionPipeline.from_pretrained(
110
+ "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=None
111
+ )
112
+ pipe.load_lora_weights(tmpdir)
113
+ pipe(prompt, num_inference_steps=1)
114
+
115
+ # check checkpoint directories exist
116
+ # checkpoint-2 should have been deleted
117
+ self.assertEqual({x for x in os.listdir(tmpdir) if "checkpoint" in x}, {"checkpoint-4", "checkpoint-6"})
118
+
119
+ def test_text_to_image_lora_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
120
+ pretrained_model_name_or_path = "hf-internal-testing/tiny-stable-diffusion-pipe"
121
+ prompt = "a prompt"
122
+
123
+ with tempfile.TemporaryDirectory() as tmpdir:
124
+ # Run training script with checkpointing
125
+ # max_train_steps == 4, checkpointing_steps == 2
126
+ # Should create checkpoints at steps 2, 4
127
+
128
+ initial_run_args = f"""
129
+ examples/text_to_image/train_text_to_image_lora.py
130
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
131
+ --dataset_name hf-internal-testing/dummy_image_text_data
132
+ --resolution 64
133
+ --center_crop
134
+ --random_flip
135
+ --train_batch_size 1
136
+ --gradient_accumulation_steps 1
137
+ --max_train_steps 4
138
+ --learning_rate 5.0e-04
139
+ --scale_lr
140
+ --lr_scheduler constant
141
+ --lr_warmup_steps 0
142
+ --output_dir {tmpdir}
143
+ --checkpointing_steps=2
144
+ --seed=0
145
+ --num_validation_images=0
146
+ """.split()
147
+
148
+ run_command(self._launch_args + initial_run_args)
149
+
150
+ pipe = DiffusionPipeline.from_pretrained(
151
+ "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=None
152
+ )
153
+ pipe.load_lora_weights(tmpdir)
154
+ pipe(prompt, num_inference_steps=1)
155
+
156
+ # check checkpoint directories exist
157
+ self.assertEqual(
158
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
159
+ {"checkpoint-2", "checkpoint-4"},
160
+ )
161
+
162
+ # resume and we should try to checkpoint at 6, where we'll have to remove
163
+ # checkpoint-2 and checkpoint-4 instead of just a single previous checkpoint
164
+
165
+ resume_run_args = f"""
166
+ examples/text_to_image/train_text_to_image_lora.py
167
+ --pretrained_model_name_or_path {pretrained_model_name_or_path}
168
+ --dataset_name hf-internal-testing/dummy_image_text_data
169
+ --resolution 64
170
+ --center_crop
171
+ --random_flip
172
+ --train_batch_size 1
173
+ --gradient_accumulation_steps 1
174
+ --max_train_steps 8
175
+ --learning_rate 5.0e-04
176
+ --scale_lr
177
+ --lr_scheduler constant
178
+ --lr_warmup_steps 0
179
+ --output_dir {tmpdir}
180
+ --checkpointing_steps=2
181
+ --resume_from_checkpoint=checkpoint-4
182
+ --checkpoints_total_limit=2
183
+ --seed=0
184
+ --num_validation_images=0
185
+ """.split()
186
+
187
+ run_command(self._launch_args + resume_run_args)
188
+
189
+ pipe = DiffusionPipeline.from_pretrained(
190
+ "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=None
191
+ )
192
+ pipe.load_lora_weights(tmpdir)
193
+ pipe(prompt, num_inference_steps=1)
194
+
195
+ # check checkpoint directories exist
196
+ self.assertEqual(
197
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
198
+ {"checkpoint-6", "checkpoint-8"},
199
+ )
200
+
201
+
202
+ class TextToImageLoRASDXL(ExamplesTestsAccelerate):
203
+ def test_text_to_image_lora_sdxl(self):
204
+ with tempfile.TemporaryDirectory() as tmpdir:
205
+ test_args = f"""
206
+ examples/text_to_image/train_text_to_image_lora_sdxl.py
207
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-xl-pipe
208
+ --dataset_name hf-internal-testing/dummy_image_text_data
209
+ --resolution 64
210
+ --train_batch_size 1
211
+ --gradient_accumulation_steps 1
212
+ --max_train_steps 2
213
+ --learning_rate 5.0e-04
214
+ --scale_lr
215
+ --lr_scheduler constant
216
+ --lr_warmup_steps 0
217
+ --output_dir {tmpdir}
218
+ """.split()
219
+
220
+ run_command(self._launch_args + test_args)
221
+ # save_pretrained smoke test
222
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "pytorch_lora_weights.safetensors")))
223
+
224
+ # make sure the state_dict has the correct naming in the parameters.
225
+ lora_state_dict = safetensors.torch.load_file(os.path.join(tmpdir, "pytorch_lora_weights.safetensors"))
226
+ is_lora = all("lora" in k for k in lora_state_dict.keys())
227
+ self.assertTrue(is_lora)
228
+
229
+ def test_text_to_image_lora_sdxl_with_text_encoder(self):
230
+ with tempfile.TemporaryDirectory() as tmpdir:
231
+ test_args = f"""
232
+ examples/text_to_image/train_text_to_image_lora_sdxl.py
233
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-xl-pipe
234
+ --dataset_name hf-internal-testing/dummy_image_text_data
235
+ --resolution 64
236
+ --train_batch_size 1
237
+ --gradient_accumulation_steps 1
238
+ --max_train_steps 2
239
+ --learning_rate 5.0e-04
240
+ --scale_lr
241
+ --lr_scheduler constant
242
+ --lr_warmup_steps 0
243
+ --output_dir {tmpdir}
244
+ --train_text_encoder
245
+ """.split()
246
+
247
+ run_command(self._launch_args + test_args)
248
+ # save_pretrained smoke test
249
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "pytorch_lora_weights.safetensors")))
250
+
251
+ # make sure the state_dict has the correct naming in the parameters.
252
+ lora_state_dict = safetensors.torch.load_file(os.path.join(tmpdir, "pytorch_lora_weights.safetensors"))
253
+ is_lora = all("lora" in k for k in lora_state_dict.keys())
254
+ self.assertTrue(is_lora)
255
+
256
+ # when not training the text encoder, all the parameters in the state dict should start
257
+ # with `"unet"` or `"text_encoder"` or `"text_encoder_2"` in their names.
258
+ keys = lora_state_dict.keys()
259
+ starts_with_unet = all(
260
+ k.startswith("unet") or k.startswith("text_encoder") or k.startswith("text_encoder_2") for k in keys
261
+ )
262
+ self.assertTrue(starts_with_unet)
263
+
264
+ def test_text_to_image_lora_sdxl_text_encoder_checkpointing_checkpoints_total_limit(self):
265
+ prompt = "a prompt"
266
+ pipeline_path = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
267
+
268
+ with tempfile.TemporaryDirectory() as tmpdir:
269
+ # Run training script with checkpointing
270
+ # max_train_steps == 6, checkpointing_steps == 2, checkpoints_total_limit == 2
271
+ # Should create checkpoints at steps 2, 4, 6
272
+ # with checkpoint at step 2 deleted
273
+
274
+ initial_run_args = f"""
275
+ examples/text_to_image/train_text_to_image_lora_sdxl.py
276
+ --pretrained_model_name_or_path {pipeline_path}
277
+ --dataset_name hf-internal-testing/dummy_image_text_data
278
+ --resolution 64
279
+ --train_batch_size 1
280
+ --gradient_accumulation_steps 1
281
+ --max_train_steps 6
282
+ --learning_rate 5.0e-04
283
+ --scale_lr
284
+ --lr_scheduler constant
285
+ --train_text_encoder
286
+ --lr_warmup_steps 0
287
+ --output_dir {tmpdir}
288
+ --checkpointing_steps=2
289
+ --checkpoints_total_limit=2
290
+ """.split()
291
+
292
+ run_command(self._launch_args + initial_run_args)
293
+
294
+ pipe = DiffusionPipeline.from_pretrained(pipeline_path)
295
+ pipe.load_lora_weights(tmpdir)
296
+ pipe(prompt, num_inference_steps=1)
297
+
298
+ # check checkpoint directories exist
299
+ # checkpoint-2 should have been deleted
300
+ self.assertEqual({x for x in os.listdir(tmpdir) if "checkpoint" in x}, {"checkpoint-4", "checkpoint-6"})
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image.py ADDED
@@ -0,0 +1,1169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
19
+ import math
20
+ import os
21
+ import random
22
+ import shutil
23
+ from contextlib import nullcontext
24
+ from pathlib import Path
25
+
26
+ import accelerate
27
+ import datasets
28
+ import numpy as np
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ import transformers
33
+ from accelerate import Accelerator
34
+ from accelerate.logging import get_logger
35
+ from accelerate.state import AcceleratorState
36
+ from accelerate.utils import ProjectConfiguration, set_seed
37
+ from datasets import load_dataset
38
+ from huggingface_hub import create_repo, upload_folder
39
+ from packaging import version
40
+ from torchvision import transforms
41
+ from tqdm.auto import tqdm
42
+ from transformers import CLIPTextModel, CLIPTokenizer
43
+ from transformers.utils import ContextManagers
44
+
45
+ import diffusers
46
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
47
+ from diffusers.optimization import get_scheduler
48
+ from diffusers.training_utils import EMAModel, compute_dream_and_update_latents, compute_snr
49
+ from diffusers.utils import check_min_version, deprecate, is_wandb_available, make_image_grid
50
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
51
+ from diffusers.utils.import_utils import is_xformers_available
52
+ from diffusers.utils.torch_utils import is_compiled_module
53
+
54
+
55
+ if is_wandb_available():
56
+ import wandb
57
+
58
+
59
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
60
+ check_min_version("0.39.0.dev0")
61
+
62
+ logger = get_logger(__name__, log_level="INFO")
63
+
64
+ DATASET_NAME_MAPPING = {
65
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
66
+ }
67
+
68
+
69
+ def save_model_card(
70
+ args,
71
+ repo_id: str,
72
+ images: list = None,
73
+ repo_folder: str = None,
74
+ ):
75
+ img_str = ""
76
+ if len(images) > 0:
77
+ image_grid = make_image_grid(images, 1, len(args.validation_prompts))
78
+ image_grid.save(os.path.join(repo_folder, "val_imgs_grid.png"))
79
+ img_str += "![val_imgs_grid](./val_imgs_grid.png)\n"
80
+
81
+ model_description = f"""
82
+ # Text-to-image finetuning - {repo_id}
83
+
84
+ This pipeline was finetuned from **{args.pretrained_model_name_or_path}** on the **{args.dataset_name}** dataset. Below are some example images generated with the finetuned pipeline using the following prompts: {args.validation_prompts}: \n
85
+ {img_str}
86
+
87
+ ## Pipeline usage
88
+
89
+ You can use the pipeline like so:
90
+
91
+ ```python
92
+ from diffusers import DiffusionPipeline
93
+ import torch
94
+
95
+ pipeline = DiffusionPipeline.from_pretrained("{repo_id}", torch_dtype=torch.float16)
96
+ prompt = "{args.validation_prompts[0]}"
97
+ image = pipeline(prompt).images[0]
98
+ image.save("my_image.png")
99
+ ```
100
+
101
+ ## Training info
102
+
103
+ These are the key hyperparameters used during training:
104
+
105
+ * Epochs: {args.num_train_epochs}
106
+ * Learning rate: {args.learning_rate}
107
+ * Batch size: {args.train_batch_size}
108
+ * Gradient accumulation steps: {args.gradient_accumulation_steps}
109
+ * Image resolution: {args.resolution}
110
+ * Mixed-precision: {args.mixed_precision}
111
+
112
+ """
113
+ wandb_info = ""
114
+ if is_wandb_available():
115
+ wandb_run_url = None
116
+ if wandb.run is not None:
117
+ wandb_run_url = wandb.run.url
118
+
119
+ if wandb_run_url is not None:
120
+ wandb_info = f"""
121
+ More information on all the CLI arguments and the environment are available on your [`wandb` run page]({wandb_run_url}).
122
+ """
123
+
124
+ model_description += wandb_info
125
+
126
+ model_card = load_or_create_model_card(
127
+ repo_id_or_path=repo_id,
128
+ from_training=True,
129
+ license="creativeml-openrail-m",
130
+ base_model=args.pretrained_model_name_or_path,
131
+ model_description=model_description,
132
+ inference=True,
133
+ )
134
+
135
+ tags = ["stable-diffusion", "stable-diffusion-diffusers", "text-to-image", "diffusers", "diffusers-training"]
136
+ model_card = populate_model_card(model_card, tags=tags)
137
+
138
+ model_card.save(os.path.join(repo_folder, "README.md"))
139
+
140
+
141
+ def log_validation(vae, text_encoder, tokenizer, unet, args, accelerator, weight_dtype, epoch):
142
+ logger.info("Running validation... ")
143
+
144
+ pipeline = StableDiffusionPipeline.from_pretrained(
145
+ args.pretrained_model_name_or_path,
146
+ vae=accelerator.unwrap_model(vae),
147
+ text_encoder=accelerator.unwrap_model(text_encoder),
148
+ tokenizer=tokenizer,
149
+ unet=accelerator.unwrap_model(unet),
150
+ safety_checker=None,
151
+ revision=args.revision,
152
+ variant=args.variant,
153
+ torch_dtype=weight_dtype,
154
+ )
155
+ pipeline = pipeline.to(accelerator.device)
156
+ pipeline.set_progress_bar_config(disable=True)
157
+
158
+ if args.enable_xformers_memory_efficient_attention:
159
+ pipeline.enable_xformers_memory_efficient_attention()
160
+
161
+ if args.seed is None:
162
+ generator = None
163
+ else:
164
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
165
+
166
+ images = []
167
+ for i in range(len(args.validation_prompts)):
168
+ if torch.backends.mps.is_available():
169
+ autocast_ctx = nullcontext()
170
+ else:
171
+ autocast_ctx = torch.autocast(accelerator.device.type)
172
+
173
+ with autocast_ctx:
174
+ image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0]
175
+
176
+ images.append(image)
177
+
178
+ for tracker in accelerator.trackers:
179
+ if tracker.name == "tensorboard":
180
+ np_images = np.stack([np.asarray(img) for img in images])
181
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
182
+ elif tracker.name == "wandb":
183
+ tracker.log(
184
+ {
185
+ "validation": [
186
+ wandb.Image(image, caption=f"{i}: {args.validation_prompts[i]}")
187
+ for i, image in enumerate(images)
188
+ ]
189
+ }
190
+ )
191
+ else:
192
+ logger.warning(f"image logging not implemented for {tracker.name}")
193
+
194
+ del pipeline
195
+ torch.cuda.empty_cache()
196
+
197
+ return images
198
+
199
+
200
+ def parse_args():
201
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
202
+ parser.add_argument(
203
+ "--input_perturbation", type=float, default=0, help="The scale of input perturbation. Recommended 0.1."
204
+ )
205
+ parser.add_argument(
206
+ "--pretrained_model_name_or_path",
207
+ type=str,
208
+ default=None,
209
+ required=True,
210
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
211
+ )
212
+ parser.add_argument(
213
+ "--revision",
214
+ type=str,
215
+ default=None,
216
+ required=False,
217
+ help="Revision of pretrained model identifier from huggingface.co/models.",
218
+ )
219
+ parser.add_argument(
220
+ "--variant",
221
+ type=str,
222
+ default=None,
223
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
224
+ )
225
+ parser.add_argument(
226
+ "--dataset_name",
227
+ type=str,
228
+ default=None,
229
+ help=(
230
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
231
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
232
+ " or to a folder containing files that 🤗 Datasets can understand."
233
+ ),
234
+ )
235
+ parser.add_argument(
236
+ "--dataset_config_name",
237
+ type=str,
238
+ default=None,
239
+ help="The config of the Dataset, leave as None if there's only one config.",
240
+ )
241
+ parser.add_argument(
242
+ "--train_data_dir",
243
+ type=str,
244
+ default=None,
245
+ help=(
246
+ "A folder containing the training data. Folder contents must follow the structure described in"
247
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
248
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
249
+ ),
250
+ )
251
+ parser.add_argument(
252
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
253
+ )
254
+ parser.add_argument(
255
+ "--caption_column",
256
+ type=str,
257
+ default="text",
258
+ help="The column of the dataset containing a caption or a list of captions.",
259
+ )
260
+ parser.add_argument(
261
+ "--max_train_samples",
262
+ type=int,
263
+ default=None,
264
+ help=(
265
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
266
+ "value if set."
267
+ ),
268
+ )
269
+ parser.add_argument(
270
+ "--validation_prompts",
271
+ type=str,
272
+ default=None,
273
+ nargs="+",
274
+ help=("A set of prompts evaluated every `--validation_epochs` and logged to `--report_to`."),
275
+ )
276
+ parser.add_argument(
277
+ "--output_dir",
278
+ type=str,
279
+ default="sd-model-finetuned",
280
+ help="The output directory where the model predictions and checkpoints will be written.",
281
+ )
282
+ parser.add_argument(
283
+ "--cache_dir",
284
+ type=str,
285
+ default=None,
286
+ help="The directory where the downloaded models and datasets will be stored.",
287
+ )
288
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
289
+ parser.add_argument(
290
+ "--resolution",
291
+ type=int,
292
+ default=512,
293
+ help=(
294
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
295
+ " resolution"
296
+ ),
297
+ )
298
+ parser.add_argument(
299
+ "--center_crop",
300
+ default=False,
301
+ action="store_true",
302
+ help=(
303
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
304
+ " cropped. The images will be resized to the resolution first before cropping."
305
+ ),
306
+ )
307
+ parser.add_argument(
308
+ "--random_flip",
309
+ action="store_true",
310
+ help="whether to randomly flip images horizontally",
311
+ )
312
+ parser.add_argument(
313
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
314
+ )
315
+ parser.add_argument("--num_train_epochs", type=int, default=100)
316
+ parser.add_argument(
317
+ "--max_train_steps",
318
+ type=int,
319
+ default=None,
320
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
321
+ )
322
+ parser.add_argument(
323
+ "--gradient_accumulation_steps",
324
+ type=int,
325
+ default=1,
326
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
327
+ )
328
+ parser.add_argument(
329
+ "--gradient_checkpointing",
330
+ action="store_true",
331
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
332
+ )
333
+ parser.add_argument(
334
+ "--learning_rate",
335
+ type=float,
336
+ default=1e-4,
337
+ help="Initial learning rate (after the potential warmup period) to use.",
338
+ )
339
+ parser.add_argument(
340
+ "--scale_lr",
341
+ action="store_true",
342
+ default=False,
343
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
344
+ )
345
+ parser.add_argument(
346
+ "--lr_scheduler",
347
+ type=str,
348
+ default="constant",
349
+ help=(
350
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
351
+ ' "constant", "constant_with_warmup"]'
352
+ ),
353
+ )
354
+ parser.add_argument(
355
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
356
+ )
357
+ parser.add_argument(
358
+ "--snr_gamma",
359
+ type=float,
360
+ default=None,
361
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
362
+ "More details here: https://huggingface.co/papers/2303.09556.",
363
+ )
364
+ parser.add_argument(
365
+ "--dream_training",
366
+ action="store_true",
367
+ help=(
368
+ "Use the DREAM training method, which makes training more efficient and accurate at the "
369
+ "expense of doing an extra forward pass. See: https://huggingface.co/papers/2312.00210"
370
+ ),
371
+ )
372
+ parser.add_argument(
373
+ "--dream_detail_preservation",
374
+ type=float,
375
+ default=1.0,
376
+ help="Dream detail preservation factor p (should be greater than 0; default=1.0, as suggested in the paper)",
377
+ )
378
+ parser.add_argument(
379
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
380
+ )
381
+ parser.add_argument(
382
+ "--allow_tf32",
383
+ action="store_true",
384
+ help=(
385
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
386
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
387
+ ),
388
+ )
389
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
390
+ parser.add_argument("--offload_ema", action="store_true", help="Offload EMA model to CPU during training step.")
391
+ parser.add_argument("--foreach_ema", action="store_true", help="Use faster foreach implementation of EMAModel.")
392
+ parser.add_argument(
393
+ "--non_ema_revision",
394
+ type=str,
395
+ default=None,
396
+ required=False,
397
+ help=(
398
+ "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
399
+ " remote repository specified with --pretrained_model_name_or_path."
400
+ ),
401
+ )
402
+ parser.add_argument(
403
+ "--dataloader_num_workers",
404
+ type=int,
405
+ default=0,
406
+ help=(
407
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
408
+ ),
409
+ )
410
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
411
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
412
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
413
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
414
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
415
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
416
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
417
+ parser.add_argument(
418
+ "--prediction_type",
419
+ type=str,
420
+ default=None,
421
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
422
+ )
423
+ parser.add_argument(
424
+ "--hub_model_id",
425
+ type=str,
426
+ default=None,
427
+ help="The name of the repository to keep in sync with the local `output_dir`.",
428
+ )
429
+ parser.add_argument(
430
+ "--logging_dir",
431
+ type=str,
432
+ default="logs",
433
+ help=(
434
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
435
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
436
+ ),
437
+ )
438
+ parser.add_argument(
439
+ "--mixed_precision",
440
+ type=str,
441
+ default=None,
442
+ choices=["no", "fp16", "bf16"],
443
+ help=(
444
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
445
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
446
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
447
+ ),
448
+ )
449
+ parser.add_argument(
450
+ "--report_to",
451
+ type=str,
452
+ default="tensorboard",
453
+ help=(
454
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
455
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
456
+ ),
457
+ )
458
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
459
+ parser.add_argument(
460
+ "--checkpointing_steps",
461
+ type=int,
462
+ default=500,
463
+ help=(
464
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
465
+ " training using `--resume_from_checkpoint`."
466
+ ),
467
+ )
468
+ parser.add_argument(
469
+ "--checkpoints_total_limit",
470
+ type=int,
471
+ default=None,
472
+ help=("Max number of checkpoints to store."),
473
+ )
474
+ parser.add_argument(
475
+ "--resume_from_checkpoint",
476
+ type=str,
477
+ default=None,
478
+ help=(
479
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
480
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
481
+ ),
482
+ )
483
+ parser.add_argument(
484
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
485
+ )
486
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
487
+ parser.add_argument(
488
+ "--validation_epochs",
489
+ type=int,
490
+ default=5,
491
+ help="Run validation every X epochs.",
492
+ )
493
+ parser.add_argument(
494
+ "--tracker_project_name",
495
+ type=str,
496
+ default="text2image-fine-tune",
497
+ help=(
498
+ "The `project_name` argument passed to Accelerator.init_trackers for"
499
+ " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
500
+ ),
501
+ )
502
+ parser.add_argument(
503
+ "--image_interpolation_mode",
504
+ type=str,
505
+ default="lanczos",
506
+ choices=[
507
+ f.lower() for f in dir(transforms.InterpolationMode) if not f.startswith("__") and not f.endswith("__")
508
+ ],
509
+ help="The image interpolation method to use for resizing images.",
510
+ )
511
+
512
+ args = parser.parse_args()
513
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
514
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
515
+ args.local_rank = env_local_rank
516
+
517
+ # Sanity checks
518
+ if args.dataset_name is None and args.train_data_dir is None:
519
+ raise ValueError("Need either a dataset name or a training folder.")
520
+
521
+ # default to using the same revision for the non-ema model if not specified
522
+ if args.non_ema_revision is None:
523
+ args.non_ema_revision = args.revision
524
+
525
+ return args
526
+
527
+
528
+ def main():
529
+ args = parse_args()
530
+
531
+ if args.report_to == "wandb" and args.hub_token is not None:
532
+ raise ValueError(
533
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
534
+ " Please use `hf auth login` to authenticate with the Hub."
535
+ )
536
+
537
+ if args.non_ema_revision is not None:
538
+ deprecate(
539
+ "non_ema_revision!=None",
540
+ "0.15.0",
541
+ message=(
542
+ "Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
543
+ " use `--variant=non_ema` instead."
544
+ ),
545
+ )
546
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
547
+
548
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
549
+
550
+ accelerator = Accelerator(
551
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
552
+ mixed_precision=args.mixed_precision,
553
+ log_with=args.report_to,
554
+ project_config=accelerator_project_config,
555
+ )
556
+
557
+ # Disable AMP for MPS.
558
+ if torch.backends.mps.is_available():
559
+ accelerator.native_amp = False
560
+
561
+ # Make one log on every process with the configuration for debugging.
562
+ logging.basicConfig(
563
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
564
+ datefmt="%m/%d/%Y %H:%M:%S",
565
+ level=logging.INFO,
566
+ )
567
+ logger.info(accelerator.state, main_process_only=False)
568
+ if accelerator.is_local_main_process:
569
+ datasets.utils.logging.set_verbosity_warning()
570
+ transformers.utils.logging.set_verbosity_warning()
571
+ diffusers.utils.logging.set_verbosity_info()
572
+ else:
573
+ datasets.utils.logging.set_verbosity_error()
574
+ transformers.utils.logging.set_verbosity_error()
575
+ diffusers.utils.logging.set_verbosity_error()
576
+
577
+ # If passed along, set the training seed now.
578
+ if args.seed is not None:
579
+ set_seed(args.seed)
580
+
581
+ # Handle the repository creation
582
+ if accelerator.is_main_process:
583
+ if args.output_dir is not None:
584
+ os.makedirs(args.output_dir, exist_ok=True)
585
+
586
+ if args.push_to_hub:
587
+ repo_id = create_repo(
588
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
589
+ ).repo_id
590
+
591
+ # Load scheduler, tokenizer and models.
592
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
593
+ tokenizer = CLIPTokenizer.from_pretrained(
594
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
595
+ )
596
+
597
+ def deepspeed_zero_init_disabled_context_manager():
598
+ """
599
+ returns either a context list that includes one that will disable zero.Init or an empty context list
600
+ """
601
+ deepspeed_plugin = AcceleratorState().deepspeed_plugin if accelerate.state.is_initialized() else None
602
+ if deepspeed_plugin is None:
603
+ return []
604
+
605
+ return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
606
+
607
+ # Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3.
608
+ # For this to work properly all models must be run through `accelerate.prepare`. But accelerate
609
+ # will try to assign the same optimizer with the same weights to all models during
610
+ # `deepspeed.initialize`, which of course doesn't work.
611
+ #
612
+ # For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2
613
+ # frozen models from being partitioned during `zero.Init` which gets called during
614
+ # `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding
615
+ # across multiple gpus and only UNet2DConditionModel will get ZeRO sharded.
616
+ with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
617
+ text_encoder = CLIPTextModel.from_pretrained(
618
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
619
+ )
620
+ vae = AutoencoderKL.from_pretrained(
621
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
622
+ )
623
+
624
+ unet = UNet2DConditionModel.from_pretrained(
625
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision
626
+ )
627
+
628
+ # Freeze vae and text_encoder and set unet to trainable
629
+ vae.requires_grad_(False)
630
+ text_encoder.requires_grad_(False)
631
+ unet.train()
632
+
633
+ # Create EMA for the unet.
634
+ if args.use_ema:
635
+ ema_unet = UNet2DConditionModel.from_pretrained(
636
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
637
+ )
638
+ ema_unet = EMAModel(
639
+ ema_unet.parameters(),
640
+ model_cls=UNet2DConditionModel,
641
+ model_config=ema_unet.config,
642
+ foreach=args.foreach_ema,
643
+ )
644
+
645
+ if args.enable_xformers_memory_efficient_attention:
646
+ if is_xformers_available():
647
+ import xformers
648
+
649
+ xformers_version = version.parse(xformers.__version__)
650
+ if xformers_version == version.parse("0.0.16"):
651
+ logger.warning(
652
+ "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."
653
+ )
654
+ unet.enable_xformers_memory_efficient_attention()
655
+ else:
656
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
657
+
658
+ # `accelerate` 0.16.0 will have better support for customized saving
659
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
660
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
661
+ def save_model_hook(models, weights, output_dir):
662
+ if accelerator.is_main_process:
663
+ if args.use_ema:
664
+ ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
665
+
666
+ for i, model in enumerate(models):
667
+ model.save_pretrained(os.path.join(output_dir, "unet"))
668
+
669
+ # make sure to pop weight so that corresponding model is not saved again
670
+ weights.pop()
671
+
672
+ def load_model_hook(models, input_dir):
673
+ if args.use_ema:
674
+ load_model = EMAModel.from_pretrained(
675
+ os.path.join(input_dir, "unet_ema"), UNet2DConditionModel, foreach=args.foreach_ema
676
+ )
677
+ ema_unet.load_state_dict(load_model.state_dict())
678
+ if args.offload_ema:
679
+ ema_unet.pin_memory()
680
+ else:
681
+ ema_unet.to(accelerator.device)
682
+ del load_model
683
+
684
+ for _ in range(len(models)):
685
+ # pop models so that they are not loaded again
686
+ model = models.pop()
687
+
688
+ # load diffusers style into model
689
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
690
+ model.register_to_config(**load_model.config)
691
+
692
+ model.load_state_dict(load_model.state_dict())
693
+ del load_model
694
+
695
+ accelerator.register_save_state_pre_hook(save_model_hook)
696
+ accelerator.register_load_state_pre_hook(load_model_hook)
697
+
698
+ if args.gradient_checkpointing:
699
+ unet.enable_gradient_checkpointing()
700
+
701
+ # Enable TF32 for faster training on Ampere GPUs,
702
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
703
+ if args.allow_tf32:
704
+ torch.backends.cuda.matmul.allow_tf32 = True
705
+
706
+ if args.scale_lr:
707
+ args.learning_rate = (
708
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
709
+ )
710
+
711
+ # Initialize the optimizer
712
+ if args.use_8bit_adam:
713
+ try:
714
+ import bitsandbytes as bnb
715
+ except ImportError:
716
+ raise ImportError(
717
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
718
+ )
719
+
720
+ optimizer_cls = bnb.optim.AdamW8bit
721
+ else:
722
+ optimizer_cls = torch.optim.AdamW
723
+
724
+ optimizer = optimizer_cls(
725
+ unet.parameters(),
726
+ lr=args.learning_rate,
727
+ betas=(args.adam_beta1, args.adam_beta2),
728
+ weight_decay=args.adam_weight_decay,
729
+ eps=args.adam_epsilon,
730
+ )
731
+
732
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
733
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
734
+
735
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
736
+ # download the dataset.
737
+ if args.dataset_name is not None:
738
+ # Downloading and loading a dataset from the hub.
739
+ dataset = load_dataset(
740
+ args.dataset_name,
741
+ args.dataset_config_name,
742
+ cache_dir=args.cache_dir,
743
+ data_dir=args.train_data_dir,
744
+ )
745
+ else:
746
+ data_files = {}
747
+ if args.train_data_dir is not None:
748
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
749
+ dataset = load_dataset(
750
+ "imagefolder",
751
+ data_files=data_files,
752
+ cache_dir=args.cache_dir,
753
+ )
754
+ # See more about loading custom images at
755
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
756
+
757
+ # Preprocessing the datasets.
758
+ # We need to tokenize inputs and targets.
759
+ column_names = dataset["train"].column_names
760
+
761
+ # 6. Get the column names for input/target.
762
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
763
+ if args.image_column is None:
764
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
765
+ else:
766
+ image_column = args.image_column
767
+ if image_column not in column_names:
768
+ raise ValueError(
769
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
770
+ )
771
+ if args.caption_column is None:
772
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
773
+ else:
774
+ caption_column = args.caption_column
775
+ if caption_column not in column_names:
776
+ raise ValueError(
777
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
778
+ )
779
+
780
+ # Preprocessing the datasets.
781
+ # We need to tokenize input captions and transform the images.
782
+ def tokenize_captions(examples, is_train=True):
783
+ captions = []
784
+ for caption in examples[caption_column]:
785
+ if isinstance(caption, str):
786
+ captions.append(caption)
787
+ elif isinstance(caption, (list, np.ndarray)):
788
+ # take a random caption if there are multiple
789
+ captions.append(random.choice(caption) if is_train else caption[0])
790
+ else:
791
+ raise ValueError(
792
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
793
+ )
794
+ inputs = tokenizer(
795
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
796
+ )
797
+ return inputs.input_ids
798
+
799
+ # Get the specified interpolation method from the args
800
+ interpolation = getattr(transforms.InterpolationMode, args.image_interpolation_mode.upper(), None)
801
+
802
+ # Raise an error if the interpolation method is invalid
803
+ if interpolation is None:
804
+ raise ValueError(f"Unsupported interpolation mode {args.image_interpolation_mode}.")
805
+
806
+ # Data preprocessing transformations
807
+ train_transforms = transforms.Compose(
808
+ [
809
+ transforms.Resize(args.resolution, interpolation=interpolation), # Use dynamic interpolation method
810
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
811
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
812
+ transforms.ToTensor(),
813
+ transforms.Normalize([0.5], [0.5]),
814
+ ]
815
+ )
816
+
817
+ def preprocess_train(examples):
818
+ images = [image.convert("RGB") for image in examples[image_column]]
819
+ examples["pixel_values"] = [train_transforms(image) for image in images]
820
+ examples["input_ids"] = tokenize_captions(examples)
821
+ return examples
822
+
823
+ with accelerator.main_process_first():
824
+ if args.max_train_samples is not None:
825
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
826
+ # Set the training transforms
827
+ train_dataset = dataset["train"].with_transform(preprocess_train)
828
+
829
+ def collate_fn(examples):
830
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
831
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
832
+ input_ids = torch.stack([example["input_ids"] for example in examples])
833
+ return {"pixel_values": pixel_values, "input_ids": input_ids}
834
+
835
+ # DataLoaders creation:
836
+ train_dataloader = torch.utils.data.DataLoader(
837
+ train_dataset,
838
+ shuffle=True,
839
+ collate_fn=collate_fn,
840
+ batch_size=args.train_batch_size,
841
+ num_workers=args.dataloader_num_workers,
842
+ )
843
+
844
+ # Scheduler and math around the number of training steps.
845
+ # Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
846
+ num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
847
+ if args.max_train_steps is None:
848
+ len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
849
+ num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
850
+ num_training_steps_for_scheduler = (
851
+ args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
852
+ )
853
+ else:
854
+ num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
855
+
856
+ lr_scheduler = get_scheduler(
857
+ args.lr_scheduler,
858
+ optimizer=optimizer,
859
+ num_warmup_steps=num_warmup_steps_for_scheduler,
860
+ num_training_steps=num_training_steps_for_scheduler,
861
+ )
862
+
863
+ # Prepare everything with our `accelerator`.
864
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
865
+ unet, optimizer, train_dataloader, lr_scheduler
866
+ )
867
+
868
+ if args.use_ema:
869
+ if args.offload_ema:
870
+ ema_unet.pin_memory()
871
+ else:
872
+ ema_unet.to(accelerator.device)
873
+
874
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
875
+ # as these weights are only used for inference, keeping weights in full precision is not required.
876
+ weight_dtype = torch.float32
877
+ if accelerator.mixed_precision == "fp16":
878
+ weight_dtype = torch.float16
879
+ args.mixed_precision = accelerator.mixed_precision
880
+ elif accelerator.mixed_precision == "bf16":
881
+ weight_dtype = torch.bfloat16
882
+ args.mixed_precision = accelerator.mixed_precision
883
+
884
+ # Move text_encode and vae to gpu and cast to weight_dtype
885
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
886
+ vae.to(accelerator.device, dtype=weight_dtype)
887
+
888
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
889
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
890
+ if args.max_train_steps is None:
891
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
892
+ if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
893
+ logger.warning(
894
+ f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
895
+ f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
896
+ f"This inconsistency may result in the learning rate scheduler not functioning properly."
897
+ )
898
+ # Afterwards we recalculate our number of training epochs
899
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
900
+
901
+ # We need to initialize the trackers we use, and also store our configuration.
902
+ # The trackers initializes automatically on the main process.
903
+ if accelerator.is_main_process:
904
+ tracker_config = dict(vars(args))
905
+ tracker_config.pop("validation_prompts")
906
+ accelerator.init_trackers(args.tracker_project_name, tracker_config)
907
+
908
+ # Function for unwrapping if model was compiled with `torch.compile`.
909
+ def unwrap_model(model):
910
+ model = accelerator.unwrap_model(model)
911
+ model = model._orig_mod if is_compiled_module(model) else model
912
+ return model
913
+
914
+ # Train!
915
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
916
+
917
+ logger.info("***** Running training *****")
918
+ logger.info(f" Num examples = {len(train_dataset)}")
919
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
920
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
921
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
922
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
923
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
924
+ global_step = 0
925
+ first_epoch = 0
926
+
927
+ # Potentially load in the weights and states from a previous save
928
+ if args.resume_from_checkpoint:
929
+ if args.resume_from_checkpoint != "latest":
930
+ path = os.path.basename(args.resume_from_checkpoint)
931
+ else:
932
+ # Get the most recent checkpoint
933
+ dirs = os.listdir(args.output_dir)
934
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
935
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
936
+ path = dirs[-1] if len(dirs) > 0 else None
937
+
938
+ if path is None:
939
+ accelerator.print(
940
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
941
+ )
942
+ args.resume_from_checkpoint = None
943
+ initial_global_step = 0
944
+ else:
945
+ accelerator.print(f"Resuming from checkpoint {path}")
946
+ accelerator.load_state(os.path.join(args.output_dir, path))
947
+ global_step = int(path.split("-")[1])
948
+
949
+ initial_global_step = global_step
950
+ first_epoch = global_step // num_update_steps_per_epoch
951
+
952
+ else:
953
+ initial_global_step = 0
954
+
955
+ progress_bar = tqdm(
956
+ range(0, args.max_train_steps),
957
+ initial=initial_global_step,
958
+ desc="Steps",
959
+ # Only show the progress bar once on each machine.
960
+ disable=not accelerator.is_local_main_process,
961
+ )
962
+
963
+ for epoch in range(first_epoch, args.num_train_epochs):
964
+ train_loss = 0.0
965
+ for step, batch in enumerate(train_dataloader):
966
+ with accelerator.accumulate(unet):
967
+ # Convert images to latent space
968
+ latents = vae.encode(batch["pixel_values"].to(weight_dtype)).latent_dist.sample()
969
+ latents = latents * vae.config.scaling_factor
970
+
971
+ # Sample noise that we'll add to the latents
972
+ noise = torch.randn_like(latents)
973
+ if args.noise_offset:
974
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
975
+ noise += args.noise_offset * torch.randn(
976
+ (latents.shape[0], latents.shape[1], 1, 1), device=latents.device
977
+ )
978
+ if args.input_perturbation:
979
+ new_noise = noise + args.input_perturbation * torch.randn_like(noise)
980
+ bsz = latents.shape[0]
981
+ # Sample a random timestep for each image
982
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
983
+ timesteps = timesteps.long()
984
+
985
+ # Add noise to the latents according to the noise magnitude at each timestep
986
+ # (this is the forward diffusion process)
987
+ if args.input_perturbation:
988
+ noisy_latents = noise_scheduler.add_noise(latents, new_noise, timesteps)
989
+ else:
990
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
991
+
992
+ # Get the text embedding for conditioning
993
+ encoder_hidden_states = text_encoder(batch["input_ids"], return_dict=False)[0]
994
+
995
+ # Get the target for loss depending on the prediction type
996
+ if args.prediction_type is not None:
997
+ # set prediction_type of scheduler if defined
998
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
999
+
1000
+ if noise_scheduler.config.prediction_type == "epsilon":
1001
+ target = noise
1002
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1003
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
1004
+ else:
1005
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1006
+
1007
+ if args.dream_training:
1008
+ noisy_latents, target = compute_dream_and_update_latents(
1009
+ unet,
1010
+ noise_scheduler,
1011
+ timesteps,
1012
+ noise,
1013
+ noisy_latents,
1014
+ target,
1015
+ encoder_hidden_states,
1016
+ args.dream_detail_preservation,
1017
+ )
1018
+
1019
+ # Predict the noise residual and compute loss
1020
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states, return_dict=False)[0]
1021
+
1022
+ if args.snr_gamma is None:
1023
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1024
+ else:
1025
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
1026
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
1027
+ # This is discussed in Section 4.2 of the same paper.
1028
+ snr = compute_snr(noise_scheduler, timesteps)
1029
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
1030
+ dim=1
1031
+ )[0]
1032
+ if noise_scheduler.config.prediction_type == "epsilon":
1033
+ mse_loss_weights = mse_loss_weights / snr
1034
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1035
+ mse_loss_weights = mse_loss_weights / (snr + 1)
1036
+
1037
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
1038
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
1039
+ loss = loss.mean()
1040
+
1041
+ # Gather the losses across all processes for logging (if we use distributed training).
1042
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
1043
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1044
+
1045
+ # Backpropagate
1046
+ accelerator.backward(loss)
1047
+ if accelerator.sync_gradients:
1048
+ accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm)
1049
+ optimizer.step()
1050
+ lr_scheduler.step()
1051
+ optimizer.zero_grad()
1052
+
1053
+ # Checks if the accelerator has performed an optimization step behind the scenes
1054
+ if accelerator.sync_gradients:
1055
+ if args.use_ema:
1056
+ if args.offload_ema:
1057
+ ema_unet.to(device="cuda", non_blocking=True)
1058
+ ema_unet.step(unet.parameters())
1059
+ if args.offload_ema:
1060
+ ema_unet.to(device="cpu", non_blocking=True)
1061
+ progress_bar.update(1)
1062
+ global_step += 1
1063
+ accelerator.log({"train_loss": train_loss}, step=global_step)
1064
+ train_loss = 0.0
1065
+
1066
+ if global_step % args.checkpointing_steps == 0:
1067
+ if accelerator.is_main_process:
1068
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1069
+ if args.checkpoints_total_limit is not None:
1070
+ checkpoints = os.listdir(args.output_dir)
1071
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1072
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1073
+
1074
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1075
+ if len(checkpoints) >= args.checkpoints_total_limit:
1076
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1077
+ removing_checkpoints = checkpoints[0:num_to_remove]
1078
+
1079
+ logger.info(
1080
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1081
+ )
1082
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1083
+
1084
+ for removing_checkpoint in removing_checkpoints:
1085
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1086
+ shutil.rmtree(removing_checkpoint)
1087
+
1088
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1089
+ accelerator.save_state(save_path)
1090
+ logger.info(f"Saved state to {save_path}")
1091
+
1092
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1093
+ progress_bar.set_postfix(**logs)
1094
+
1095
+ if global_step >= args.max_train_steps:
1096
+ break
1097
+
1098
+ if accelerator.is_main_process:
1099
+ if args.validation_prompts is not None and epoch % args.validation_epochs == 0:
1100
+ if args.use_ema:
1101
+ # Store the UNet parameters temporarily and load the EMA parameters to perform inference.
1102
+ ema_unet.store(unet.parameters())
1103
+ ema_unet.copy_to(unet.parameters())
1104
+ log_validation(
1105
+ vae,
1106
+ text_encoder,
1107
+ tokenizer,
1108
+ unet,
1109
+ args,
1110
+ accelerator,
1111
+ weight_dtype,
1112
+ global_step,
1113
+ )
1114
+ if args.use_ema:
1115
+ # Switch back to the original UNet parameters.
1116
+ ema_unet.restore(unet.parameters())
1117
+
1118
+ # Create the pipeline using the trained modules and save it.
1119
+ accelerator.wait_for_everyone()
1120
+ if accelerator.is_main_process:
1121
+ unet = unwrap_model(unet)
1122
+ if args.use_ema:
1123
+ ema_unet.copy_to(unet.parameters())
1124
+
1125
+ pipeline = StableDiffusionPipeline.from_pretrained(
1126
+ args.pretrained_model_name_or_path,
1127
+ text_encoder=text_encoder,
1128
+ vae=vae,
1129
+ unet=unet,
1130
+ revision=args.revision,
1131
+ variant=args.variant,
1132
+ )
1133
+ pipeline.save_pretrained(args.output_dir)
1134
+
1135
+ # Run a final round of inference.
1136
+ images = []
1137
+ if args.validation_prompts is not None:
1138
+ logger.info("Running inference for collecting generated images...")
1139
+ pipeline = pipeline.to(accelerator.device)
1140
+ pipeline.torch_dtype = weight_dtype
1141
+ pipeline.set_progress_bar_config(disable=True)
1142
+
1143
+ if args.enable_xformers_memory_efficient_attention:
1144
+ pipeline.enable_xformers_memory_efficient_attention()
1145
+
1146
+ if args.seed is None:
1147
+ generator = None
1148
+ else:
1149
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
1150
+
1151
+ for i in range(len(args.validation_prompts)):
1152
+ with torch.autocast("cuda"):
1153
+ image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0]
1154
+ images.append(image)
1155
+
1156
+ if args.push_to_hub:
1157
+ save_model_card(args, repo_id, images, repo_folder=args.output_dir)
1158
+ upload_folder(
1159
+ repo_id=repo_id,
1160
+ folder_path=args.output_dir,
1161
+ commit_message="End of training",
1162
+ ignore_patterns=["step_*", "epoch_*"],
1163
+ )
1164
+
1165
+ accelerator.end_training()
1166
+
1167
+
1168
+ if __name__ == "__main__":
1169
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_flax.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
19
+ import math
20
+ import os
21
+ import random
22
+ from pathlib import Path
23
+
24
+ import jax
25
+ import jax.numpy as jnp
26
+ import numpy as np
27
+ import optax
28
+ import torch
29
+ import torch.utils.checkpoint
30
+ import transformers
31
+ from datasets import load_dataset
32
+ from flax import jax_utils
33
+ from flax.training import train_state
34
+ from flax.training.common_utils import shard
35
+ from huggingface_hub import create_repo, upload_folder
36
+ from torchvision import transforms
37
+ from tqdm.auto import tqdm
38
+ from transformers import CLIPImageProcessor, CLIPTokenizer, FlaxCLIPTextModel, set_seed
39
+
40
+ from diffusers import (
41
+ FlaxAutoencoderKL,
42
+ FlaxDDPMScheduler,
43
+ FlaxPNDMScheduler,
44
+ FlaxStableDiffusionPipeline,
45
+ FlaxUNet2DConditionModel,
46
+ )
47
+ from diffusers.pipelines.stable_diffusion import FlaxStableDiffusionSafetyChecker
48
+ from diffusers.utils import check_min_version
49
+
50
+
51
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
52
+ check_min_version("0.39.0.dev0")
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ def parse_args():
58
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
59
+ parser.add_argument(
60
+ "--pretrained_model_name_or_path",
61
+ type=str,
62
+ default=None,
63
+ required=True,
64
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
65
+ )
66
+ parser.add_argument(
67
+ "--revision",
68
+ type=str,
69
+ default=None,
70
+ required=False,
71
+ help="Revision of pretrained model identifier from huggingface.co/models.",
72
+ )
73
+ parser.add_argument(
74
+ "--variant",
75
+ type=str,
76
+ default=None,
77
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
78
+ )
79
+ parser.add_argument(
80
+ "--dataset_name",
81
+ type=str,
82
+ default=None,
83
+ help=(
84
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
85
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
86
+ " or to a folder containing files that 🤗 Datasets can understand."
87
+ ),
88
+ )
89
+ parser.add_argument(
90
+ "--dataset_config_name",
91
+ type=str,
92
+ default=None,
93
+ help="The config of the Dataset, leave as None if there's only one config.",
94
+ )
95
+ parser.add_argument(
96
+ "--train_data_dir",
97
+ type=str,
98
+ default=None,
99
+ help=(
100
+ "A folder containing the training data. Folder contents must follow the structure described in"
101
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
102
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
103
+ ),
104
+ )
105
+ parser.add_argument(
106
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
107
+ )
108
+ parser.add_argument(
109
+ "--caption_column",
110
+ type=str,
111
+ default="text",
112
+ help="The column of the dataset containing a caption or a list of captions.",
113
+ )
114
+ parser.add_argument(
115
+ "--max_train_samples",
116
+ type=int,
117
+ default=None,
118
+ help=(
119
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
120
+ "value if set."
121
+ ),
122
+ )
123
+ parser.add_argument(
124
+ "--output_dir",
125
+ type=str,
126
+ default="sd-model-finetuned",
127
+ help="The output directory where the model predictions and checkpoints will be written.",
128
+ )
129
+ parser.add_argument(
130
+ "--cache_dir",
131
+ type=str,
132
+ default=None,
133
+ help="The directory where the downloaded models and datasets will be stored.",
134
+ )
135
+ parser.add_argument("--seed", type=int, default=0, help="A seed for reproducible training.")
136
+ parser.add_argument(
137
+ "--resolution",
138
+ type=int,
139
+ default=512,
140
+ help=(
141
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
142
+ " resolution"
143
+ ),
144
+ )
145
+ parser.add_argument(
146
+ "--center_crop",
147
+ default=False,
148
+ action="store_true",
149
+ help=(
150
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
151
+ " cropped. The images will be resized to the resolution first before cropping."
152
+ ),
153
+ )
154
+ parser.add_argument(
155
+ "--random_flip",
156
+ action="store_true",
157
+ help="whether to randomly flip images horizontally",
158
+ )
159
+ parser.add_argument(
160
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
161
+ )
162
+ parser.add_argument("--num_train_epochs", type=int, default=100)
163
+ parser.add_argument(
164
+ "--max_train_steps",
165
+ type=int,
166
+ default=None,
167
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
168
+ )
169
+ parser.add_argument(
170
+ "--learning_rate",
171
+ type=float,
172
+ default=1e-4,
173
+ help="Initial learning rate (after the potential warmup period) to use.",
174
+ )
175
+ parser.add_argument(
176
+ "--scale_lr",
177
+ action="store_true",
178
+ default=False,
179
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
180
+ )
181
+ parser.add_argument(
182
+ "--lr_scheduler",
183
+ type=str,
184
+ default="constant",
185
+ help=(
186
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
187
+ ' "constant", "constant_with_warmup"]'
188
+ ),
189
+ )
190
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
191
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
192
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
193
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
194
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
195
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
196
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
197
+ parser.add_argument(
198
+ "--hub_model_id",
199
+ type=str,
200
+ default=None,
201
+ help="The name of the repository to keep in sync with the local `output_dir`.",
202
+ )
203
+ parser.add_argument(
204
+ "--logging_dir",
205
+ type=str,
206
+ default="logs",
207
+ help=(
208
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
209
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
210
+ ),
211
+ )
212
+ parser.add_argument(
213
+ "--report_to",
214
+ type=str,
215
+ default="tensorboard",
216
+ help=(
217
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
218
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
219
+ ),
220
+ )
221
+ parser.add_argument(
222
+ "--mixed_precision",
223
+ type=str,
224
+ default="no",
225
+ choices=["no", "fp16", "bf16"],
226
+ help=(
227
+ "Whether to use mixed precision. Choose"
228
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
229
+ "and an Nvidia Ampere GPU."
230
+ ),
231
+ )
232
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
233
+ parser.add_argument(
234
+ "--from_pt",
235
+ action="store_true",
236
+ default=False,
237
+ help="Flag to indicate whether to convert models from PyTorch.",
238
+ )
239
+
240
+ args = parser.parse_args()
241
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
242
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
243
+ args.local_rank = env_local_rank
244
+
245
+ # Sanity checks
246
+ if args.dataset_name is None and args.train_data_dir is None:
247
+ raise ValueError("Need either a dataset name or a training folder.")
248
+
249
+ return args
250
+
251
+
252
+ dataset_name_mapping = {
253
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
254
+ }
255
+
256
+
257
+ def get_params_to_save(params):
258
+ return jax.device_get(jax.tree_util.tree_map(lambda x: x[0], params))
259
+
260
+
261
+ def main():
262
+ args = parse_args()
263
+
264
+ if args.report_to == "wandb" and args.hub_token is not None:
265
+ raise ValueError(
266
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
267
+ " Please use `hf auth login` to authenticate with the Hub."
268
+ )
269
+
270
+ logging.basicConfig(
271
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
272
+ datefmt="%m/%d/%Y %H:%M:%S",
273
+ level=logging.INFO,
274
+ )
275
+ # Setup logging, we only want one process per machine to log things on the screen.
276
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
277
+ if jax.process_index() == 0:
278
+ transformers.utils.logging.set_verbosity_info()
279
+ else:
280
+ transformers.utils.logging.set_verbosity_error()
281
+
282
+ if args.seed is not None:
283
+ set_seed(args.seed)
284
+
285
+ # Handle the repository creation
286
+ if jax.process_index() == 0:
287
+ if args.output_dir is not None:
288
+ os.makedirs(args.output_dir, exist_ok=True)
289
+
290
+ if args.push_to_hub:
291
+ repo_id = create_repo(
292
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
293
+ ).repo_id
294
+
295
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
296
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
297
+
298
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
299
+ # download the dataset.
300
+ if args.dataset_name is not None:
301
+ # Downloading and loading a dataset from the hub.
302
+ dataset = load_dataset(
303
+ args.dataset_name, args.dataset_config_name, cache_dir=args.cache_dir, data_dir=args.train_data_dir
304
+ )
305
+ else:
306
+ data_files = {}
307
+ if args.train_data_dir is not None:
308
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
309
+ dataset = load_dataset(
310
+ "imagefolder",
311
+ data_files=data_files,
312
+ cache_dir=args.cache_dir,
313
+ )
314
+ # See more about loading custom images at
315
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
316
+
317
+ # Preprocessing the datasets.
318
+ # We need to tokenize inputs and targets.
319
+ column_names = dataset["train"].column_names
320
+
321
+ # 6. Get the column names for input/target.
322
+ dataset_columns = dataset_name_mapping.get(args.dataset_name, None)
323
+ if args.image_column is None:
324
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
325
+ else:
326
+ image_column = args.image_column
327
+ if image_column not in column_names:
328
+ raise ValueError(
329
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
330
+ )
331
+ if args.caption_column is None:
332
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
333
+ else:
334
+ caption_column = args.caption_column
335
+ if caption_column not in column_names:
336
+ raise ValueError(
337
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
338
+ )
339
+
340
+ # Preprocessing the datasets.
341
+ # We need to tokenize input captions and transform the images.
342
+ def tokenize_captions(examples, is_train=True):
343
+ captions = []
344
+ for caption in examples[caption_column]:
345
+ if isinstance(caption, str):
346
+ captions.append(caption)
347
+ elif isinstance(caption, (list, np.ndarray)):
348
+ # take a random caption if there are multiple
349
+ captions.append(random.choice(caption) if is_train else caption[0])
350
+ else:
351
+ raise ValueError(
352
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
353
+ )
354
+ inputs = tokenizer(captions, max_length=tokenizer.model_max_length, padding="do_not_pad", truncation=True)
355
+ input_ids = inputs.input_ids
356
+ return input_ids
357
+
358
+ train_transforms = transforms.Compose(
359
+ [
360
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
361
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
362
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
363
+ transforms.ToTensor(),
364
+ transforms.Normalize([0.5], [0.5]),
365
+ ]
366
+ )
367
+
368
+ def preprocess_train(examples):
369
+ images = [image.convert("RGB") for image in examples[image_column]]
370
+ examples["pixel_values"] = [train_transforms(image) for image in images]
371
+ examples["input_ids"] = tokenize_captions(examples)
372
+
373
+ return examples
374
+
375
+ if args.max_train_samples is not None:
376
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
377
+ # Set the training transforms
378
+ train_dataset = dataset["train"].with_transform(preprocess_train)
379
+
380
+ def collate_fn(examples):
381
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
382
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
383
+ input_ids = [example["input_ids"] for example in examples]
384
+
385
+ padded_tokens = tokenizer.pad(
386
+ {"input_ids": input_ids}, padding="max_length", max_length=tokenizer.model_max_length, return_tensors="pt"
387
+ )
388
+ batch = {
389
+ "pixel_values": pixel_values,
390
+ "input_ids": padded_tokens.input_ids,
391
+ }
392
+ batch = {k: v.numpy() for k, v in batch.items()}
393
+
394
+ return batch
395
+
396
+ total_train_batch_size = args.train_batch_size * jax.local_device_count()
397
+ train_dataloader = torch.utils.data.DataLoader(
398
+ train_dataset, shuffle=True, collate_fn=collate_fn, batch_size=total_train_batch_size, drop_last=True
399
+ )
400
+
401
+ weight_dtype = jnp.float32
402
+ if args.mixed_precision == "fp16":
403
+ weight_dtype = jnp.float16
404
+ elif args.mixed_precision == "bf16":
405
+ weight_dtype = jnp.bfloat16
406
+
407
+ # Load models and create wrapper for stable diffusion
408
+ tokenizer = CLIPTokenizer.from_pretrained(
409
+ args.pretrained_model_name_or_path,
410
+ from_pt=args.from_pt,
411
+ revision=args.revision,
412
+ subfolder="tokenizer",
413
+ )
414
+ text_encoder = FlaxCLIPTextModel.from_pretrained(
415
+ args.pretrained_model_name_or_path,
416
+ from_pt=args.from_pt,
417
+ revision=args.revision,
418
+ subfolder="text_encoder",
419
+ dtype=weight_dtype,
420
+ )
421
+ vae, vae_params = FlaxAutoencoderKL.from_pretrained(
422
+ args.pretrained_model_name_or_path,
423
+ from_pt=args.from_pt,
424
+ revision=args.revision,
425
+ subfolder="vae",
426
+ dtype=weight_dtype,
427
+ )
428
+ unet, unet_params = FlaxUNet2DConditionModel.from_pretrained(
429
+ args.pretrained_model_name_or_path,
430
+ from_pt=args.from_pt,
431
+ revision=args.revision,
432
+ subfolder="unet",
433
+ dtype=weight_dtype,
434
+ )
435
+
436
+ # Optimization
437
+ if args.scale_lr:
438
+ args.learning_rate = args.learning_rate * total_train_batch_size
439
+
440
+ constant_scheduler = optax.constant_schedule(args.learning_rate)
441
+
442
+ adamw = optax.adamw(
443
+ learning_rate=constant_scheduler,
444
+ b1=args.adam_beta1,
445
+ b2=args.adam_beta2,
446
+ eps=args.adam_epsilon,
447
+ weight_decay=args.adam_weight_decay,
448
+ )
449
+
450
+ optimizer = optax.chain(
451
+ optax.clip_by_global_norm(args.max_grad_norm),
452
+ adamw,
453
+ )
454
+
455
+ state = train_state.TrainState.create(apply_fn=unet.__call__, params=unet_params, tx=optimizer)
456
+
457
+ noise_scheduler = FlaxDDPMScheduler(
458
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000
459
+ )
460
+ noise_scheduler_state = noise_scheduler.create_state()
461
+
462
+ # Initialize our training
463
+ rng = jax.random.PRNGKey(args.seed)
464
+ train_rngs = jax.random.split(rng, jax.local_device_count())
465
+
466
+ def train_step(state, text_encoder_params, vae_params, batch, train_rng):
467
+ dropout_rng, sample_rng, new_train_rng = jax.random.split(train_rng, 3)
468
+
469
+ def compute_loss(params):
470
+ # Convert images to latent space
471
+ vae_outputs = vae.apply(
472
+ {"params": vae_params}, batch["pixel_values"], deterministic=True, method=vae.encode
473
+ )
474
+ latents = vae_outputs.latent_dist.sample(sample_rng)
475
+ # (NHWC) -> (NCHW)
476
+ latents = jnp.transpose(latents, (0, 3, 1, 2))
477
+ latents = latents * vae.config.scaling_factor
478
+
479
+ # Sample noise that we'll add to the latents
480
+ noise_rng, timestep_rng = jax.random.split(sample_rng)
481
+ noise = jax.random.normal(noise_rng, latents.shape)
482
+ # Sample a random timestep for each image
483
+ bsz = latents.shape[0]
484
+ timesteps = jax.random.randint(
485
+ timestep_rng,
486
+ (bsz,),
487
+ 0,
488
+ noise_scheduler.config.num_train_timesteps,
489
+ )
490
+
491
+ # Add noise to the latents according to the noise magnitude at each timestep
492
+ # (this is the forward diffusion process)
493
+ noisy_latents = noise_scheduler.add_noise(noise_scheduler_state, latents, noise, timesteps)
494
+
495
+ # Get the text embedding for conditioning
496
+ encoder_hidden_states = text_encoder(
497
+ batch["input_ids"],
498
+ params=text_encoder_params,
499
+ train=False,
500
+ )[0]
501
+
502
+ # Predict the noise residual and compute loss
503
+ model_pred = unet.apply(
504
+ {"params": params}, noisy_latents, timesteps, encoder_hidden_states, train=True
505
+ ).sample
506
+
507
+ # Get the target for loss depending on the prediction type
508
+ if noise_scheduler.config.prediction_type == "epsilon":
509
+ target = noise
510
+ elif noise_scheduler.config.prediction_type == "v_prediction":
511
+ target = noise_scheduler.get_velocity(noise_scheduler_state, latents, noise, timesteps)
512
+ else:
513
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
514
+
515
+ loss = (target - model_pred) ** 2
516
+ loss = loss.mean()
517
+
518
+ return loss
519
+
520
+ grad_fn = jax.value_and_grad(compute_loss)
521
+ loss, grad = grad_fn(state.params)
522
+ grad = jax.lax.pmean(grad, "batch")
523
+
524
+ new_state = state.apply_gradients(grads=grad)
525
+
526
+ metrics = {"loss": loss}
527
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
528
+
529
+ return new_state, metrics, new_train_rng
530
+
531
+ # Create parallel version of the train step
532
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
533
+
534
+ # Replicate the train state on each device
535
+ state = jax_utils.replicate(state)
536
+ text_encoder_params = jax_utils.replicate(text_encoder.params)
537
+ vae_params = jax_utils.replicate(vae_params)
538
+
539
+ # Train!
540
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader))
541
+
542
+ # Scheduler and math around the number of training steps.
543
+ if args.max_train_steps is None:
544
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
545
+
546
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
547
+
548
+ logger.info("***** Running training *****")
549
+ logger.info(f" Num examples = {len(train_dataset)}")
550
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
551
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
552
+ logger.info(f" Total train batch size (w. parallel & distributed) = {total_train_batch_size}")
553
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
554
+
555
+ global_step = 0
556
+
557
+ epochs = tqdm(range(args.num_train_epochs), desc="Epoch ... ", position=0)
558
+ for epoch in epochs:
559
+ # ======================== Training ================================
560
+
561
+ train_metrics = []
562
+
563
+ steps_per_epoch = len(train_dataset) // total_train_batch_size
564
+ train_step_progress_bar = tqdm(total=steps_per_epoch, desc="Training...", position=1, leave=False)
565
+ # train
566
+ for batch in train_dataloader:
567
+ batch = shard(batch)
568
+ state, train_metric, train_rngs = p_train_step(state, text_encoder_params, vae_params, batch, train_rngs)
569
+ train_metrics.append(train_metric)
570
+
571
+ train_step_progress_bar.update(1)
572
+
573
+ global_step += 1
574
+ if global_step >= args.max_train_steps:
575
+ break
576
+
577
+ train_metric = jax_utils.unreplicate(train_metric)
578
+
579
+ train_step_progress_bar.close()
580
+ epochs.write(f"Epoch... ({epoch + 1}/{args.num_train_epochs} | Loss: {train_metric['loss']})")
581
+
582
+ # Create the pipeline using using the trained modules and save it.
583
+ if jax.process_index() == 0:
584
+ scheduler = FlaxPNDMScheduler(
585
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", skip_prk_steps=True
586
+ )
587
+ safety_checker = FlaxStableDiffusionSafetyChecker.from_pretrained(
588
+ "CompVis/stable-diffusion-safety-checker", from_pt=True
589
+ )
590
+ pipeline = FlaxStableDiffusionPipeline(
591
+ text_encoder=text_encoder,
592
+ vae=vae,
593
+ unet=unet,
594
+ tokenizer=tokenizer,
595
+ scheduler=scheduler,
596
+ safety_checker=safety_checker,
597
+ feature_extractor=CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32"),
598
+ )
599
+
600
+ pipeline.save_pretrained(
601
+ args.output_dir,
602
+ params={
603
+ "text_encoder": get_params_to_save(text_encoder_params),
604
+ "vae": get_params_to_save(vae_params),
605
+ "unet": get_params_to_save(state.params),
606
+ "safety_checker": safety_checker.params,
607
+ },
608
+ )
609
+
610
+ if args.push_to_hub:
611
+ upload_folder(
612
+ repo_id=repo_id,
613
+ folder_path=args.output_dir,
614
+ commit_message="End of training",
615
+ ignore_patterns=["step_*", "epoch_*"],
616
+ )
617
+
618
+
619
+ if __name__ == "__main__":
620
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_lora.py ADDED
@@ -0,0 +1,1039 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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
+ """Fine-tuning script for Stable Diffusion for text2image with support for LoRA."""
17
+
18
+ import argparse
19
+ import logging
20
+ import math
21
+ import os
22
+ import random
23
+ import shutil
24
+ from contextlib import nullcontext
25
+ from pathlib import Path
26
+
27
+ import datasets
28
+ import numpy as np
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ import transformers
33
+ from accelerate import Accelerator
34
+ from accelerate.logging import get_logger
35
+ from accelerate.utils import ProjectConfiguration, set_seed
36
+ from datasets import load_dataset
37
+ from huggingface_hub import create_repo, upload_folder
38
+ from packaging import version
39
+ from peft import LoraConfig
40
+ from peft.utils import get_peft_model_state_dict, set_peft_model_state_dict
41
+ from torchvision import transforms
42
+ from tqdm.auto import tqdm
43
+ from transformers import CLIPTextModel, CLIPTokenizer
44
+
45
+ import diffusers
46
+ from diffusers import AutoencoderKL, DDPMScheduler, DiffusionPipeline, StableDiffusionPipeline, UNet2DConditionModel
47
+ from diffusers.optimization import get_scheduler
48
+ from diffusers.training_utils import cast_training_params, compute_snr
49
+ from diffusers.utils import (
50
+ check_min_version,
51
+ convert_state_dict_to_diffusers,
52
+ convert_unet_state_dict_to_peft,
53
+ is_wandb_available,
54
+ )
55
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
56
+ from diffusers.utils.import_utils import is_xformers_available
57
+ from diffusers.utils.torch_utils import is_compiled_module
58
+
59
+
60
+ if is_wandb_available():
61
+ import wandb
62
+
63
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
64
+ check_min_version("0.39.0.dev0")
65
+
66
+ logger = get_logger(__name__, log_level="INFO")
67
+
68
+
69
+ def save_model_card(
70
+ repo_id: str,
71
+ images: list = None,
72
+ base_model: str = None,
73
+ dataset_name: str = None,
74
+ repo_folder: str = None,
75
+ ):
76
+ img_str = ""
77
+ if images is not None:
78
+ for i, image in enumerate(images):
79
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
80
+ img_str += f"![img_{i}](./image_{i}.png)\n"
81
+
82
+ model_description = f"""
83
+ # LoRA text2image fine-tuning - {repo_id}
84
+ These are LoRA adaption weights for {base_model}. The weights were fine-tuned on the {dataset_name} dataset. You can find some example images in the following. \n
85
+ {img_str}
86
+ """
87
+
88
+ model_card = load_or_create_model_card(
89
+ repo_id_or_path=repo_id,
90
+ from_training=True,
91
+ license="creativeml-openrail-m",
92
+ base_model=base_model,
93
+ model_description=model_description,
94
+ inference=True,
95
+ )
96
+
97
+ tags = [
98
+ "stable-diffusion",
99
+ "stable-diffusion-diffusers",
100
+ "text-to-image",
101
+ "diffusers",
102
+ "diffusers-training",
103
+ "lora",
104
+ ]
105
+ model_card = populate_model_card(model_card, tags=tags)
106
+
107
+ model_card.save(os.path.join(repo_folder, "README.md"))
108
+
109
+
110
+ def log_validation(
111
+ pipeline,
112
+ args,
113
+ accelerator,
114
+ epoch,
115
+ is_final_validation=False,
116
+ ):
117
+ logger.info(
118
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
119
+ f" {args.validation_prompt}."
120
+ )
121
+ pipeline = pipeline.to(accelerator.device)
122
+ pipeline.set_progress_bar_config(disable=True)
123
+ generator = torch.Generator(device=accelerator.device)
124
+ if args.seed is not None:
125
+ generator = generator.manual_seed(args.seed)
126
+ images = []
127
+ if torch.backends.mps.is_available():
128
+ autocast_ctx = nullcontext()
129
+ else:
130
+ autocast_ctx = torch.autocast(accelerator.device.type)
131
+
132
+ with autocast_ctx:
133
+ for _ in range(args.num_validation_images):
134
+ images.append(pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0])
135
+
136
+ for tracker in accelerator.trackers:
137
+ phase_name = "test" if is_final_validation else "validation"
138
+ if tracker.name == "tensorboard":
139
+ np_images = np.stack([np.asarray(img) for img in images])
140
+ tracker.writer.add_images(phase_name, np_images, epoch, dataformats="NHWC")
141
+ if tracker.name == "wandb":
142
+ tracker.log(
143
+ {
144
+ phase_name: [
145
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
146
+ ]
147
+ }
148
+ )
149
+ return images
150
+
151
+
152
+ def parse_args():
153
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
154
+ parser.add_argument(
155
+ "--pretrained_model_name_or_path",
156
+ type=str,
157
+ default=None,
158
+ required=True,
159
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
160
+ )
161
+ parser.add_argument(
162
+ "--revision",
163
+ type=str,
164
+ default=None,
165
+ required=False,
166
+ help="Revision of pretrained model identifier from huggingface.co/models.",
167
+ )
168
+ parser.add_argument(
169
+ "--variant",
170
+ type=str,
171
+ default=None,
172
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
173
+ )
174
+ parser.add_argument(
175
+ "--dataset_name",
176
+ type=str,
177
+ default=None,
178
+ help=(
179
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
180
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
181
+ " or to a folder containing files that 🤗 Datasets can understand."
182
+ ),
183
+ )
184
+ parser.add_argument(
185
+ "--dataset_config_name",
186
+ type=str,
187
+ default=None,
188
+ help="The config of the Dataset, leave as None if there's only one config.",
189
+ )
190
+ parser.add_argument(
191
+ "--train_data_dir",
192
+ type=str,
193
+ default=None,
194
+ help=(
195
+ "A folder containing the training data. Folder contents must follow the structure described in"
196
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
197
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
198
+ ),
199
+ )
200
+ parser.add_argument(
201
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
202
+ )
203
+ parser.add_argument(
204
+ "--caption_column",
205
+ type=str,
206
+ default="text",
207
+ help="The column of the dataset containing a caption or a list of captions.",
208
+ )
209
+ parser.add_argument(
210
+ "--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
211
+ )
212
+ parser.add_argument(
213
+ "--num_validation_images",
214
+ type=int,
215
+ default=4,
216
+ help="Number of images that should be generated during validation with `validation_prompt`.",
217
+ )
218
+ parser.add_argument(
219
+ "--validation_epochs",
220
+ type=int,
221
+ default=1,
222
+ help=(
223
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
224
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
225
+ ),
226
+ )
227
+ parser.add_argument(
228
+ "--max_train_samples",
229
+ type=int,
230
+ default=None,
231
+ help=(
232
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
233
+ "value if set."
234
+ ),
235
+ )
236
+ parser.add_argument(
237
+ "--output_dir",
238
+ type=str,
239
+ default="sd-model-finetuned-lora",
240
+ help="The output directory where the model predictions and checkpoints will be written.",
241
+ )
242
+ parser.add_argument(
243
+ "--cache_dir",
244
+ type=str,
245
+ default=None,
246
+ help="The directory where the downloaded models and datasets will be stored.",
247
+ )
248
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
249
+ parser.add_argument(
250
+ "--resolution",
251
+ type=int,
252
+ default=512,
253
+ help=(
254
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
255
+ " resolution"
256
+ ),
257
+ )
258
+ parser.add_argument(
259
+ "--center_crop",
260
+ default=False,
261
+ action="store_true",
262
+ help=(
263
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
264
+ " cropped. The images will be resized to the resolution first before cropping."
265
+ ),
266
+ )
267
+ parser.add_argument(
268
+ "--random_flip",
269
+ action="store_true",
270
+ help="whether to randomly flip images horizontally",
271
+ )
272
+ parser.add_argument(
273
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
274
+ )
275
+ parser.add_argument("--num_train_epochs", type=int, default=100)
276
+ parser.add_argument(
277
+ "--max_train_steps",
278
+ type=int,
279
+ default=None,
280
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
281
+ )
282
+ parser.add_argument(
283
+ "--gradient_accumulation_steps",
284
+ type=int,
285
+ default=1,
286
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
287
+ )
288
+ parser.add_argument(
289
+ "--gradient_checkpointing",
290
+ action="store_true",
291
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
292
+ )
293
+ parser.add_argument(
294
+ "--learning_rate",
295
+ type=float,
296
+ default=1e-4,
297
+ help="Initial learning rate (after the potential warmup period) to use.",
298
+ )
299
+ parser.add_argument(
300
+ "--scale_lr",
301
+ action="store_true",
302
+ default=False,
303
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
304
+ )
305
+ parser.add_argument(
306
+ "--lr_scheduler",
307
+ type=str,
308
+ default="constant",
309
+ help=(
310
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
311
+ ' "constant", "constant_with_warmup"]'
312
+ ),
313
+ )
314
+ parser.add_argument(
315
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
316
+ )
317
+ parser.add_argument(
318
+ "--snr_gamma",
319
+ type=float,
320
+ default=None,
321
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
322
+ "More details here: https://huggingface.co/papers/2303.09556.",
323
+ )
324
+ parser.add_argument(
325
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
326
+ )
327
+ parser.add_argument(
328
+ "--allow_tf32",
329
+ action="store_true",
330
+ help=(
331
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
332
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
333
+ ),
334
+ )
335
+ parser.add_argument(
336
+ "--dataloader_num_workers",
337
+ type=int,
338
+ default=0,
339
+ help=(
340
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
341
+ ),
342
+ )
343
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
344
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
345
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
346
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
347
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
348
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
349
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
350
+ parser.add_argument(
351
+ "--prediction_type",
352
+ type=str,
353
+ default=None,
354
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
355
+ )
356
+ parser.add_argument(
357
+ "--hub_model_id",
358
+ type=str,
359
+ default=None,
360
+ help="The name of the repository to keep in sync with the local `output_dir`.",
361
+ )
362
+ parser.add_argument(
363
+ "--logging_dir",
364
+ type=str,
365
+ default="logs",
366
+ help=(
367
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
368
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
369
+ ),
370
+ )
371
+ parser.add_argument(
372
+ "--mixed_precision",
373
+ type=str,
374
+ default=None,
375
+ choices=["no", "fp16", "bf16"],
376
+ help=(
377
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
378
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
379
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
380
+ ),
381
+ )
382
+ parser.add_argument(
383
+ "--report_to",
384
+ type=str,
385
+ default="tensorboard",
386
+ help=(
387
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
388
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
389
+ ),
390
+ )
391
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
392
+ parser.add_argument(
393
+ "--checkpointing_steps",
394
+ type=int,
395
+ default=500,
396
+ help=(
397
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
398
+ " training using `--resume_from_checkpoint`."
399
+ ),
400
+ )
401
+ parser.add_argument(
402
+ "--checkpoints_total_limit",
403
+ type=int,
404
+ default=None,
405
+ help=("Max number of checkpoints to store."),
406
+ )
407
+ parser.add_argument(
408
+ "--resume_from_checkpoint",
409
+ type=str,
410
+ default=None,
411
+ help=(
412
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
413
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
414
+ ),
415
+ )
416
+ parser.add_argument(
417
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
418
+ )
419
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
420
+ parser.add_argument(
421
+ "--rank",
422
+ type=int,
423
+ default=4,
424
+ help=("The dimension of the LoRA update matrices."),
425
+ )
426
+ parser.add_argument(
427
+ "--image_interpolation_mode",
428
+ type=str,
429
+ default="lanczos",
430
+ choices=[
431
+ f.lower() for f in dir(transforms.InterpolationMode) if not f.startswith("__") and not f.endswith("__")
432
+ ],
433
+ help="The image interpolation method to use for resizing images.",
434
+ )
435
+
436
+ args = parser.parse_args()
437
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
438
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
439
+ args.local_rank = env_local_rank
440
+
441
+ # Sanity checks
442
+ if args.dataset_name is None and args.train_data_dir is None:
443
+ raise ValueError("Need either a dataset name or a training folder.")
444
+
445
+ return args
446
+
447
+
448
+ DATASET_NAME_MAPPING = {
449
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
450
+ }
451
+
452
+
453
+ def main():
454
+ args = parse_args()
455
+ if args.report_to == "wandb" and args.hub_token is not None:
456
+ raise ValueError(
457
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
458
+ " Please use `hf auth login` to authenticate with the Hub."
459
+ )
460
+
461
+ logging_dir = Path(args.output_dir, args.logging_dir)
462
+
463
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
464
+
465
+ accelerator = Accelerator(
466
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
467
+ mixed_precision=args.mixed_precision,
468
+ log_with=args.report_to,
469
+ project_config=accelerator_project_config,
470
+ )
471
+
472
+ # Disable AMP for MPS.
473
+ if torch.backends.mps.is_available():
474
+ accelerator.native_amp = False
475
+
476
+ # Make one log on every process with the configuration for debugging.
477
+ logging.basicConfig(
478
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
479
+ datefmt="%m/%d/%Y %H:%M:%S",
480
+ level=logging.INFO,
481
+ )
482
+ logger.info(accelerator.state, main_process_only=False)
483
+ if accelerator.is_local_main_process:
484
+ datasets.utils.logging.set_verbosity_warning()
485
+ transformers.utils.logging.set_verbosity_warning()
486
+ diffusers.utils.logging.set_verbosity_info()
487
+ else:
488
+ datasets.utils.logging.set_verbosity_error()
489
+ transformers.utils.logging.set_verbosity_error()
490
+ diffusers.utils.logging.set_verbosity_error()
491
+
492
+ # If passed along, set the training seed now.
493
+ if args.seed is not None:
494
+ set_seed(args.seed)
495
+
496
+ # Handle the repository creation
497
+ if accelerator.is_main_process:
498
+ if args.output_dir is not None:
499
+ os.makedirs(args.output_dir, exist_ok=True)
500
+
501
+ if args.push_to_hub:
502
+ repo_id = create_repo(
503
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
504
+ ).repo_id
505
+ # Load scheduler, tokenizer and models.
506
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
507
+ tokenizer = CLIPTokenizer.from_pretrained(
508
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
509
+ )
510
+ text_encoder = CLIPTextModel.from_pretrained(
511
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
512
+ )
513
+ vae = AutoencoderKL.from_pretrained(
514
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
515
+ )
516
+ unet = UNet2DConditionModel.from_pretrained(
517
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
518
+ )
519
+ # freeze parameters of models to save more memory
520
+ unet.requires_grad_(False)
521
+ vae.requires_grad_(False)
522
+ text_encoder.requires_grad_(False)
523
+
524
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
525
+ # as these weights are only used for inference, keeping weights in full precision is not required.
526
+ weight_dtype = torch.float32
527
+ if accelerator.mixed_precision == "fp16":
528
+ weight_dtype = torch.float16
529
+ elif accelerator.mixed_precision == "bf16":
530
+ weight_dtype = torch.bfloat16
531
+
532
+ unet_lora_config = LoraConfig(
533
+ r=args.rank,
534
+ lora_alpha=args.rank,
535
+ init_lora_weights="gaussian",
536
+ target_modules=["to_k", "to_q", "to_v", "to_out.0"],
537
+ )
538
+
539
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
540
+ unet.to(accelerator.device, dtype=weight_dtype)
541
+ vae.to(accelerator.device, dtype=weight_dtype)
542
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
543
+
544
+ # Add adapter and make sure the trainable params are in float32.
545
+ unet.add_adapter(unet_lora_config)
546
+ if args.mixed_precision == "fp16":
547
+ # only upcast trainable parameters (LoRA) into fp32
548
+ cast_training_params(unet, dtype=torch.float32)
549
+
550
+ if args.enable_xformers_memory_efficient_attention:
551
+ if is_xformers_available():
552
+ import xformers
553
+
554
+ xformers_version = version.parse(xformers.__version__)
555
+ if xformers_version == version.parse("0.0.16"):
556
+ logger.warning(
557
+ "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."
558
+ )
559
+ unet.enable_xformers_memory_efficient_attention()
560
+ else:
561
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
562
+
563
+ lora_layers = filter(lambda p: p.requires_grad, unet.parameters())
564
+
565
+ if args.gradient_checkpointing:
566
+ unet.enable_gradient_checkpointing()
567
+
568
+ # Enable TF32 for faster training on Ampere GPUs,
569
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
570
+ if args.allow_tf32:
571
+ torch.backends.cuda.matmul.allow_tf32 = True
572
+
573
+ if args.scale_lr:
574
+ args.learning_rate = (
575
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
576
+ )
577
+
578
+ # Initialize the optimizer
579
+ if args.use_8bit_adam:
580
+ try:
581
+ import bitsandbytes as bnb
582
+ except ImportError:
583
+ raise ImportError(
584
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
585
+ )
586
+
587
+ optimizer_cls = bnb.optim.AdamW8bit
588
+ else:
589
+ optimizer_cls = torch.optim.AdamW
590
+
591
+ optimizer = optimizer_cls(
592
+ lora_layers,
593
+ lr=args.learning_rate,
594
+ betas=(args.adam_beta1, args.adam_beta2),
595
+ weight_decay=args.adam_weight_decay,
596
+ eps=args.adam_epsilon,
597
+ )
598
+
599
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
600
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
601
+
602
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
603
+ # download the dataset.
604
+ if args.dataset_name is not None:
605
+ # Downloading and loading a dataset from the hub.
606
+ dataset = load_dataset(
607
+ args.dataset_name,
608
+ args.dataset_config_name,
609
+ cache_dir=args.cache_dir,
610
+ data_dir=args.train_data_dir,
611
+ )
612
+ else:
613
+ data_files = {}
614
+ if args.train_data_dir is not None:
615
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
616
+ dataset = load_dataset(
617
+ "imagefolder",
618
+ data_files=data_files,
619
+ cache_dir=args.cache_dir,
620
+ )
621
+ # See more about loading custom images at
622
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
623
+
624
+ # Preprocessing the datasets.
625
+ # We need to tokenize inputs and targets.
626
+ column_names = dataset["train"].column_names
627
+
628
+ # 6. Get the column names for input/target.
629
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
630
+ if args.image_column is None:
631
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
632
+ else:
633
+ image_column = args.image_column
634
+ if image_column not in column_names:
635
+ raise ValueError(
636
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
637
+ )
638
+ if args.caption_column is None:
639
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
640
+ else:
641
+ caption_column = args.caption_column
642
+ if caption_column not in column_names:
643
+ raise ValueError(
644
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
645
+ )
646
+
647
+ # Preprocessing the datasets.
648
+ # We need to tokenize input captions and transform the images.
649
+ def tokenize_captions(examples, is_train=True):
650
+ captions = []
651
+ for caption in examples[caption_column]:
652
+ if isinstance(caption, str):
653
+ captions.append(caption)
654
+ elif isinstance(caption, (list, np.ndarray)):
655
+ # take a random caption if there are multiple
656
+ captions.append(random.choice(caption) if is_train else caption[0])
657
+ else:
658
+ raise ValueError(
659
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
660
+ )
661
+ inputs = tokenizer(
662
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
663
+ )
664
+ return inputs.input_ids
665
+
666
+ # Get the specified interpolation method from the args
667
+ interpolation = getattr(transforms.InterpolationMode, args.image_interpolation_mode.upper(), None)
668
+
669
+ # Raise an error if the interpolation method is invalid
670
+ if interpolation is None:
671
+ raise ValueError(f"Unsupported interpolation mode {args.image_interpolation_mode}.")
672
+
673
+ # Data preprocessing transformations
674
+ train_transforms = transforms.Compose(
675
+ [
676
+ transforms.Resize(args.resolution, interpolation=interpolation), # Use dynamic interpolation method
677
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
678
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
679
+ transforms.ToTensor(),
680
+ transforms.Normalize([0.5], [0.5]),
681
+ ]
682
+ )
683
+
684
+ def unwrap_model(model):
685
+ model = accelerator.unwrap_model(model)
686
+ model = model._orig_mod if is_compiled_module(model) else model
687
+ return model
688
+
689
+ def preprocess_train(examples):
690
+ images = [image.convert("RGB") for image in examples[image_column]]
691
+ examples["pixel_values"] = [train_transforms(image) for image in images]
692
+ examples["input_ids"] = tokenize_captions(examples)
693
+ return examples
694
+
695
+ with accelerator.main_process_first():
696
+ if args.max_train_samples is not None:
697
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
698
+ # Set the training transforms
699
+ train_dataset = dataset["train"].with_transform(preprocess_train)
700
+
701
+ def collate_fn(examples):
702
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
703
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
704
+ input_ids = torch.stack([example["input_ids"] for example in examples])
705
+ return {"pixel_values": pixel_values, "input_ids": input_ids}
706
+
707
+ # DataLoaders creation:
708
+ train_dataloader = torch.utils.data.DataLoader(
709
+ train_dataset,
710
+ shuffle=True,
711
+ collate_fn=collate_fn,
712
+ batch_size=args.train_batch_size,
713
+ num_workers=args.dataloader_num_workers,
714
+ )
715
+
716
+ def save_model_hook(models, weights, output_dir):
717
+ if accelerator.is_main_process:
718
+ unet_lora_layers_to_save = None
719
+
720
+ for model in models:
721
+ if isinstance(model, type(unwrap_model(unet))):
722
+ unet_lora_layers_to_save = get_peft_model_state_dict(model)
723
+ else:
724
+ raise ValueError(f"Unexpected save model: {model.__class__}")
725
+
726
+ # make sure to pop weight so that corresponding model is not saved again
727
+ weights.pop()
728
+
729
+ StableDiffusionPipeline.save_lora_weights(
730
+ save_directory=output_dir,
731
+ unet_lora_layers=unet_lora_layers_to_save,
732
+ safe_serialization=True,
733
+ )
734
+
735
+ def load_model_hook(models, input_dir):
736
+ unet_ = None
737
+
738
+ while len(models) > 0:
739
+ model = models.pop()
740
+ if isinstance(model, type(unwrap_model(unet))):
741
+ unet_ = model
742
+ else:
743
+ raise ValueError(f"unexpected save model: {model.__class__}")
744
+
745
+ # returns a tuple of state dictionary and network alphas
746
+ lora_state_dict, network_alphas = StableDiffusionPipeline.lora_state_dict(input_dir)
747
+
748
+ unet_state_dict = {f"{k.replace('unet.', '')}": v for k, v in lora_state_dict.items() if k.startswith("unet.")}
749
+ unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
750
+ incompatible_keys = set_peft_model_state_dict(unet_, unet_state_dict, adapter_name="default")
751
+
752
+ if incompatible_keys is not None:
753
+ # check only for unexpected keys
754
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
755
+ # throw warning if some unexpected keys are found and continue loading
756
+ if unexpected_keys:
757
+ logger.warning(
758
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
759
+ f" {unexpected_keys}. "
760
+ )
761
+
762
+ # Make sure the trainable params are in float32
763
+ if args.mixed_precision in ["fp16"]:
764
+ cast_training_params([unet_], dtype=torch.float32)
765
+
766
+ # Scheduler and math around the number of training steps.
767
+ # Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
768
+ num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
769
+ if args.max_train_steps is None:
770
+ len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
771
+ num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
772
+ num_training_steps_for_scheduler = (
773
+ args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
774
+ )
775
+ else:
776
+ num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
777
+
778
+ lr_scheduler = get_scheduler(
779
+ args.lr_scheduler,
780
+ optimizer=optimizer,
781
+ num_warmup_steps=num_warmup_steps_for_scheduler,
782
+ num_training_steps=num_training_steps_for_scheduler,
783
+ )
784
+
785
+ # Prepare everything with our `accelerator`.
786
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
787
+ unet, optimizer, train_dataloader, lr_scheduler
788
+ )
789
+
790
+ # Register the hooks for efficient saving and loading of LoRA weights
791
+ accelerator.register_save_state_pre_hook(save_model_hook)
792
+ accelerator.register_load_state_pre_hook(load_model_hook)
793
+
794
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
795
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
796
+ if args.max_train_steps is None:
797
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
798
+ if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
799
+ logger.warning(
800
+ f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
801
+ f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
802
+ f"This inconsistency may result in the learning rate scheduler not functioning properly."
803
+ )
804
+ # Afterwards we recalculate our number of training epochs
805
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
806
+
807
+ # We need to initialize the trackers we use, and also store our configuration.
808
+ # The trackers initializes automatically on the main process.
809
+ if accelerator.is_main_process:
810
+ accelerator.init_trackers("text2image-fine-tune", config=vars(args))
811
+
812
+ # Train!
813
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
814
+
815
+ logger.info("***** Running training *****")
816
+ logger.info(f" Num examples = {len(train_dataset)}")
817
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
818
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
819
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
820
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
821
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
822
+ global_step = 0
823
+ first_epoch = 0
824
+
825
+ # Potentially load in the weights and states from a previous save
826
+ if args.resume_from_checkpoint:
827
+ if args.resume_from_checkpoint != "latest":
828
+ path = os.path.basename(args.resume_from_checkpoint)
829
+ else:
830
+ # Get the most recent checkpoint
831
+ dirs = os.listdir(args.output_dir)
832
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
833
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
834
+ path = dirs[-1] if len(dirs) > 0 else None
835
+
836
+ if path is None:
837
+ accelerator.print(
838
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
839
+ )
840
+ args.resume_from_checkpoint = None
841
+ initial_global_step = 0
842
+ else:
843
+ accelerator.print(f"Resuming from checkpoint {path}")
844
+ accelerator.load_state(os.path.join(args.output_dir, path))
845
+ global_step = int(path.split("-")[1])
846
+
847
+ initial_global_step = global_step
848
+ first_epoch = global_step // num_update_steps_per_epoch
849
+ else:
850
+ initial_global_step = 0
851
+
852
+ progress_bar = tqdm(
853
+ range(0, args.max_train_steps),
854
+ initial=initial_global_step,
855
+ desc="Steps",
856
+ # Only show the progress bar once on each machine.
857
+ disable=not accelerator.is_local_main_process,
858
+ )
859
+
860
+ for epoch in range(first_epoch, args.num_train_epochs):
861
+ unet.train()
862
+ train_loss = 0.0
863
+ for step, batch in enumerate(train_dataloader):
864
+ with accelerator.accumulate(unet):
865
+ # Convert images to latent space
866
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
867
+ latents = latents * vae.config.scaling_factor
868
+
869
+ # Sample noise that we'll add to the latents
870
+ noise = torch.randn_like(latents)
871
+ if args.noise_offset:
872
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
873
+ noise += args.noise_offset * torch.randn(
874
+ (latents.shape[0], latents.shape[1], 1, 1), device=latents.device
875
+ )
876
+
877
+ bsz = latents.shape[0]
878
+ # Sample a random timestep for each image
879
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
880
+ timesteps = timesteps.long()
881
+
882
+ # Add noise to the latents according to the noise magnitude at each timestep
883
+ # (this is the forward diffusion process)
884
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
885
+
886
+ # Get the text embedding for conditioning
887
+ encoder_hidden_states = text_encoder(batch["input_ids"], return_dict=False)[0]
888
+
889
+ # Get the target for loss depending on the prediction type
890
+ if args.prediction_type is not None:
891
+ # set prediction_type of scheduler if defined
892
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
893
+
894
+ if noise_scheduler.config.prediction_type == "epsilon":
895
+ target = noise
896
+ elif noise_scheduler.config.prediction_type == "v_prediction":
897
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
898
+ else:
899
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
900
+
901
+ # Predict the noise residual and compute loss
902
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states, return_dict=False)[0]
903
+
904
+ if args.snr_gamma is None:
905
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
906
+ else:
907
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
908
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
909
+ # This is discussed in Section 4.2 of the same paper.
910
+ snr = compute_snr(noise_scheduler, timesteps)
911
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
912
+ dim=1
913
+ )[0]
914
+ if noise_scheduler.config.prediction_type == "epsilon":
915
+ mse_loss_weights = mse_loss_weights / snr
916
+ elif noise_scheduler.config.prediction_type == "v_prediction":
917
+ mse_loss_weights = mse_loss_weights / (snr + 1)
918
+
919
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
920
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
921
+ loss = loss.mean()
922
+
923
+ # Gather the losses across all processes for logging (if we use distributed training).
924
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
925
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
926
+
927
+ # Backpropagate
928
+ accelerator.backward(loss)
929
+ if accelerator.sync_gradients:
930
+ params_to_clip = lora_layers
931
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
932
+ optimizer.step()
933
+ lr_scheduler.step()
934
+ optimizer.zero_grad()
935
+
936
+ # Checks if the accelerator has performed an optimization step behind the scenes
937
+ if accelerator.sync_gradients:
938
+ progress_bar.update(1)
939
+ global_step += 1
940
+ accelerator.log({"train_loss": train_loss}, step=global_step)
941
+ train_loss = 0.0
942
+
943
+ if global_step % args.checkpointing_steps == 0:
944
+ if accelerator.is_main_process:
945
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
946
+ if args.checkpoints_total_limit is not None:
947
+ checkpoints = os.listdir(args.output_dir)
948
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
949
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
950
+
951
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
952
+ if len(checkpoints) >= args.checkpoints_total_limit:
953
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
954
+ removing_checkpoints = checkpoints[0:num_to_remove]
955
+
956
+ logger.info(
957
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
958
+ )
959
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
960
+
961
+ for removing_checkpoint in removing_checkpoints:
962
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
963
+ shutil.rmtree(removing_checkpoint)
964
+
965
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
966
+ accelerator.save_state(save_path)
967
+
968
+ logger.info(f"Saved state to {save_path}")
969
+
970
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
971
+ progress_bar.set_postfix(**logs)
972
+
973
+ if global_step >= args.max_train_steps:
974
+ break
975
+
976
+ if accelerator.is_main_process:
977
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
978
+ # create pipeline
979
+ pipeline = DiffusionPipeline.from_pretrained(
980
+ args.pretrained_model_name_or_path,
981
+ unet=unwrap_model(unet),
982
+ revision=args.revision,
983
+ variant=args.variant,
984
+ torch_dtype=weight_dtype,
985
+ )
986
+ images = log_validation(pipeline, args, accelerator, epoch)
987
+
988
+ del pipeline
989
+ torch.cuda.empty_cache()
990
+
991
+ # Save the lora layers
992
+ accelerator.wait_for_everyone()
993
+ if accelerator.is_main_process:
994
+ unet = unet.to(torch.float32)
995
+
996
+ unwrapped_unet = unwrap_model(unet)
997
+ unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unwrapped_unet))
998
+ StableDiffusionPipeline.save_lora_weights(
999
+ save_directory=args.output_dir,
1000
+ unet_lora_layers=unet_lora_state_dict,
1001
+ safe_serialization=True,
1002
+ )
1003
+
1004
+ # Final inference
1005
+ # Load previous pipeline
1006
+ if args.validation_prompt is not None:
1007
+ pipeline = DiffusionPipeline.from_pretrained(
1008
+ args.pretrained_model_name_or_path,
1009
+ revision=args.revision,
1010
+ variant=args.variant,
1011
+ torch_dtype=weight_dtype,
1012
+ )
1013
+
1014
+ # load attention processors
1015
+ pipeline.load_lora_weights(args.output_dir)
1016
+
1017
+ # run inference
1018
+ images = log_validation(pipeline, args, accelerator, epoch, is_final_validation=True)
1019
+
1020
+ if args.push_to_hub:
1021
+ save_model_card(
1022
+ repo_id,
1023
+ images=images,
1024
+ base_model=args.pretrained_model_name_or_path,
1025
+ dataset_name=args.dataset_name,
1026
+ repo_folder=args.output_dir,
1027
+ )
1028
+ upload_folder(
1029
+ repo_id=repo_id,
1030
+ folder_path=args.output_dir,
1031
+ commit_message="End of training",
1032
+ ignore_patterns=["step_*", "epoch_*"],
1033
+ )
1034
+
1035
+ accelerator.end_training()
1036
+
1037
+
1038
+ if __name__ == "__main__":
1039
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_lora_sdxl.py ADDED
@@ -0,0 +1,1342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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
+ """Fine-tuning script for Stable Diffusion XL for text2image with support for LoRA."""
17
+
18
+ import argparse
19
+ import logging
20
+ import math
21
+ import os
22
+ import random
23
+ import shutil
24
+ from contextlib import nullcontext
25
+ from pathlib import Path
26
+
27
+ import datasets
28
+ import numpy as np
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ import transformers
33
+ from accelerate import Accelerator
34
+ from accelerate.logging import get_logger
35
+ from accelerate.utils import DistributedDataParallelKwargs, DistributedType, ProjectConfiguration, set_seed
36
+ from datasets import load_dataset
37
+ from huggingface_hub import create_repo, upload_folder
38
+ from packaging import version
39
+ from peft import LoraConfig, set_peft_model_state_dict
40
+ from peft.utils import get_peft_model_state_dict
41
+ from torchvision import transforms
42
+ from torchvision.transforms.functional import crop
43
+ from tqdm.auto import tqdm
44
+ from transformers import AutoTokenizer, PretrainedConfig
45
+
46
+ import diffusers
47
+ from diffusers import (
48
+ AutoencoderKL,
49
+ DDPMScheduler,
50
+ StableDiffusionXLPipeline,
51
+ UNet2DConditionModel,
52
+ )
53
+ from diffusers.loaders import StableDiffusionLoraLoaderMixin
54
+ from diffusers.optimization import get_scheduler
55
+ from diffusers.training_utils import _set_state_dict_into_text_encoder, cast_training_params, compute_snr
56
+ from diffusers.utils import (
57
+ check_min_version,
58
+ convert_state_dict_to_diffusers,
59
+ convert_unet_state_dict_to_peft,
60
+ is_wandb_available,
61
+ )
62
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
63
+ from diffusers.utils.import_utils import is_torch_npu_available, is_xformers_available
64
+ from diffusers.utils.torch_utils import is_compiled_module
65
+
66
+
67
+ if is_wandb_available():
68
+ import wandb
69
+
70
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
71
+ check_min_version("0.39.0.dev0")
72
+
73
+ logger = get_logger(__name__)
74
+ if is_torch_npu_available():
75
+ torch.npu.config.allow_internal_format = False
76
+
77
+
78
+ def save_model_card(
79
+ repo_id: str,
80
+ images: list = None,
81
+ base_model: str = None,
82
+ dataset_name: str = None,
83
+ train_text_encoder: bool = False,
84
+ repo_folder: str = None,
85
+ vae_path: str = None,
86
+ ):
87
+ img_str = ""
88
+ if images is not None:
89
+ for i, image in enumerate(images):
90
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
91
+ img_str += f"![img_{i}](./image_{i}.png)\n"
92
+
93
+ model_description = f"""
94
+ # LoRA text2image fine-tuning - {repo_id}
95
+
96
+ These are LoRA adaption weights for {base_model}. The weights were fine-tuned on the {dataset_name} dataset. You can find some example images in the following. \n
97
+ {img_str}
98
+
99
+ LoRA for the text encoder was enabled: {train_text_encoder}.
100
+
101
+ Special VAE used for training: {vae_path}.
102
+ """
103
+ model_card = load_or_create_model_card(
104
+ repo_id_or_path=repo_id,
105
+ from_training=True,
106
+ license="creativeml-openrail-m",
107
+ base_model=base_model,
108
+ model_description=model_description,
109
+ inference=True,
110
+ )
111
+
112
+ tags = [
113
+ "stable-diffusion-xl",
114
+ "stable-diffusion-xl-diffusers",
115
+ "text-to-image",
116
+ "diffusers",
117
+ "diffusers-training",
118
+ "lora",
119
+ ]
120
+ model_card = populate_model_card(model_card, tags=tags)
121
+
122
+ model_card.save(os.path.join(repo_folder, "README.md"))
123
+
124
+
125
+ def log_validation(
126
+ pipeline,
127
+ args,
128
+ accelerator,
129
+ epoch,
130
+ is_final_validation=False,
131
+ ):
132
+ logger.info(
133
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
134
+ f" {args.validation_prompt}."
135
+ )
136
+ pipeline = pipeline.to(accelerator.device)
137
+ pipeline.set_progress_bar_config(disable=True)
138
+
139
+ # run inference
140
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed is not None else None
141
+ pipeline_args = {"prompt": args.validation_prompt}
142
+ if torch.backends.mps.is_available():
143
+ autocast_ctx = nullcontext()
144
+ else:
145
+ autocast_ctx = torch.autocast(accelerator.device.type)
146
+
147
+ with autocast_ctx:
148
+ images = [pipeline(**pipeline_args, generator=generator).images[0] for _ in range(args.num_validation_images)]
149
+
150
+ for tracker in accelerator.trackers:
151
+ phase_name = "test" if is_final_validation else "validation"
152
+ if tracker.name == "tensorboard":
153
+ np_images = np.stack([np.asarray(img) for img in images])
154
+ tracker.writer.add_images(phase_name, np_images, epoch, dataformats="NHWC")
155
+ if tracker.name == "wandb":
156
+ tracker.log(
157
+ {
158
+ phase_name: [
159
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
160
+ ]
161
+ }
162
+ )
163
+ return images
164
+
165
+
166
+ def import_model_class_from_model_name_or_path(
167
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
168
+ ):
169
+ text_encoder_config = PretrainedConfig.from_pretrained(
170
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
171
+ )
172
+ model_class = text_encoder_config.architectures[0]
173
+
174
+ if model_class == "CLIPTextModel":
175
+ from transformers import CLIPTextModel
176
+
177
+ return CLIPTextModel
178
+ elif model_class == "CLIPTextModelWithProjection":
179
+ from transformers import CLIPTextModelWithProjection
180
+
181
+ return CLIPTextModelWithProjection
182
+ else:
183
+ raise ValueError(f"{model_class} is not supported.")
184
+
185
+
186
+ def parse_args(input_args=None):
187
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
188
+ parser.add_argument(
189
+ "--pretrained_model_name_or_path",
190
+ type=str,
191
+ default=None,
192
+ required=True,
193
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
194
+ )
195
+ parser.add_argument(
196
+ "--pretrained_vae_model_name_or_path",
197
+ type=str,
198
+ default=None,
199
+ help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
200
+ )
201
+ parser.add_argument(
202
+ "--revision",
203
+ type=str,
204
+ default=None,
205
+ required=False,
206
+ help="Revision of pretrained model identifier from huggingface.co/models.",
207
+ )
208
+ parser.add_argument(
209
+ "--variant",
210
+ type=str,
211
+ default=None,
212
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
213
+ )
214
+ parser.add_argument(
215
+ "--dataset_name",
216
+ type=str,
217
+ default=None,
218
+ help=(
219
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
220
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
221
+ " or to a folder containing files that 🤗 Datasets can understand."
222
+ ),
223
+ )
224
+ parser.add_argument(
225
+ "--dataset_config_name",
226
+ type=str,
227
+ default=None,
228
+ help="The config of the Dataset, leave as None if there's only one config.",
229
+ )
230
+ parser.add_argument(
231
+ "--train_data_dir",
232
+ type=str,
233
+ default=None,
234
+ help=(
235
+ "A folder containing the training data. Folder contents must follow the structure described in"
236
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
237
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
238
+ ),
239
+ )
240
+ parser.add_argument(
241
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
242
+ )
243
+ parser.add_argument(
244
+ "--caption_column",
245
+ type=str,
246
+ default="text",
247
+ help="The column of the dataset containing a caption or a list of captions.",
248
+ )
249
+ parser.add_argument(
250
+ "--validation_prompt",
251
+ type=str,
252
+ default=None,
253
+ help="A prompt that is used during validation to verify that the model is learning.",
254
+ )
255
+ parser.add_argument(
256
+ "--num_validation_images",
257
+ type=int,
258
+ default=4,
259
+ help="Number of images that should be generated during validation with `validation_prompt`.",
260
+ )
261
+ parser.add_argument(
262
+ "--validation_epochs",
263
+ type=int,
264
+ default=1,
265
+ help=(
266
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
267
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
268
+ ),
269
+ )
270
+ parser.add_argument(
271
+ "--max_train_samples",
272
+ type=int,
273
+ default=None,
274
+ help=(
275
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
276
+ "value if set."
277
+ ),
278
+ )
279
+ parser.add_argument(
280
+ "--output_dir",
281
+ type=str,
282
+ default="sd-model-finetuned-lora",
283
+ help="The output directory where the model predictions and checkpoints will be written.",
284
+ )
285
+ parser.add_argument(
286
+ "--cache_dir",
287
+ type=str,
288
+ default=None,
289
+ help="The directory where the downloaded models and datasets will be stored.",
290
+ )
291
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
292
+ parser.add_argument(
293
+ "--resolution",
294
+ type=int,
295
+ default=1024,
296
+ help=(
297
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
298
+ " resolution"
299
+ ),
300
+ )
301
+ parser.add_argument(
302
+ "--center_crop",
303
+ default=False,
304
+ action="store_true",
305
+ help=(
306
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
307
+ " cropped. The images will be resized to the resolution first before cropping."
308
+ ),
309
+ )
310
+ parser.add_argument(
311
+ "--random_flip",
312
+ action="store_true",
313
+ help="whether to randomly flip images horizontally",
314
+ )
315
+ parser.add_argument(
316
+ "--train_text_encoder",
317
+ action="store_true",
318
+ help="Whether to train the text encoder. If set, the text encoder should be float32 precision.",
319
+ )
320
+ parser.add_argument(
321
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
322
+ )
323
+ parser.add_argument("--num_train_epochs", type=int, default=100)
324
+ parser.add_argument(
325
+ "--max_train_steps",
326
+ type=int,
327
+ default=None,
328
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
329
+ )
330
+ parser.add_argument(
331
+ "--checkpointing_steps",
332
+ type=int,
333
+ default=500,
334
+ help=(
335
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
336
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
337
+ " training using `--resume_from_checkpoint`."
338
+ ),
339
+ )
340
+ parser.add_argument(
341
+ "--checkpoints_total_limit",
342
+ type=int,
343
+ default=None,
344
+ help=("Max number of checkpoints to store."),
345
+ )
346
+ parser.add_argument(
347
+ "--resume_from_checkpoint",
348
+ type=str,
349
+ default=None,
350
+ help=(
351
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
352
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
353
+ ),
354
+ )
355
+ parser.add_argument(
356
+ "--gradient_accumulation_steps",
357
+ type=int,
358
+ default=1,
359
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
360
+ )
361
+ parser.add_argument(
362
+ "--gradient_checkpointing",
363
+ action="store_true",
364
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
365
+ )
366
+ parser.add_argument(
367
+ "--learning_rate",
368
+ type=float,
369
+ default=1e-4,
370
+ help="Initial learning rate (after the potential warmup period) to use.",
371
+ )
372
+ parser.add_argument(
373
+ "--scale_lr",
374
+ action="store_true",
375
+ default=False,
376
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
377
+ )
378
+ parser.add_argument(
379
+ "--lr_scheduler",
380
+ type=str,
381
+ default="constant",
382
+ help=(
383
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
384
+ ' "constant", "constant_with_warmup"]'
385
+ ),
386
+ )
387
+ parser.add_argument(
388
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
389
+ )
390
+ parser.add_argument(
391
+ "--snr_gamma",
392
+ type=float,
393
+ default=None,
394
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
395
+ "More details here: https://huggingface.co/papers/2303.09556.",
396
+ )
397
+ parser.add_argument(
398
+ "--allow_tf32",
399
+ action="store_true",
400
+ help=(
401
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
402
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
403
+ ),
404
+ )
405
+ parser.add_argument(
406
+ "--dataloader_num_workers",
407
+ type=int,
408
+ default=0,
409
+ help=(
410
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
411
+ ),
412
+ )
413
+ parser.add_argument(
414
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
415
+ )
416
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
417
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
418
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
419
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
420
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
421
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
422
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
423
+ parser.add_argument(
424
+ "--prediction_type",
425
+ type=str,
426
+ default=None,
427
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
428
+ )
429
+ parser.add_argument(
430
+ "--hub_model_id",
431
+ type=str,
432
+ default=None,
433
+ help="The name of the repository to keep in sync with the local `output_dir`.",
434
+ )
435
+ parser.add_argument(
436
+ "--logging_dir",
437
+ type=str,
438
+ default="logs",
439
+ help=(
440
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
441
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
442
+ ),
443
+ )
444
+ parser.add_argument(
445
+ "--report_to",
446
+ type=str,
447
+ default="tensorboard",
448
+ help=(
449
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
450
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
451
+ ),
452
+ )
453
+ parser.add_argument(
454
+ "--mixed_precision",
455
+ type=str,
456
+ default=None,
457
+ choices=["no", "fp16", "bf16"],
458
+ help=(
459
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
460
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
461
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
462
+ ),
463
+ )
464
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
465
+ parser.add_argument(
466
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
467
+ )
468
+ parser.add_argument(
469
+ "--enable_npu_flash_attention", action="store_true", help="Whether or not to use npu flash attention."
470
+ )
471
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
472
+ parser.add_argument(
473
+ "--rank",
474
+ type=int,
475
+ default=4,
476
+ help=("The dimension of the LoRA update matrices."),
477
+ )
478
+ parser.add_argument(
479
+ "--debug_loss",
480
+ action="store_true",
481
+ help="debug loss for each image, if filenames are available in the dataset",
482
+ )
483
+ parser.add_argument(
484
+ "--image_interpolation_mode",
485
+ type=str,
486
+ default="lanczos",
487
+ choices=[
488
+ f.lower() for f in dir(transforms.InterpolationMode) if not f.startswith("__") and not f.endswith("__")
489
+ ],
490
+ help="The image interpolation method to use for resizing images.",
491
+ )
492
+
493
+ if input_args is not None:
494
+ args = parser.parse_args(input_args)
495
+ else:
496
+ args = parser.parse_args()
497
+
498
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
499
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
500
+ args.local_rank = env_local_rank
501
+
502
+ # Sanity checks
503
+ if args.dataset_name is None and args.train_data_dir is None:
504
+ raise ValueError("Need either a dataset name or a training folder.")
505
+
506
+ return args
507
+
508
+
509
+ DATASET_NAME_MAPPING = {
510
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
511
+ }
512
+
513
+
514
+ def tokenize_prompt(tokenizer, prompt):
515
+ text_inputs = tokenizer(
516
+ prompt,
517
+ padding="max_length",
518
+ max_length=tokenizer.model_max_length,
519
+ truncation=True,
520
+ return_tensors="pt",
521
+ )
522
+ text_input_ids = text_inputs.input_ids
523
+ return text_input_ids
524
+
525
+
526
+ # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
527
+ def encode_prompt(text_encoders, tokenizers, prompt, text_input_ids_list=None):
528
+ prompt_embeds_list = []
529
+
530
+ for i, text_encoder in enumerate(text_encoders):
531
+ if tokenizers is not None:
532
+ tokenizer = tokenizers[i]
533
+ text_input_ids = tokenize_prompt(tokenizer, prompt)
534
+ else:
535
+ assert text_input_ids_list is not None
536
+ text_input_ids = text_input_ids_list[i]
537
+
538
+ prompt_embeds = text_encoder(
539
+ text_input_ids.to(text_encoder.device), output_hidden_states=True, return_dict=False
540
+ )
541
+
542
+ # We are only ALWAYS interested in the pooled output of the final text encoder
543
+ pooled_prompt_embeds = prompt_embeds[0]
544
+ prompt_embeds = prompt_embeds[-1][-2]
545
+ bs_embed, seq_len, _ = prompt_embeds.shape
546
+ prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
547
+ prompt_embeds_list.append(prompt_embeds)
548
+
549
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
550
+ pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
551
+ return prompt_embeds, pooled_prompt_embeds
552
+
553
+
554
+ def main(args):
555
+ if args.report_to == "wandb" and args.hub_token is not None:
556
+ raise ValueError(
557
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
558
+ " Please use `hf auth login` to authenticate with the Hub."
559
+ )
560
+
561
+ logging_dir = Path(args.output_dir, args.logging_dir)
562
+
563
+ if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
564
+ # due to pytorch#99272, MPS does not yet support bfloat16.
565
+ raise ValueError(
566
+ "Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
567
+ )
568
+
569
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
570
+ kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
571
+ accelerator = Accelerator(
572
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
573
+ mixed_precision=args.mixed_precision,
574
+ log_with=args.report_to,
575
+ project_config=accelerator_project_config,
576
+ kwargs_handlers=[kwargs],
577
+ )
578
+
579
+ # Make one log on every process with the configuration for debugging.
580
+ logging.basicConfig(
581
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
582
+ datefmt="%m/%d/%Y %H:%M:%S",
583
+ level=logging.INFO,
584
+ )
585
+ logger.info(accelerator.state, main_process_only=False)
586
+ if accelerator.is_local_main_process:
587
+ datasets.utils.logging.set_verbosity_warning()
588
+ transformers.utils.logging.set_verbosity_warning()
589
+ diffusers.utils.logging.set_verbosity_info()
590
+ else:
591
+ datasets.utils.logging.set_verbosity_error()
592
+ transformers.utils.logging.set_verbosity_error()
593
+ diffusers.utils.logging.set_verbosity_error()
594
+
595
+ # If passed along, set the training seed now.
596
+ if args.seed is not None:
597
+ set_seed(args.seed)
598
+
599
+ # Handle the repository creation
600
+ if accelerator.is_main_process:
601
+ if args.output_dir is not None:
602
+ os.makedirs(args.output_dir, exist_ok=True)
603
+
604
+ if args.push_to_hub:
605
+ repo_id = create_repo(
606
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
607
+ ).repo_id
608
+
609
+ # Load the tokenizers
610
+ tokenizer_one = AutoTokenizer.from_pretrained(
611
+ args.pretrained_model_name_or_path,
612
+ subfolder="tokenizer",
613
+ revision=args.revision,
614
+ use_fast=False,
615
+ )
616
+ tokenizer_two = AutoTokenizer.from_pretrained(
617
+ args.pretrained_model_name_or_path,
618
+ subfolder="tokenizer_2",
619
+ revision=args.revision,
620
+ use_fast=False,
621
+ )
622
+
623
+ # import correct text encoder classes
624
+ text_encoder_cls_one = import_model_class_from_model_name_or_path(
625
+ args.pretrained_model_name_or_path, args.revision
626
+ )
627
+ text_encoder_cls_two = import_model_class_from_model_name_or_path(
628
+ args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
629
+ )
630
+
631
+ # Load scheduler and models
632
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
633
+ text_encoder_one = text_encoder_cls_one.from_pretrained(
634
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
635
+ )
636
+ text_encoder_two = text_encoder_cls_two.from_pretrained(
637
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
638
+ )
639
+ vae_path = (
640
+ args.pretrained_model_name_or_path
641
+ if args.pretrained_vae_model_name_or_path is None
642
+ else args.pretrained_vae_model_name_or_path
643
+ )
644
+ vae = AutoencoderKL.from_pretrained(
645
+ vae_path,
646
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
647
+ revision=args.revision,
648
+ variant=args.variant,
649
+ )
650
+ unet = UNet2DConditionModel.from_pretrained(
651
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
652
+ )
653
+
654
+ # We only train the additional adapter LoRA layers
655
+ vae.requires_grad_(False)
656
+ text_encoder_one.requires_grad_(False)
657
+ text_encoder_two.requires_grad_(False)
658
+ unet.requires_grad_(False)
659
+
660
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
661
+ # as these weights are only used for inference, keeping weights in full precision is not required.
662
+ weight_dtype = torch.float32
663
+ if accelerator.mixed_precision == "fp16":
664
+ weight_dtype = torch.float16
665
+ elif accelerator.mixed_precision == "bf16":
666
+ weight_dtype = torch.bfloat16
667
+
668
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
669
+ # The VAE is in float32 to avoid NaN losses.
670
+ unet.to(accelerator.device, dtype=weight_dtype)
671
+
672
+ if args.pretrained_vae_model_name_or_path is None:
673
+ vae.to(accelerator.device, dtype=torch.float32)
674
+ else:
675
+ vae.to(accelerator.device, dtype=weight_dtype)
676
+ text_encoder_one.to(accelerator.device, dtype=weight_dtype)
677
+ text_encoder_two.to(accelerator.device, dtype=weight_dtype)
678
+
679
+ if args.enable_npu_flash_attention:
680
+ if is_torch_npu_available():
681
+ logger.info("npu flash attention enabled.")
682
+ unet.enable_npu_flash_attention()
683
+ else:
684
+ raise ValueError("npu flash attention requires torch_npu extensions and is supported only on npu devices.")
685
+
686
+ if args.enable_xformers_memory_efficient_attention:
687
+ if is_xformers_available():
688
+ import xformers
689
+
690
+ xformers_version = version.parse(xformers.__version__)
691
+ if xformers_version == version.parse("0.0.16"):
692
+ logger.warning(
693
+ "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."
694
+ )
695
+ unet.enable_xformers_memory_efficient_attention()
696
+ else:
697
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
698
+
699
+ # now we will add new LoRA weights to the attention layers
700
+ # Set correct lora layers
701
+ unet_lora_config = LoraConfig(
702
+ r=args.rank,
703
+ lora_alpha=args.rank,
704
+ init_lora_weights="gaussian",
705
+ target_modules=["to_k", "to_q", "to_v", "to_out.0"],
706
+ )
707
+
708
+ unet.add_adapter(unet_lora_config)
709
+
710
+ # The text encoder comes from 🤗 transformers, we will also attach adapters to it.
711
+ if args.train_text_encoder:
712
+ # ensure that dtype is float32, even if rest of the model that isn't trained is loaded in fp16
713
+ text_lora_config = LoraConfig(
714
+ r=args.rank,
715
+ lora_alpha=args.rank,
716
+ init_lora_weights="gaussian",
717
+ target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
718
+ )
719
+ text_encoder_one.add_adapter(text_lora_config)
720
+ text_encoder_two.add_adapter(text_lora_config)
721
+
722
+ def unwrap_model(model):
723
+ model = accelerator.unwrap_model(model)
724
+ model = model._orig_mod if is_compiled_module(model) else model
725
+ return model
726
+
727
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
728
+ def save_model_hook(models, weights, output_dir):
729
+ if accelerator.is_main_process:
730
+ # there are only two options here. Either are just the unet attn processor layers
731
+ # or there are the unet and text encoder attn layers
732
+ unet_lora_layers_to_save = None
733
+ text_encoder_one_lora_layers_to_save = None
734
+ text_encoder_two_lora_layers_to_save = None
735
+
736
+ for model in models:
737
+ if isinstance(unwrap_model(model), type(unwrap_model(unet))):
738
+ unet_lora_layers_to_save = convert_state_dict_to_diffusers(get_peft_model_state_dict(model))
739
+ elif isinstance(unwrap_model(model), type(unwrap_model(text_encoder_one))):
740
+ text_encoder_one_lora_layers_to_save = convert_state_dict_to_diffusers(
741
+ get_peft_model_state_dict(model)
742
+ )
743
+ elif isinstance(unwrap_model(model), type(unwrap_model(text_encoder_two))):
744
+ text_encoder_two_lora_layers_to_save = convert_state_dict_to_diffusers(
745
+ get_peft_model_state_dict(model)
746
+ )
747
+ else:
748
+ raise ValueError(f"unexpected save model: {model.__class__}")
749
+
750
+ # make sure to pop weight so that corresponding model is not saved again
751
+ if weights:
752
+ weights.pop()
753
+
754
+ StableDiffusionXLPipeline.save_lora_weights(
755
+ output_dir,
756
+ unet_lora_layers=unet_lora_layers_to_save,
757
+ text_encoder_lora_layers=text_encoder_one_lora_layers_to_save,
758
+ text_encoder_2_lora_layers=text_encoder_two_lora_layers_to_save,
759
+ )
760
+
761
+ def load_model_hook(models, input_dir):
762
+ unet_ = None
763
+ text_encoder_one_ = None
764
+ text_encoder_two_ = None
765
+
766
+ while len(models) > 0:
767
+ model = models.pop()
768
+
769
+ if isinstance(model, type(unwrap_model(unet))):
770
+ unet_ = model
771
+ elif isinstance(model, type(unwrap_model(text_encoder_one))):
772
+ text_encoder_one_ = model
773
+ elif isinstance(model, type(unwrap_model(text_encoder_two))):
774
+ text_encoder_two_ = model
775
+ else:
776
+ raise ValueError(f"unexpected save model: {model.__class__}")
777
+
778
+ lora_state_dict, _ = StableDiffusionLoraLoaderMixin.lora_state_dict(input_dir)
779
+ unet_state_dict = {f"{k.replace('unet.', '')}": v for k, v in lora_state_dict.items() if k.startswith("unet.")}
780
+ unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
781
+ incompatible_keys = set_peft_model_state_dict(unet_, unet_state_dict, adapter_name="default")
782
+ if incompatible_keys is not None:
783
+ # check only for unexpected keys
784
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
785
+ if unexpected_keys:
786
+ logger.warning(
787
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
788
+ f" {unexpected_keys}. "
789
+ )
790
+
791
+ if args.train_text_encoder:
792
+ _set_state_dict_into_text_encoder(lora_state_dict, prefix="text_encoder.", text_encoder=text_encoder_one_)
793
+
794
+ _set_state_dict_into_text_encoder(
795
+ lora_state_dict, prefix="text_encoder_2.", text_encoder=text_encoder_two_
796
+ )
797
+
798
+ # Make sure the trainable params are in float32. This is again needed since the base models
799
+ # are in `weight_dtype`. More details:
800
+ # https://github.com/huggingface/diffusers/pull/6514#discussion_r1449796804
801
+ if args.mixed_precision == "fp16":
802
+ models = [unet_]
803
+ if args.train_text_encoder:
804
+ models.extend([text_encoder_one_, text_encoder_two_])
805
+ cast_training_params(models, dtype=torch.float32)
806
+
807
+ accelerator.register_save_state_pre_hook(save_model_hook)
808
+ accelerator.register_load_state_pre_hook(load_model_hook)
809
+
810
+ if args.gradient_checkpointing:
811
+ unet.enable_gradient_checkpointing()
812
+ if args.train_text_encoder:
813
+ text_encoder_one.gradient_checkpointing_enable()
814
+ text_encoder_two.gradient_checkpointing_enable()
815
+
816
+ # Enable TF32 for faster training on Ampere GPUs,
817
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
818
+ if args.allow_tf32:
819
+ torch.backends.cuda.matmul.allow_tf32 = True
820
+
821
+ if args.scale_lr:
822
+ args.learning_rate = (
823
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
824
+ )
825
+
826
+ # Make sure the trainable params are in float32.
827
+ if args.mixed_precision == "fp16":
828
+ models = [unet]
829
+ if args.train_text_encoder:
830
+ models.extend([text_encoder_one, text_encoder_two])
831
+ cast_training_params(models, dtype=torch.float32)
832
+
833
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
834
+ if args.use_8bit_adam:
835
+ try:
836
+ import bitsandbytes as bnb
837
+ except ImportError:
838
+ raise ImportError(
839
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
840
+ )
841
+
842
+ optimizer_class = bnb.optim.AdamW8bit
843
+ else:
844
+ optimizer_class = torch.optim.AdamW
845
+
846
+ # Optimizer creation
847
+ params_to_optimize = list(filter(lambda p: p.requires_grad, unet.parameters()))
848
+ if args.train_text_encoder:
849
+ params_to_optimize = (
850
+ params_to_optimize
851
+ + list(filter(lambda p: p.requires_grad, text_encoder_one.parameters()))
852
+ + list(filter(lambda p: p.requires_grad, text_encoder_two.parameters()))
853
+ )
854
+ optimizer = optimizer_class(
855
+ params_to_optimize,
856
+ lr=args.learning_rate,
857
+ betas=(args.adam_beta1, args.adam_beta2),
858
+ weight_decay=args.adam_weight_decay,
859
+ eps=args.adam_epsilon,
860
+ )
861
+
862
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
863
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
864
+
865
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
866
+ # download the dataset.
867
+ if args.dataset_name is not None:
868
+ # Downloading and loading a dataset from the hub.
869
+ dataset = load_dataset(
870
+ args.dataset_name, args.dataset_config_name, cache_dir=args.cache_dir, data_dir=args.train_data_dir
871
+ )
872
+ else:
873
+ data_files = {}
874
+ if args.train_data_dir is not None:
875
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
876
+ dataset = load_dataset(
877
+ "imagefolder",
878
+ data_files=data_files,
879
+ cache_dir=args.cache_dir,
880
+ )
881
+ # See more about loading custom images at
882
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
883
+
884
+ # Preprocessing the datasets.
885
+ # We need to tokenize inputs and targets.
886
+ column_names = dataset["train"].column_names
887
+
888
+ # 6. Get the column names for input/target.
889
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
890
+ if args.image_column is None:
891
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
892
+ else:
893
+ image_column = args.image_column
894
+ if image_column not in column_names:
895
+ raise ValueError(
896
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
897
+ )
898
+ if args.caption_column is None:
899
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
900
+ else:
901
+ caption_column = args.caption_column
902
+ if caption_column not in column_names:
903
+ raise ValueError(
904
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
905
+ )
906
+
907
+ # Preprocessing the datasets.
908
+ # We need to tokenize input captions and transform the images.
909
+ def tokenize_captions(examples, is_train=True):
910
+ captions = []
911
+ for caption in examples[caption_column]:
912
+ if isinstance(caption, str):
913
+ captions.append(caption)
914
+ elif isinstance(caption, (list, np.ndarray)):
915
+ # take a random caption if there are multiple
916
+ captions.append(random.choice(caption) if is_train else caption[0])
917
+ else:
918
+ raise ValueError(
919
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
920
+ )
921
+ tokens_one = tokenize_prompt(tokenizer_one, captions)
922
+ tokens_two = tokenize_prompt(tokenizer_two, captions)
923
+ return tokens_one, tokens_two
924
+
925
+ # Get the specified interpolation method from the args
926
+ interpolation = getattr(transforms.InterpolationMode, args.image_interpolation_mode.upper(), None)
927
+
928
+ # Raise an error if the interpolation method is invalid
929
+ if interpolation is None:
930
+ raise ValueError(f"Unsupported interpolation mode {args.image_interpolation_mode}.")
931
+ # Preprocessing the datasets.
932
+ train_resize = transforms.Resize(args.resolution, interpolation=interpolation) # Use dynamic interpolation method
933
+ train_crop = transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution)
934
+ train_flip = transforms.RandomHorizontalFlip(p=1.0)
935
+ train_transforms = transforms.Compose(
936
+ [
937
+ transforms.ToTensor(),
938
+ transforms.Normalize([0.5], [0.5]),
939
+ ]
940
+ )
941
+
942
+ def preprocess_train(examples):
943
+ images = [image.convert("RGB") for image in examples[image_column]]
944
+ # image aug
945
+ original_sizes = []
946
+ all_images = []
947
+ crop_top_lefts = []
948
+ for image in images:
949
+ original_sizes.append((image.height, image.width))
950
+ image = train_resize(image)
951
+ if args.random_flip and random.random() < 0.5:
952
+ # flip
953
+ image = train_flip(image)
954
+ if args.center_crop:
955
+ y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
956
+ x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
957
+ image = train_crop(image)
958
+ else:
959
+ y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
960
+ image = crop(image, y1, x1, h, w)
961
+ crop_top_left = (y1, x1)
962
+ crop_top_lefts.append(crop_top_left)
963
+ image = train_transforms(image)
964
+ all_images.append(image)
965
+
966
+ examples["original_sizes"] = original_sizes
967
+ examples["crop_top_lefts"] = crop_top_lefts
968
+ examples["pixel_values"] = all_images
969
+ tokens_one, tokens_two = tokenize_captions(examples)
970
+ examples["input_ids_one"] = tokens_one
971
+ examples["input_ids_two"] = tokens_two
972
+ if args.debug_loss:
973
+ fnames = [os.path.basename(image.filename) for image in examples[image_column] if image.filename]
974
+ if fnames:
975
+ examples["filenames"] = fnames
976
+ return examples
977
+
978
+ with accelerator.main_process_first():
979
+ if args.max_train_samples is not None:
980
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
981
+ # Set the training transforms
982
+ train_dataset = dataset["train"].with_transform(preprocess_train, output_all_columns=True)
983
+
984
+ def collate_fn(examples):
985
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
986
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
987
+ original_sizes = [example["original_sizes"] for example in examples]
988
+ crop_top_lefts = [example["crop_top_lefts"] for example in examples]
989
+ input_ids_one = torch.stack([example["input_ids_one"] for example in examples])
990
+ input_ids_two = torch.stack([example["input_ids_two"] for example in examples])
991
+ result = {
992
+ "pixel_values": pixel_values,
993
+ "input_ids_one": input_ids_one,
994
+ "input_ids_two": input_ids_two,
995
+ "original_sizes": original_sizes,
996
+ "crop_top_lefts": crop_top_lefts,
997
+ }
998
+
999
+ filenames = [example["filenames"] for example in examples if "filenames" in example]
1000
+ if filenames:
1001
+ result["filenames"] = filenames
1002
+ return result
1003
+
1004
+ # DataLoaders creation:
1005
+ train_dataloader = torch.utils.data.DataLoader(
1006
+ train_dataset,
1007
+ shuffle=True,
1008
+ collate_fn=collate_fn,
1009
+ batch_size=args.train_batch_size,
1010
+ num_workers=args.dataloader_num_workers,
1011
+ )
1012
+
1013
+ # Scheduler and math around the number of training steps.
1014
+ overrode_max_train_steps = False
1015
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1016
+ if args.max_train_steps is None:
1017
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1018
+ overrode_max_train_steps = True
1019
+
1020
+ lr_scheduler = get_scheduler(
1021
+ args.lr_scheduler,
1022
+ optimizer=optimizer,
1023
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
1024
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
1025
+ )
1026
+
1027
+ # Prepare everything with our `accelerator`.
1028
+ if args.train_text_encoder:
1029
+ unet, text_encoder_one, text_encoder_two, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
1030
+ unet, text_encoder_one, text_encoder_two, optimizer, train_dataloader, lr_scheduler
1031
+ )
1032
+ else:
1033
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
1034
+ unet, optimizer, train_dataloader, lr_scheduler
1035
+ )
1036
+
1037
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1038
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1039
+ if overrode_max_train_steps:
1040
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1041
+ # Afterwards we recalculate our number of training epochs
1042
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1043
+
1044
+ # We need to initialize the trackers we use, and also store our configuration.
1045
+ # The trackers initializes automatically on the main process.
1046
+ if accelerator.is_main_process:
1047
+ accelerator.init_trackers("text2image-fine-tune", config=vars(args))
1048
+
1049
+ # Train!
1050
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1051
+
1052
+ logger.info("***** Running training *****")
1053
+ logger.info(f" Num examples = {len(train_dataset)}")
1054
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1055
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1056
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1057
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1058
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1059
+ global_step = 0
1060
+ first_epoch = 0
1061
+
1062
+ # Potentially load in the weights and states from a previous save
1063
+ if args.resume_from_checkpoint:
1064
+ if args.resume_from_checkpoint != "latest":
1065
+ path = os.path.basename(args.resume_from_checkpoint)
1066
+ else:
1067
+ # Get the most recent checkpoint
1068
+ dirs = os.listdir(args.output_dir)
1069
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1070
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1071
+ path = dirs[-1] if len(dirs) > 0 else None
1072
+
1073
+ if path is None:
1074
+ accelerator.print(
1075
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1076
+ )
1077
+ args.resume_from_checkpoint = None
1078
+ initial_global_step = 0
1079
+ else:
1080
+ accelerator.print(f"Resuming from checkpoint {path}")
1081
+ accelerator.load_state(os.path.join(args.output_dir, path))
1082
+ global_step = int(path.split("-")[1])
1083
+
1084
+ initial_global_step = global_step
1085
+ first_epoch = global_step // num_update_steps_per_epoch
1086
+
1087
+ else:
1088
+ initial_global_step = 0
1089
+
1090
+ progress_bar = tqdm(
1091
+ range(0, args.max_train_steps),
1092
+ initial=initial_global_step,
1093
+ desc="Steps",
1094
+ # Only show the progress bar once on each machine.
1095
+ disable=not accelerator.is_local_main_process,
1096
+ )
1097
+
1098
+ for epoch in range(first_epoch, args.num_train_epochs):
1099
+ unet.train()
1100
+ if args.train_text_encoder:
1101
+ text_encoder_one.train()
1102
+ text_encoder_two.train()
1103
+ train_loss = 0.0
1104
+ for step, batch in enumerate(train_dataloader):
1105
+ with accelerator.accumulate(unet):
1106
+ # Convert images to latent space
1107
+ if args.pretrained_vae_model_name_or_path is not None:
1108
+ pixel_values = batch["pixel_values"].to(dtype=weight_dtype)
1109
+ else:
1110
+ pixel_values = batch["pixel_values"]
1111
+
1112
+ model_input = vae.encode(pixel_values).latent_dist.sample()
1113
+ model_input = model_input * vae.config.scaling_factor
1114
+ if args.pretrained_vae_model_name_or_path is None:
1115
+ model_input = model_input.to(weight_dtype)
1116
+
1117
+ # Sample noise that we'll add to the latents
1118
+ noise = torch.randn_like(model_input)
1119
+ if args.noise_offset:
1120
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
1121
+ noise += args.noise_offset * torch.randn(
1122
+ (model_input.shape[0], model_input.shape[1], 1, 1), device=model_input.device
1123
+ )
1124
+
1125
+ bsz = model_input.shape[0]
1126
+ # Sample a random timestep for each image
1127
+ timesteps = torch.randint(
1128
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=model_input.device
1129
+ )
1130
+ timesteps = timesteps.long()
1131
+
1132
+ # Add noise to the model input according to the noise magnitude at each timestep
1133
+ # (this is the forward diffusion process)
1134
+ noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps)
1135
+
1136
+ # time ids
1137
+ def compute_time_ids(original_size, crops_coords_top_left):
1138
+ # Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
1139
+ target_size = (args.resolution, args.resolution)
1140
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1141
+ add_time_ids = torch.tensor([add_time_ids])
1142
+ add_time_ids = add_time_ids.to(accelerator.device, dtype=weight_dtype)
1143
+ return add_time_ids
1144
+
1145
+ add_time_ids = torch.cat(
1146
+ [compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
1147
+ )
1148
+
1149
+ # Predict the noise residual
1150
+ unet_added_conditions = {"time_ids": add_time_ids}
1151
+ prompt_embeds, pooled_prompt_embeds = encode_prompt(
1152
+ text_encoders=[text_encoder_one, text_encoder_two],
1153
+ tokenizers=None,
1154
+ prompt=None,
1155
+ text_input_ids_list=[batch["input_ids_one"], batch["input_ids_two"]],
1156
+ )
1157
+ unet_added_conditions.update({"text_embeds": pooled_prompt_embeds})
1158
+ model_pred = unet(
1159
+ noisy_model_input,
1160
+ timesteps,
1161
+ prompt_embeds,
1162
+ added_cond_kwargs=unet_added_conditions,
1163
+ return_dict=False,
1164
+ )[0]
1165
+
1166
+ # Get the target for loss depending on the prediction type
1167
+ if args.prediction_type is not None:
1168
+ # set prediction_type of scheduler if defined
1169
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
1170
+
1171
+ if noise_scheduler.config.prediction_type == "epsilon":
1172
+ target = noise
1173
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1174
+ target = noise_scheduler.get_velocity(model_input, noise, timesteps)
1175
+ else:
1176
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1177
+
1178
+ if args.snr_gamma is None:
1179
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1180
+ else:
1181
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
1182
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
1183
+ # This is discussed in Section 4.2 of the same paper.
1184
+ snr = compute_snr(noise_scheduler, timesteps)
1185
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
1186
+ dim=1
1187
+ )[0]
1188
+ if noise_scheduler.config.prediction_type == "epsilon":
1189
+ mse_loss_weights = mse_loss_weights / snr
1190
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1191
+ mse_loss_weights = mse_loss_weights / (snr + 1)
1192
+
1193
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
1194
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
1195
+ loss = loss.mean()
1196
+ if args.debug_loss and "filenames" in batch:
1197
+ for fname in batch["filenames"]:
1198
+ accelerator.log({"loss_for_" + fname: loss}, step=global_step)
1199
+ # Gather the losses across all processes for logging (if we use distributed training).
1200
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
1201
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1202
+
1203
+ # Backpropagate
1204
+ accelerator.backward(loss)
1205
+ if accelerator.sync_gradients:
1206
+ accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
1207
+ optimizer.step()
1208
+ lr_scheduler.step()
1209
+ optimizer.zero_grad()
1210
+
1211
+ # Checks if the accelerator has performed an optimization step behind the scenes
1212
+ if accelerator.sync_gradients:
1213
+ progress_bar.update(1)
1214
+ global_step += 1
1215
+ accelerator.log({"train_loss": train_loss}, step=global_step)
1216
+ train_loss = 0.0
1217
+
1218
+ # DeepSpeed requires saving weights on every device; saving weights only on the main process would cause issues.
1219
+ if accelerator.distributed_type == DistributedType.DEEPSPEED or accelerator.is_main_process:
1220
+ if global_step % args.checkpointing_steps == 0:
1221
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1222
+ if args.checkpoints_total_limit is not None:
1223
+ checkpoints = os.listdir(args.output_dir)
1224
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1225
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1226
+
1227
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1228
+ if len(checkpoints) >= args.checkpoints_total_limit:
1229
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1230
+ removing_checkpoints = checkpoints[0:num_to_remove]
1231
+
1232
+ logger.info(
1233
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1234
+ )
1235
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1236
+
1237
+ for removing_checkpoint in removing_checkpoints:
1238
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1239
+ shutil.rmtree(removing_checkpoint)
1240
+
1241
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1242
+ accelerator.save_state(save_path)
1243
+ logger.info(f"Saved state to {save_path}")
1244
+
1245
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1246
+ progress_bar.set_postfix(**logs)
1247
+
1248
+ if global_step >= args.max_train_steps:
1249
+ break
1250
+
1251
+ if accelerator.is_main_process:
1252
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
1253
+ # create pipeline
1254
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1255
+ args.pretrained_model_name_or_path,
1256
+ vae=vae,
1257
+ text_encoder=unwrap_model(text_encoder_one),
1258
+ text_encoder_2=unwrap_model(text_encoder_two),
1259
+ unet=unwrap_model(unet),
1260
+ revision=args.revision,
1261
+ variant=args.variant,
1262
+ torch_dtype=weight_dtype,
1263
+ )
1264
+
1265
+ images = log_validation(pipeline, args, accelerator, epoch)
1266
+
1267
+ del pipeline
1268
+ torch.cuda.empty_cache()
1269
+
1270
+ # Save the lora layers
1271
+ accelerator.wait_for_everyone()
1272
+ if accelerator.is_main_process:
1273
+ unet = unwrap_model(unet)
1274
+ unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
1275
+
1276
+ if args.train_text_encoder:
1277
+ text_encoder_one = unwrap_model(text_encoder_one)
1278
+ text_encoder_two = unwrap_model(text_encoder_two)
1279
+
1280
+ text_encoder_lora_layers = convert_state_dict_to_diffusers(get_peft_model_state_dict(text_encoder_one))
1281
+ text_encoder_2_lora_layers = convert_state_dict_to_diffusers(get_peft_model_state_dict(text_encoder_two))
1282
+ else:
1283
+ text_encoder_lora_layers = None
1284
+ text_encoder_2_lora_layers = None
1285
+
1286
+ StableDiffusionXLPipeline.save_lora_weights(
1287
+ save_directory=args.output_dir,
1288
+ unet_lora_layers=unet_lora_state_dict,
1289
+ text_encoder_lora_layers=text_encoder_lora_layers,
1290
+ text_encoder_2_lora_layers=text_encoder_2_lora_layers,
1291
+ )
1292
+
1293
+ del unet
1294
+ del text_encoder_one
1295
+ del text_encoder_two
1296
+ del text_encoder_lora_layers
1297
+ del text_encoder_2_lora_layers
1298
+ torch.cuda.empty_cache()
1299
+
1300
+ # Final inference
1301
+ # Make sure vae.dtype is consistent with the unet.dtype
1302
+ if args.mixed_precision == "fp16":
1303
+ vae.to(weight_dtype)
1304
+ # Load previous pipeline
1305
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1306
+ args.pretrained_model_name_or_path,
1307
+ vae=vae,
1308
+ revision=args.revision,
1309
+ variant=args.variant,
1310
+ torch_dtype=weight_dtype,
1311
+ )
1312
+
1313
+ # load attention processors
1314
+ pipeline.load_lora_weights(args.output_dir)
1315
+
1316
+ # run inference
1317
+ if args.validation_prompt and args.num_validation_images > 0:
1318
+ images = log_validation(pipeline, args, accelerator, epoch, is_final_validation=True)
1319
+
1320
+ if args.push_to_hub:
1321
+ save_model_card(
1322
+ repo_id,
1323
+ images=images,
1324
+ base_model=args.pretrained_model_name_or_path,
1325
+ dataset_name=args.dataset_name,
1326
+ train_text_encoder=args.train_text_encoder,
1327
+ repo_folder=args.output_dir,
1328
+ vae_path=args.pretrained_vae_model_name_or_path,
1329
+ )
1330
+ upload_folder(
1331
+ repo_id=repo_id,
1332
+ folder_path=args.output_dir,
1333
+ commit_message="End of training",
1334
+ ignore_patterns=["step_*", "epoch_*"],
1335
+ )
1336
+
1337
+ accelerator.end_training()
1338
+
1339
+
1340
+ if __name__ == "__main__":
1341
+ args = parse_args()
1342
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/examples/text_to_image/train_text_to_image_sdxl.py ADDED
@@ -0,0 +1,1370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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
+ """Fine-tuning script for Stable Diffusion XL for text2image."""
17
+
18
+ import argparse
19
+ import functools
20
+ import gc
21
+ import logging
22
+ import math
23
+ import os
24
+ import random
25
+ import shutil
26
+ from contextlib import nullcontext
27
+ from pathlib import Path
28
+
29
+ import accelerate
30
+ import datasets
31
+ import numpy as np
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.utils import DistributedType, ProjectConfiguration, set_seed
39
+ from datasets import concatenate_datasets, load_dataset
40
+ from huggingface_hub import create_repo, upload_folder
41
+ from packaging import version
42
+ from torchvision import transforms
43
+ from torchvision.transforms.functional import crop
44
+ from tqdm.auto import tqdm
45
+ from transformers import AutoTokenizer, PretrainedConfig
46
+
47
+ import diffusers
48
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionXLPipeline, UNet2DConditionModel
49
+ from diffusers.optimization import get_scheduler
50
+ from diffusers.training_utils import EMAModel, compute_snr
51
+ from diffusers.utils import check_min_version, is_wandb_available
52
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
53
+ from diffusers.utils.import_utils import is_torch_npu_available, is_xformers_available
54
+ from diffusers.utils.torch_utils import is_compiled_module
55
+
56
+
57
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
58
+ check_min_version("0.39.0.dev0")
59
+
60
+ logger = get_logger(__name__)
61
+ if is_torch_npu_available():
62
+ import torch_npu
63
+
64
+ torch.npu.config.allow_internal_format = False
65
+
66
+ DATASET_NAME_MAPPING = {
67
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
68
+ }
69
+
70
+
71
+ def save_model_card(
72
+ repo_id: str,
73
+ images: list = None,
74
+ validation_prompt: str = None,
75
+ base_model: str = None,
76
+ dataset_name: str = None,
77
+ repo_folder: str = None,
78
+ vae_path: str = None,
79
+ ):
80
+ img_str = ""
81
+ if images is not None:
82
+ for i, image in enumerate(images):
83
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
84
+ img_str += f"![img_{i}](./image_{i}.png)\n"
85
+
86
+ model_description = f"""
87
+ # Text-to-image finetuning - {repo_id}
88
+
89
+ This pipeline was finetuned from **{base_model}** on the **{dataset_name}** dataset. Below are some example images generated with the finetuned pipeline using the following prompt: {validation_prompt}: \n
90
+ {img_str}
91
+
92
+ Special VAE used for training: {vae_path}.
93
+ """
94
+
95
+ model_card = load_or_create_model_card(
96
+ repo_id_or_path=repo_id,
97
+ from_training=True,
98
+ license="creativeml-openrail-m",
99
+ base_model=base_model,
100
+ model_description=model_description,
101
+ inference=True,
102
+ )
103
+
104
+ tags = [
105
+ "stable-diffusion-xl",
106
+ "stable-diffusion-xl-diffusers",
107
+ "text-to-image",
108
+ "diffusers-training",
109
+ "diffusers",
110
+ ]
111
+ model_card = populate_model_card(model_card, tags=tags)
112
+
113
+ model_card.save(os.path.join(repo_folder, "README.md"))
114
+
115
+
116
+ def import_model_class_from_model_name_or_path(
117
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
118
+ ):
119
+ text_encoder_config = PretrainedConfig.from_pretrained(
120
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
121
+ )
122
+ model_class = text_encoder_config.architectures[0]
123
+
124
+ if model_class == "CLIPTextModel":
125
+ from transformers import CLIPTextModel
126
+
127
+ return CLIPTextModel
128
+ elif model_class == "CLIPTextModelWithProjection":
129
+ from transformers import CLIPTextModelWithProjection
130
+
131
+ return CLIPTextModelWithProjection
132
+ else:
133
+ raise ValueError(f"{model_class} is not supported.")
134
+
135
+
136
+ def parse_args(input_args=None):
137
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
138
+ parser.add_argument(
139
+ "--pretrained_model_name_or_path",
140
+ type=str,
141
+ default=None,
142
+ required=True,
143
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
144
+ )
145
+ parser.add_argument(
146
+ "--pretrained_vae_model_name_or_path",
147
+ type=str,
148
+ default=None,
149
+ help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
150
+ )
151
+ parser.add_argument(
152
+ "--revision",
153
+ type=str,
154
+ default=None,
155
+ required=False,
156
+ help="Revision of pretrained model identifier from huggingface.co/models.",
157
+ )
158
+ parser.add_argument(
159
+ "--variant",
160
+ type=str,
161
+ default=None,
162
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
163
+ )
164
+ parser.add_argument(
165
+ "--dataset_name",
166
+ type=str,
167
+ default=None,
168
+ help=(
169
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
170
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
171
+ " or to a folder containing files that 🤗 Datasets can understand."
172
+ ),
173
+ )
174
+ parser.add_argument(
175
+ "--dataset_config_name",
176
+ type=str,
177
+ default=None,
178
+ help="The config of the Dataset, leave as None if there's only one config.",
179
+ )
180
+ parser.add_argument(
181
+ "--train_data_dir",
182
+ type=str,
183
+ default=None,
184
+ help=(
185
+ "A folder containing the training data. Folder contents must follow the structure described in"
186
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
187
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
188
+ ),
189
+ )
190
+ parser.add_argument(
191
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
192
+ )
193
+ parser.add_argument(
194
+ "--caption_column",
195
+ type=str,
196
+ default="text",
197
+ help="The column of the dataset containing a caption or a list of captions.",
198
+ )
199
+ parser.add_argument(
200
+ "--validation_prompt",
201
+ type=str,
202
+ default=None,
203
+ help="A prompt that is used during validation to verify that the model is learning.",
204
+ )
205
+ parser.add_argument(
206
+ "--num_validation_images",
207
+ type=int,
208
+ default=4,
209
+ help="Number of images that should be generated during validation with `validation_prompt`.",
210
+ )
211
+ parser.add_argument(
212
+ "--validation_epochs",
213
+ type=int,
214
+ default=1,
215
+ help=(
216
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
217
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
218
+ ),
219
+ )
220
+ parser.add_argument(
221
+ "--max_train_samples",
222
+ type=int,
223
+ default=None,
224
+ help=(
225
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
226
+ "value if set."
227
+ ),
228
+ )
229
+ parser.add_argument(
230
+ "--proportion_empty_prompts",
231
+ type=float,
232
+ default=0,
233
+ help="Proportion of image prompts to be replaced with empty strings. Defaults to 0 (no prompt replacement).",
234
+ )
235
+ parser.add_argument(
236
+ "--output_dir",
237
+ type=str,
238
+ default="sdxl-model-finetuned",
239
+ help="The output directory where the model predictions and checkpoints will be written.",
240
+ )
241
+ parser.add_argument(
242
+ "--cache_dir",
243
+ type=str,
244
+ default=None,
245
+ help="The directory where the downloaded models and datasets will be stored.",
246
+ )
247
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
248
+ parser.add_argument(
249
+ "--resolution",
250
+ type=int,
251
+ default=1024,
252
+ help=(
253
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
254
+ " resolution"
255
+ ),
256
+ )
257
+ parser.add_argument(
258
+ "--center_crop",
259
+ default=False,
260
+ action="store_true",
261
+ help=(
262
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
263
+ " cropped. The images will be resized to the resolution first before cropping."
264
+ ),
265
+ )
266
+ parser.add_argument(
267
+ "--random_flip",
268
+ action="store_true",
269
+ help="whether to randomly flip images horizontally",
270
+ )
271
+ parser.add_argument(
272
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
273
+ )
274
+ parser.add_argument("--num_train_epochs", type=int, default=100)
275
+ parser.add_argument(
276
+ "--max_train_steps",
277
+ type=int,
278
+ default=None,
279
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
280
+ )
281
+ parser.add_argument(
282
+ "--checkpointing_steps",
283
+ type=int,
284
+ default=500,
285
+ help=(
286
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
287
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
288
+ " training using `--resume_from_checkpoint`."
289
+ ),
290
+ )
291
+ parser.add_argument(
292
+ "--checkpoints_total_limit",
293
+ type=int,
294
+ default=None,
295
+ help=("Max number of checkpoints to store."),
296
+ )
297
+ parser.add_argument(
298
+ "--resume_from_checkpoint",
299
+ type=str,
300
+ default=None,
301
+ help=(
302
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
303
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
304
+ ),
305
+ )
306
+ parser.add_argument(
307
+ "--gradient_accumulation_steps",
308
+ type=int,
309
+ default=1,
310
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
311
+ )
312
+ parser.add_argument(
313
+ "--gradient_checkpointing",
314
+ action="store_true",
315
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
316
+ )
317
+ parser.add_argument(
318
+ "--learning_rate",
319
+ type=float,
320
+ default=1e-4,
321
+ help="Initial learning rate (after the potential warmup period) to use.",
322
+ )
323
+ parser.add_argument(
324
+ "--scale_lr",
325
+ action="store_true",
326
+ default=False,
327
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
328
+ )
329
+ parser.add_argument(
330
+ "--lr_scheduler",
331
+ type=str,
332
+ default="constant",
333
+ help=(
334
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
335
+ ' "constant", "constant_with_warmup"]'
336
+ ),
337
+ )
338
+ parser.add_argument(
339
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
340
+ )
341
+ parser.add_argument(
342
+ "--timestep_bias_strategy",
343
+ type=str,
344
+ default="none",
345
+ choices=["earlier", "later", "range", "none"],
346
+ help=(
347
+ "The timestep bias strategy, which may help direct the model toward learning low or high frequency details."
348
+ " Choices: ['earlier', 'later', 'range', 'none']."
349
+ " The default is 'none', which means no bias is applied, and training proceeds normally."
350
+ " The value of 'later' will increase the frequency of the model's final training timesteps."
351
+ ),
352
+ )
353
+ parser.add_argument(
354
+ "--timestep_bias_multiplier",
355
+ type=float,
356
+ default=1.0,
357
+ help=(
358
+ "The multiplier for the bias. Defaults to 1.0, which means no bias is applied."
359
+ " A value of 2.0 will double the weight of the bias, and a value of 0.5 will halve it."
360
+ ),
361
+ )
362
+ parser.add_argument(
363
+ "--timestep_bias_begin",
364
+ type=int,
365
+ default=0,
366
+ help=(
367
+ "When using `--timestep_bias_strategy=range`, the beginning (inclusive) timestep to bias."
368
+ " Defaults to zero, which equates to having no specific bias."
369
+ ),
370
+ )
371
+ parser.add_argument(
372
+ "--timestep_bias_end",
373
+ type=int,
374
+ default=1000,
375
+ help=(
376
+ "When using `--timestep_bias_strategy=range`, the final timestep (inclusive) to bias."
377
+ " Defaults to 1000, which is the number of timesteps that Stable Diffusion is trained on."
378
+ ),
379
+ )
380
+ parser.add_argument(
381
+ "--timestep_bias_portion",
382
+ type=float,
383
+ default=0.25,
384
+ help=(
385
+ "The portion of timesteps to bias. Defaults to 0.25, which 25% of timesteps will be biased."
386
+ " A value of 0.5 will bias one half of the timesteps. The value provided for `--timestep_bias_strategy` determines"
387
+ " whether the biased portions are in the earlier or later timesteps."
388
+ ),
389
+ )
390
+ parser.add_argument(
391
+ "--snr_gamma",
392
+ type=float,
393
+ default=None,
394
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
395
+ "More details here: https://huggingface.co/papers/2303.09556.",
396
+ )
397
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
398
+ parser.add_argument(
399
+ "--allow_tf32",
400
+ action="store_true",
401
+ help=(
402
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
403
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
404
+ ),
405
+ )
406
+ parser.add_argument(
407
+ "--dataloader_num_workers",
408
+ type=int,
409
+ default=0,
410
+ help=(
411
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
412
+ ),
413
+ )
414
+ parser.add_argument(
415
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
416
+ )
417
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
418
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
419
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
420
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
421
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
422
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
423
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
424
+ parser.add_argument(
425
+ "--prediction_type",
426
+ type=str,
427
+ default=None,
428
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
429
+ )
430
+ parser.add_argument(
431
+ "--hub_model_id",
432
+ type=str,
433
+ default=None,
434
+ help="The name of the repository to keep in sync with the local `output_dir`.",
435
+ )
436
+ parser.add_argument(
437
+ "--logging_dir",
438
+ type=str,
439
+ default="logs",
440
+ help=(
441
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
442
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
443
+ ),
444
+ )
445
+ parser.add_argument(
446
+ "--report_to",
447
+ type=str,
448
+ default="tensorboard",
449
+ help=(
450
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
451
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
452
+ ),
453
+ )
454
+ parser.add_argument(
455
+ "--mixed_precision",
456
+ type=str,
457
+ default=None,
458
+ choices=["no", "fp16", "bf16"],
459
+ help=(
460
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
461
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
462
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
463
+ ),
464
+ )
465
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
466
+ parser.add_argument(
467
+ "--enable_npu_flash_attention", action="store_true", help="Whether or not to use npu flash attention."
468
+ )
469
+ parser.add_argument(
470
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
471
+ )
472
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
473
+ parser.add_argument(
474
+ "--image_interpolation_mode",
475
+ type=str,
476
+ default="lanczos",
477
+ choices=[
478
+ f.lower() for f in dir(transforms.InterpolationMode) if not f.startswith("__") and not f.endswith("__")
479
+ ],
480
+ help="The image interpolation method to use for resizing images.",
481
+ )
482
+
483
+ if input_args is not None:
484
+ args = parser.parse_args(input_args)
485
+ else:
486
+ args = parser.parse_args()
487
+
488
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
489
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
490
+ args.local_rank = env_local_rank
491
+
492
+ # Sanity checks
493
+ if args.dataset_name is None and args.train_data_dir is None:
494
+ raise ValueError("Need either a dataset name or a training folder.")
495
+ if args.proportion_empty_prompts < 0 or args.proportion_empty_prompts > 1:
496
+ raise ValueError("`--proportion_empty_prompts` must be in the range [0, 1].")
497
+
498
+ return args
499
+
500
+
501
+ # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
502
+ def encode_prompt(batch, text_encoders, tokenizers, proportion_empty_prompts, caption_column, is_train=True):
503
+ prompt_embeds_list = []
504
+ prompt_batch = batch[caption_column]
505
+
506
+ captions = []
507
+ for caption in prompt_batch:
508
+ if random.random() < proportion_empty_prompts:
509
+ captions.append("")
510
+ elif isinstance(caption, str):
511
+ captions.append(caption)
512
+ elif isinstance(caption, (list, np.ndarray)):
513
+ # take a random caption if there are multiple
514
+ captions.append(random.choice(caption) if is_train else caption[0])
515
+
516
+ with torch.no_grad():
517
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
518
+ text_inputs = tokenizer(
519
+ captions,
520
+ padding="max_length",
521
+ max_length=tokenizer.model_max_length,
522
+ truncation=True,
523
+ return_tensors="pt",
524
+ )
525
+ text_input_ids = text_inputs.input_ids
526
+ prompt_embeds = text_encoder(
527
+ text_input_ids.to(text_encoder.device),
528
+ output_hidden_states=True,
529
+ return_dict=False,
530
+ )
531
+
532
+ # We are only ALWAYS interested in the pooled output of the final text encoder
533
+ pooled_prompt_embeds = prompt_embeds[0]
534
+ prompt_embeds = prompt_embeds[-1][-2]
535
+ bs_embed, seq_len, _ = prompt_embeds.shape
536
+ prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
537
+ prompt_embeds_list.append(prompt_embeds)
538
+
539
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
540
+ pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
541
+ return {"prompt_embeds": prompt_embeds.cpu(), "pooled_prompt_embeds": pooled_prompt_embeds.cpu()}
542
+
543
+
544
+ def compute_vae_encodings(batch, vae):
545
+ images = batch.pop("pixel_values")
546
+ pixel_values = torch.stack(list(images))
547
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
548
+ pixel_values = pixel_values.to(vae.device, dtype=vae.dtype)
549
+
550
+ with torch.no_grad():
551
+ model_input = vae.encode(pixel_values).latent_dist.sample()
552
+ model_input = model_input * vae.config.scaling_factor
553
+
554
+ # There might have slightly performance improvement
555
+ # by changing model_input.cpu() to accelerator.gather(model_input)
556
+ return {"model_input": model_input.cpu()}
557
+
558
+
559
+ def generate_timestep_weights(args, num_timesteps):
560
+ weights = torch.ones(num_timesteps)
561
+
562
+ # Determine the indices to bias
563
+ num_to_bias = int(args.timestep_bias_portion * num_timesteps)
564
+
565
+ if args.timestep_bias_strategy == "later":
566
+ bias_indices = slice(-num_to_bias, None)
567
+ elif args.timestep_bias_strategy == "earlier":
568
+ bias_indices = slice(0, num_to_bias)
569
+ elif args.timestep_bias_strategy == "range":
570
+ # Out of the possible 1000 timesteps, we might want to focus on eg. 200-500.
571
+ range_begin = args.timestep_bias_begin
572
+ range_end = args.timestep_bias_end
573
+ if range_begin < 0:
574
+ raise ValueError(
575
+ "When using the range strategy for timestep bias, you must provide a beginning timestep greater or equal to zero."
576
+ )
577
+ if range_end > num_timesteps:
578
+ raise ValueError(
579
+ "When using the range strategy for timestep bias, you must provide an ending timestep smaller than the number of timesteps."
580
+ )
581
+ bias_indices = slice(range_begin, range_end)
582
+ else: # 'none' or any other string
583
+ return weights
584
+ if args.timestep_bias_multiplier <= 0:
585
+ return ValueError(
586
+ "The parameter --timestep_bias_multiplier is not intended to be used to disable the training of specific timesteps."
587
+ " If it was intended to disable timestep bias, use `--timestep_bias_strategy none` instead."
588
+ " A timestep bias multiplier less than or equal to 0 is not allowed."
589
+ )
590
+
591
+ # Apply the bias
592
+ weights[bias_indices] *= args.timestep_bias_multiplier
593
+
594
+ # Normalize
595
+ weights /= weights.sum()
596
+
597
+ return weights
598
+
599
+
600
+ def main(args):
601
+ if args.report_to == "wandb" and args.hub_token is not None:
602
+ raise ValueError(
603
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
604
+ " Please use `hf auth login` to authenticate with the Hub."
605
+ )
606
+
607
+ logging_dir = Path(args.output_dir, args.logging_dir)
608
+
609
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
610
+
611
+ if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
612
+ # due to pytorch#99272, MPS does not yet support bfloat16.
613
+ raise ValueError(
614
+ "Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
615
+ )
616
+
617
+ accelerator = Accelerator(
618
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
619
+ mixed_precision=args.mixed_precision,
620
+ log_with=args.report_to,
621
+ project_config=accelerator_project_config,
622
+ )
623
+
624
+ # Disable AMP for MPS.
625
+ if torch.backends.mps.is_available():
626
+ accelerator.native_amp = False
627
+
628
+ if args.report_to == "wandb":
629
+ if not is_wandb_available():
630
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
631
+ import wandb
632
+
633
+ # Make one log on every process with the configuration for debugging.
634
+ logging.basicConfig(
635
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
636
+ datefmt="%m/%d/%Y %H:%M:%S",
637
+ level=logging.INFO,
638
+ )
639
+ logger.info(accelerator.state, main_process_only=False)
640
+ if accelerator.is_local_main_process:
641
+ datasets.utils.logging.set_verbosity_warning()
642
+ transformers.utils.logging.set_verbosity_warning()
643
+ diffusers.utils.logging.set_verbosity_info()
644
+ else:
645
+ datasets.utils.logging.set_verbosity_error()
646
+ transformers.utils.logging.set_verbosity_error()
647
+ diffusers.utils.logging.set_verbosity_error()
648
+
649
+ # If passed along, set the training seed now.
650
+ if args.seed is not None:
651
+ set_seed(args.seed)
652
+
653
+ # Handle the repository creation
654
+ if accelerator.is_main_process:
655
+ if args.output_dir is not None:
656
+ os.makedirs(args.output_dir, exist_ok=True)
657
+
658
+ if args.push_to_hub:
659
+ repo_id = create_repo(
660
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
661
+ ).repo_id
662
+
663
+ # Load the tokenizers
664
+ tokenizer_one = AutoTokenizer.from_pretrained(
665
+ args.pretrained_model_name_or_path,
666
+ subfolder="tokenizer",
667
+ revision=args.revision,
668
+ use_fast=False,
669
+ )
670
+ tokenizer_two = AutoTokenizer.from_pretrained(
671
+ args.pretrained_model_name_or_path,
672
+ subfolder="tokenizer_2",
673
+ revision=args.revision,
674
+ use_fast=False,
675
+ )
676
+
677
+ # import correct text encoder classes
678
+ text_encoder_cls_one = import_model_class_from_model_name_or_path(
679
+ args.pretrained_model_name_or_path, args.revision
680
+ )
681
+ text_encoder_cls_two = import_model_class_from_model_name_or_path(
682
+ args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
683
+ )
684
+
685
+ # Load scheduler and models
686
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
687
+ # Check for terminal SNR in combination with SNR Gamma
688
+ text_encoder_one = text_encoder_cls_one.from_pretrained(
689
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
690
+ )
691
+ text_encoder_two = text_encoder_cls_two.from_pretrained(
692
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
693
+ )
694
+ vae_path = (
695
+ args.pretrained_model_name_or_path
696
+ if args.pretrained_vae_model_name_or_path is None
697
+ else args.pretrained_vae_model_name_or_path
698
+ )
699
+ vae = AutoencoderKL.from_pretrained(
700
+ vae_path,
701
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
702
+ revision=args.revision,
703
+ variant=args.variant,
704
+ )
705
+ unet = UNet2DConditionModel.from_pretrained(
706
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
707
+ )
708
+
709
+ # Freeze vae and text encoders.
710
+ vae.requires_grad_(False)
711
+ text_encoder_one.requires_grad_(False)
712
+ text_encoder_two.requires_grad_(False)
713
+ # Set unet as trainable.
714
+ unet.train()
715
+
716
+ # For mixed precision training we cast all non-trainable weights to half-precision
717
+ # as these weights are only used for inference, keeping weights in full precision is not required.
718
+ weight_dtype = torch.float32
719
+ if accelerator.mixed_precision == "fp16":
720
+ weight_dtype = torch.float16
721
+ elif accelerator.mixed_precision == "bf16":
722
+ weight_dtype = torch.bfloat16
723
+
724
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
725
+ # The VAE is in float32 to avoid NaN losses.
726
+ vae.to(accelerator.device, dtype=torch.float32)
727
+ text_encoder_one.to(accelerator.device, dtype=weight_dtype)
728
+ text_encoder_two.to(accelerator.device, dtype=weight_dtype)
729
+
730
+ # Create EMA for the unet.
731
+ if args.use_ema:
732
+ ema_unet = UNet2DConditionModel.from_pretrained(
733
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
734
+ )
735
+ ema_unet = EMAModel(ema_unet.parameters(), model_cls=UNet2DConditionModel, model_config=ema_unet.config)
736
+ if args.enable_npu_flash_attention:
737
+ if is_torch_npu_available():
738
+ logger.info("npu flash attention enabled.")
739
+ unet.enable_npu_flash_attention()
740
+ else:
741
+ raise ValueError("npu flash attention requires torch_npu extensions and is supported only on npu devices.")
742
+ if args.enable_xformers_memory_efficient_attention:
743
+ if is_xformers_available():
744
+ import xformers
745
+
746
+ xformers_version = version.parse(xformers.__version__)
747
+ if xformers_version == version.parse("0.0.16"):
748
+ logger.warning(
749
+ "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."
750
+ )
751
+ unet.enable_xformers_memory_efficient_attention()
752
+ else:
753
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
754
+
755
+ # `accelerate` 0.16.0 will have better support for customized saving
756
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
757
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
758
+ def save_model_hook(models, weights, output_dir):
759
+ if accelerator.is_main_process:
760
+ if args.use_ema:
761
+ ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
762
+
763
+ for i, model in enumerate(models):
764
+ model.save_pretrained(os.path.join(output_dir, "unet"))
765
+
766
+ # make sure to pop weight so that corresponding model is not saved again
767
+ if weights:
768
+ weights.pop()
769
+
770
+ def load_model_hook(models, input_dir):
771
+ if args.use_ema:
772
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
773
+ ema_unet.load_state_dict(load_model.state_dict())
774
+ ema_unet.to(accelerator.device)
775
+ del load_model
776
+
777
+ for _ in range(len(models)):
778
+ # pop models so that they are not loaded again
779
+ model = models.pop()
780
+
781
+ # load diffusers style into model
782
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
783
+ model.register_to_config(**load_model.config)
784
+
785
+ model.load_state_dict(load_model.state_dict())
786
+ del load_model
787
+
788
+ accelerator.register_save_state_pre_hook(save_model_hook)
789
+ accelerator.register_load_state_pre_hook(load_model_hook)
790
+
791
+ if args.gradient_checkpointing:
792
+ unet.enable_gradient_checkpointing()
793
+
794
+ # Enable TF32 for faster training on Ampere GPUs,
795
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
796
+ if args.allow_tf32:
797
+ torch.backends.cuda.matmul.allow_tf32 = True
798
+
799
+ if args.scale_lr:
800
+ args.learning_rate = (
801
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
802
+ )
803
+
804
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
805
+ if args.use_8bit_adam:
806
+ try:
807
+ import bitsandbytes as bnb
808
+ except ImportError:
809
+ raise ImportError(
810
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
811
+ )
812
+
813
+ optimizer_class = bnb.optim.AdamW8bit
814
+ else:
815
+ optimizer_class = torch.optim.AdamW
816
+
817
+ # Optimizer creation
818
+ params_to_optimize = unet.parameters()
819
+ optimizer = optimizer_class(
820
+ params_to_optimize,
821
+ lr=args.learning_rate,
822
+ betas=(args.adam_beta1, args.adam_beta2),
823
+ weight_decay=args.adam_weight_decay,
824
+ eps=args.adam_epsilon,
825
+ )
826
+
827
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
828
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
829
+
830
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
831
+ # download the dataset.
832
+ if args.dataset_name is not None:
833
+ # Downloading and loading a dataset from the hub.
834
+ dataset = load_dataset(
835
+ args.dataset_name, args.dataset_config_name, cache_dir=args.cache_dir, data_dir=args.train_data_dir
836
+ )
837
+ else:
838
+ data_files = {}
839
+ if args.train_data_dir is not None:
840
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
841
+ dataset = load_dataset(
842
+ "imagefolder",
843
+ data_files=data_files,
844
+ cache_dir=args.cache_dir,
845
+ )
846
+ # See more about loading custom images at
847
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
848
+
849
+ # Preprocessing the datasets.
850
+ # We need to tokenize inputs and targets.
851
+ column_names = dataset["train"].column_names
852
+
853
+ # 6. Get the column names for input/target.
854
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
855
+ if args.image_column is None:
856
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
857
+ else:
858
+ image_column = args.image_column
859
+ if image_column not in column_names:
860
+ raise ValueError(
861
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
862
+ )
863
+ if args.caption_column is None:
864
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
865
+ else:
866
+ caption_column = args.caption_column
867
+ if caption_column not in column_names:
868
+ raise ValueError(
869
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
870
+ )
871
+
872
+ # Preprocessing the datasets.
873
+ interpolation = getattr(transforms.InterpolationMode, args.image_interpolation_mode.upper(), None)
874
+ if interpolation is None:
875
+ raise ValueError(f"Unsupported interpolation mode {interpolation=}.")
876
+ train_resize = transforms.Resize(args.resolution, interpolation=interpolation)
877
+ train_crop = transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution)
878
+ train_flip = transforms.RandomHorizontalFlip(p=1.0)
879
+ train_transforms = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
880
+
881
+ def preprocess_train(examples):
882
+ images = [image.convert("RGB") for image in examples[image_column]]
883
+ # image aug
884
+ original_sizes = []
885
+ all_images = []
886
+ crop_top_lefts = []
887
+ for image in images:
888
+ original_sizes.append((image.height, image.width))
889
+ image = train_resize(image)
890
+ if args.random_flip and random.random() < 0.5:
891
+ # flip
892
+ image = train_flip(image)
893
+ if args.center_crop:
894
+ y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
895
+ x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
896
+ image = train_crop(image)
897
+ else:
898
+ y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
899
+ image = crop(image, y1, x1, h, w)
900
+ crop_top_left = (y1, x1)
901
+ crop_top_lefts.append(crop_top_left)
902
+ image = train_transforms(image)
903
+ all_images.append(image)
904
+
905
+ examples["original_sizes"] = original_sizes
906
+ examples["crop_top_lefts"] = crop_top_lefts
907
+ examples["pixel_values"] = all_images
908
+ return examples
909
+
910
+ with accelerator.main_process_first():
911
+ if args.max_train_samples is not None:
912
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
913
+ # Set the training transforms
914
+ train_dataset = dataset["train"].with_transform(preprocess_train)
915
+
916
+ # Let's first compute all the embeddings so that we can free up the text encoders
917
+ # from memory. We will pre-compute the VAE encodings too.
918
+ text_encoders = [text_encoder_one, text_encoder_two]
919
+ tokenizers = [tokenizer_one, tokenizer_two]
920
+ compute_embeddings_fn = functools.partial(
921
+ encode_prompt,
922
+ text_encoders=text_encoders,
923
+ tokenizers=tokenizers,
924
+ proportion_empty_prompts=args.proportion_empty_prompts,
925
+ caption_column=args.caption_column,
926
+ )
927
+ compute_vae_encodings_fn = functools.partial(compute_vae_encodings, vae=vae)
928
+ with accelerator.main_process_first():
929
+ from datasets.fingerprint import Hasher
930
+
931
+ # fingerprint used by the cache for the other processes to load the result
932
+ # details: https://github.com/huggingface/diffusers/pull/4038#discussion_r1266078401
933
+ new_fingerprint = Hasher.hash(args)
934
+ new_fingerprint_for_vae = Hasher.hash((vae_path, args))
935
+ train_dataset_with_embeddings = train_dataset.map(
936
+ compute_embeddings_fn, batched=True, new_fingerprint=new_fingerprint
937
+ )
938
+ train_dataset_with_vae = train_dataset.map(
939
+ compute_vae_encodings_fn,
940
+ batched=True,
941
+ batch_size=args.train_batch_size,
942
+ new_fingerprint=new_fingerprint_for_vae,
943
+ )
944
+ precomputed_dataset = concatenate_datasets(
945
+ [train_dataset_with_embeddings, train_dataset_with_vae.remove_columns(["image", "text"])], axis=1
946
+ )
947
+ precomputed_dataset = precomputed_dataset.with_transform(preprocess_train)
948
+
949
+ del compute_vae_encodings_fn, compute_embeddings_fn, text_encoder_one, text_encoder_two
950
+ del text_encoders, tokenizers, vae
951
+ gc.collect()
952
+ if is_torch_npu_available():
953
+ torch_npu.npu.empty_cache()
954
+ elif torch.cuda.is_available():
955
+ torch.cuda.empty_cache()
956
+
957
+ def collate_fn(examples):
958
+ model_input = torch.stack([torch.tensor(example["model_input"]) for example in examples])
959
+ original_sizes = [example["original_sizes"] for example in examples]
960
+ crop_top_lefts = [example["crop_top_lefts"] for example in examples]
961
+ prompt_embeds = torch.stack([torch.tensor(example["prompt_embeds"]) for example in examples])
962
+ pooled_prompt_embeds = torch.stack([torch.tensor(example["pooled_prompt_embeds"]) for example in examples])
963
+
964
+ return {
965
+ "model_input": model_input,
966
+ "prompt_embeds": prompt_embeds,
967
+ "pooled_prompt_embeds": pooled_prompt_embeds,
968
+ "original_sizes": original_sizes,
969
+ "crop_top_lefts": crop_top_lefts,
970
+ }
971
+
972
+ # DataLoaders creation:
973
+ train_dataloader = torch.utils.data.DataLoader(
974
+ precomputed_dataset,
975
+ shuffle=True,
976
+ collate_fn=collate_fn,
977
+ batch_size=args.train_batch_size,
978
+ num_workers=args.dataloader_num_workers,
979
+ )
980
+
981
+ # Scheduler and math around the number of training steps.
982
+ overrode_max_train_steps = False
983
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
984
+ if args.max_train_steps is None:
985
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
986
+ overrode_max_train_steps = True
987
+
988
+ lr_scheduler = get_scheduler(
989
+ args.lr_scheduler,
990
+ optimizer=optimizer,
991
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
992
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
993
+ )
994
+
995
+ # Prepare everything with our `accelerator`.
996
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
997
+ unet, optimizer, train_dataloader, lr_scheduler
998
+ )
999
+
1000
+ if args.use_ema:
1001
+ ema_unet.to(accelerator.device)
1002
+
1003
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1004
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1005
+ if overrode_max_train_steps:
1006
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1007
+ # Afterwards we recalculate our number of training epochs
1008
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1009
+
1010
+ # We need to initialize the trackers we use, and also store our configuration.
1011
+ # The trackers initializes automatically on the main process.
1012
+ if accelerator.is_main_process:
1013
+ accelerator.init_trackers("text2image-fine-tune-sdxl", config=vars(args))
1014
+
1015
+ # Function for unwrapping if torch.compile() was used in accelerate.
1016
+ def unwrap_model(model):
1017
+ model = accelerator.unwrap_model(model)
1018
+ model = model._orig_mod if is_compiled_module(model) else model
1019
+ return model
1020
+
1021
+ if torch.backends.mps.is_available() or "playground" in args.pretrained_model_name_or_path:
1022
+ autocast_ctx = nullcontext()
1023
+ else:
1024
+ autocast_ctx = torch.autocast(accelerator.device.type)
1025
+
1026
+ # Train!
1027
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1028
+
1029
+ logger.info("***** Running training *****")
1030
+ logger.info(f" Num examples = {len(precomputed_dataset)}")
1031
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1032
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1033
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1034
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1035
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1036
+ global_step = 0
1037
+ first_epoch = 0
1038
+
1039
+ # Potentially load in the weights and states from a previous save
1040
+ if args.resume_from_checkpoint:
1041
+ if args.resume_from_checkpoint != "latest":
1042
+ path = os.path.basename(args.resume_from_checkpoint)
1043
+ else:
1044
+ # Get the most recent checkpoint
1045
+ dirs = os.listdir(args.output_dir)
1046
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1047
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1048
+ path = dirs[-1] if len(dirs) > 0 else None
1049
+
1050
+ if path is None:
1051
+ accelerator.print(
1052
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1053
+ )
1054
+ args.resume_from_checkpoint = None
1055
+ initial_global_step = 0
1056
+ else:
1057
+ accelerator.print(f"Resuming from checkpoint {path}")
1058
+ accelerator.load_state(os.path.join(args.output_dir, path))
1059
+ global_step = int(path.split("-")[1])
1060
+
1061
+ initial_global_step = global_step
1062
+ first_epoch = global_step // num_update_steps_per_epoch
1063
+
1064
+ else:
1065
+ initial_global_step = 0
1066
+
1067
+ progress_bar = tqdm(
1068
+ range(0, args.max_train_steps),
1069
+ initial=initial_global_step,
1070
+ desc="Steps",
1071
+ # Only show the progress bar once on each machine.
1072
+ disable=not accelerator.is_local_main_process,
1073
+ )
1074
+
1075
+ for epoch in range(first_epoch, args.num_train_epochs):
1076
+ train_loss = 0.0
1077
+ for step, batch in enumerate(train_dataloader):
1078
+ with accelerator.accumulate(unet):
1079
+ # Sample noise that we'll add to the latents
1080
+ model_input = batch["model_input"].to(accelerator.device)
1081
+ noise = torch.randn_like(model_input)
1082
+ if args.noise_offset:
1083
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
1084
+ noise += args.noise_offset * torch.randn(
1085
+ (model_input.shape[0], model_input.shape[1], 1, 1), device=model_input.device
1086
+ )
1087
+
1088
+ bsz = model_input.shape[0]
1089
+ if args.timestep_bias_strategy == "none":
1090
+ # Sample a random timestep for each image without bias.
1091
+ timesteps = torch.randint(
1092
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=model_input.device
1093
+ )
1094
+ else:
1095
+ # Sample a random timestep for each image, potentially biased by the timestep weights.
1096
+ # Biasing the timestep weights allows us to spend less time training irrelevant timesteps.
1097
+ weights = generate_timestep_weights(args, noise_scheduler.config.num_train_timesteps).to(
1098
+ model_input.device
1099
+ )
1100
+ timesteps = torch.multinomial(weights, bsz, replacement=True).long()
1101
+
1102
+ # Add noise to the model input according to the noise magnitude at each timestep
1103
+ # (this is the forward diffusion process)
1104
+ noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps).to(dtype=weight_dtype)
1105
+
1106
+ # time ids
1107
+ def compute_time_ids(original_size, crops_coords_top_left):
1108
+ # Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
1109
+ target_size = (args.resolution, args.resolution)
1110
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1111
+ add_time_ids = torch.tensor([add_time_ids], device=accelerator.device, dtype=weight_dtype)
1112
+ return add_time_ids
1113
+
1114
+ add_time_ids = torch.cat(
1115
+ [compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
1116
+ )
1117
+
1118
+ # Predict the noise residual
1119
+ unet_added_conditions = {"time_ids": add_time_ids}
1120
+ prompt_embeds = batch["prompt_embeds"].to(accelerator.device, dtype=weight_dtype)
1121
+ pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(accelerator.device)
1122
+ unet_added_conditions.update({"text_embeds": pooled_prompt_embeds})
1123
+ model_pred = unet(
1124
+ noisy_model_input,
1125
+ timesteps,
1126
+ prompt_embeds,
1127
+ added_cond_kwargs=unet_added_conditions,
1128
+ return_dict=False,
1129
+ )[0]
1130
+
1131
+ # Get the target for loss depending on the prediction type
1132
+ if args.prediction_type is not None:
1133
+ # set prediction_type of scheduler if defined
1134
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
1135
+
1136
+ if noise_scheduler.config.prediction_type == "epsilon":
1137
+ target = noise
1138
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1139
+ target = noise_scheduler.get_velocity(model_input, noise, timesteps)
1140
+ elif noise_scheduler.config.prediction_type == "sample":
1141
+ # We set the target to latents here, but the model_pred will return the noise sample prediction.
1142
+ target = model_input
1143
+ # We will have to subtract the noise residual from the prediction to get the target sample.
1144
+ model_pred = model_pred - noise
1145
+ else:
1146
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1147
+
1148
+ if args.snr_gamma is None:
1149
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1150
+ else:
1151
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
1152
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
1153
+ # This is discussed in Section 4.2 of the same paper.
1154
+ snr = compute_snr(noise_scheduler, timesteps)
1155
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
1156
+ dim=1
1157
+ )[0]
1158
+ if noise_scheduler.config.prediction_type == "epsilon":
1159
+ mse_loss_weights = mse_loss_weights / snr
1160
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1161
+ mse_loss_weights = mse_loss_weights / (snr + 1)
1162
+
1163
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
1164
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
1165
+ loss = loss.mean()
1166
+
1167
+ # Gather the losses across all processes for logging (if we use distributed training).
1168
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
1169
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1170
+
1171
+ # Backpropagate
1172
+ accelerator.backward(loss)
1173
+ if accelerator.sync_gradients:
1174
+ params_to_clip = unet.parameters()
1175
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1176
+ optimizer.step()
1177
+ lr_scheduler.step()
1178
+ optimizer.zero_grad()
1179
+
1180
+ # Checks if the accelerator has performed an optimization step behind the scenes
1181
+ if accelerator.sync_gradients:
1182
+ if args.use_ema:
1183
+ ema_unet.step(unet.parameters())
1184
+ progress_bar.update(1)
1185
+ global_step += 1
1186
+ accelerator.log({"train_loss": train_loss}, step=global_step)
1187
+ train_loss = 0.0
1188
+
1189
+ # DeepSpeed requires saving weights on every device; saving weights only on the main process would cause issues.
1190
+ if accelerator.distributed_type == DistributedType.DEEPSPEED or accelerator.is_main_process:
1191
+ if global_step % args.checkpointing_steps == 0:
1192
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1193
+ if args.checkpoints_total_limit is not None:
1194
+ checkpoints = os.listdir(args.output_dir)
1195
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1196
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1197
+
1198
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1199
+ if len(checkpoints) >= args.checkpoints_total_limit:
1200
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1201
+ removing_checkpoints = checkpoints[0:num_to_remove]
1202
+
1203
+ logger.info(
1204
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1205
+ )
1206
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1207
+
1208
+ for removing_checkpoint in removing_checkpoints:
1209
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1210
+ shutil.rmtree(removing_checkpoint)
1211
+
1212
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1213
+ accelerator.save_state(save_path)
1214
+ logger.info(f"Saved state to {save_path}")
1215
+
1216
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1217
+ progress_bar.set_postfix(**logs)
1218
+
1219
+ if global_step >= args.max_train_steps:
1220
+ break
1221
+
1222
+ if accelerator.is_main_process:
1223
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
1224
+ logger.info(
1225
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
1226
+ f" {args.validation_prompt}."
1227
+ )
1228
+ if args.use_ema:
1229
+ # Store the UNet parameters temporarily and load the EMA parameters to perform inference.
1230
+ ema_unet.store(unet.parameters())
1231
+ ema_unet.copy_to(unet.parameters())
1232
+
1233
+ # create pipeline
1234
+ vae = AutoencoderKL.from_pretrained(
1235
+ vae_path,
1236
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
1237
+ revision=args.revision,
1238
+ variant=args.variant,
1239
+ )
1240
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1241
+ args.pretrained_model_name_or_path,
1242
+ vae=vae,
1243
+ unet=accelerator.unwrap_model(unet),
1244
+ revision=args.revision,
1245
+ variant=args.variant,
1246
+ torch_dtype=weight_dtype,
1247
+ )
1248
+ if args.prediction_type is not None:
1249
+ scheduler_args = {"prediction_type": args.prediction_type}
1250
+ pipeline.scheduler = pipeline.scheduler.from_config(pipeline.scheduler.config, **scheduler_args)
1251
+
1252
+ pipeline = pipeline.to(accelerator.device)
1253
+ pipeline.set_progress_bar_config(disable=True)
1254
+
1255
+ # run inference
1256
+ generator = (
1257
+ torch.Generator(device=accelerator.device).manual_seed(args.seed)
1258
+ if args.seed is not None
1259
+ else None
1260
+ )
1261
+ pipeline_args = {"prompt": args.validation_prompt}
1262
+
1263
+ with autocast_ctx:
1264
+ images = [
1265
+ pipeline(**pipeline_args, generator=generator, num_inference_steps=25).images[0]
1266
+ for _ in range(args.num_validation_images)
1267
+ ]
1268
+
1269
+ for tracker in accelerator.trackers:
1270
+ if tracker.name == "tensorboard":
1271
+ np_images = np.stack([np.asarray(img) for img in images])
1272
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
1273
+ if tracker.name == "wandb":
1274
+ tracker.log(
1275
+ {
1276
+ "validation": [
1277
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1278
+ for i, image in enumerate(images)
1279
+ ]
1280
+ }
1281
+ )
1282
+
1283
+ del pipeline
1284
+ if is_torch_npu_available():
1285
+ torch_npu.npu.empty_cache()
1286
+ elif torch.cuda.is_available():
1287
+ torch.cuda.empty_cache()
1288
+
1289
+ if args.use_ema:
1290
+ # Switch back to the original UNet parameters.
1291
+ ema_unet.restore(unet.parameters())
1292
+
1293
+ accelerator.wait_for_everyone()
1294
+ if accelerator.is_main_process:
1295
+ unet = unwrap_model(unet)
1296
+ if args.use_ema:
1297
+ ema_unet.copy_to(unet.parameters())
1298
+
1299
+ # Serialize pipeline.
1300
+ vae = AutoencoderKL.from_pretrained(
1301
+ vae_path,
1302
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
1303
+ revision=args.revision,
1304
+ variant=args.variant,
1305
+ torch_dtype=weight_dtype,
1306
+ )
1307
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1308
+ args.pretrained_model_name_or_path,
1309
+ unet=unet,
1310
+ vae=vae,
1311
+ revision=args.revision,
1312
+ variant=args.variant,
1313
+ torch_dtype=weight_dtype,
1314
+ )
1315
+ if args.prediction_type is not None:
1316
+ scheduler_args = {"prediction_type": args.prediction_type}
1317
+ pipeline.scheduler = pipeline.scheduler.from_config(pipeline.scheduler.config, **scheduler_args)
1318
+ pipeline.save_pretrained(args.output_dir)
1319
+
1320
+ # run inference
1321
+ images = []
1322
+ if args.validation_prompt and args.num_validation_images > 0:
1323
+ pipeline = pipeline.to(accelerator.device)
1324
+ generator = (
1325
+ torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed is not None else None
1326
+ )
1327
+
1328
+ with autocast_ctx:
1329
+ images = [
1330
+ pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
1331
+ for _ in range(args.num_validation_images)
1332
+ ]
1333
+
1334
+ for tracker in accelerator.trackers:
1335
+ if tracker.name == "tensorboard":
1336
+ np_images = np.stack([np.asarray(img) for img in images])
1337
+ tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC")
1338
+ if tracker.name == "wandb":
1339
+ tracker.log(
1340
+ {
1341
+ "test": [
1342
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1343
+ for i, image in enumerate(images)
1344
+ ]
1345
+ }
1346
+ )
1347
+
1348
+ if args.push_to_hub:
1349
+ save_model_card(
1350
+ repo_id=repo_id,
1351
+ images=images,
1352
+ validation_prompt=args.validation_prompt,
1353
+ base_model=args.pretrained_model_name_or_path,
1354
+ dataset_name=args.dataset_name,
1355
+ repo_folder=args.output_dir,
1356
+ vae_path=args.pretrained_vae_model_name_or_path,
1357
+ )
1358
+ upload_folder(
1359
+ repo_id=repo_id,
1360
+ folder_path=args.output_dir,
1361
+ commit_message="End of training",
1362
+ ignore_patterns=["step_*", "epoch_*"],
1363
+ )
1364
+
1365
+ accelerator.end_training()
1366
+
1367
+
1368
+ if __name__ == "__main__":
1369
+ args = parse_args()
1370
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Textual Inversion fine-tuning example
2
+
3
+ [Textual inversion](https://huggingface.co/papers/2208.01618) is a method to personalize text2image models like stable diffusion on your own images using just 3-5 examples.
4
+ The `textual_inversion.py` script shows how to implement the training procedure and adapt it for stable diffusion.
5
+
6
+ ## Running on Colab
7
+
8
+ Colab for training
9
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb)
10
+
11
+ Colab for inference
12
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/stable_conceptualizer_inference.ipynb)
13
+
14
+ ## Running locally with PyTorch
15
+ ### Installing the dependencies
16
+
17
+ Before running the scripts, make sure to install the library's training dependencies:
18
+
19
+ **Important**
20
+
21
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
22
+ ```bash
23
+ git clone https://github.com/huggingface/diffusers
24
+ cd diffusers
25
+ pip install .
26
+ ```
27
+
28
+ Then cd in the example folder and run:
29
+ ```bash
30
+ pip install -r requirements.txt
31
+ ```
32
+
33
+ And initialize an [🤗 Accelerate](https://github.com/huggingface/accelerate/) environment with:
34
+
35
+ ```bash
36
+ accelerate config
37
+ ```
38
+
39
+ ### Cat toy example
40
+
41
+ First, let's login so that we can upload the checkpoint to the Hub during training:
42
+
43
+ ```bash
44
+ hf auth login
45
+ ```
46
+
47
+ Now let's get our dataset. For this example we will use some cat images: https://huggingface.co/datasets/diffusers/cat_toy_example .
48
+
49
+ Let's first download it locally:
50
+
51
+ ```py
52
+ from huggingface_hub import snapshot_download
53
+
54
+ local_dir = "./cat"
55
+ snapshot_download("diffusers/cat_toy_example", local_dir=local_dir, repo_type="dataset", ignore_patterns=".gitattributes")
56
+ ```
57
+
58
+ This will be our training data.
59
+ Now we can launch the training using:
60
+
61
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
62
+
63
+ **___Note: Please follow the [README_sdxl.md](./README_sdxl.md) if you are using the [stable-diffusion-xl](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0).___**
64
+
65
+ ```bash
66
+ export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
67
+ export DATA_DIR="./cat"
68
+
69
+ accelerate launch textual_inversion.py \
70
+ --pretrained_model_name_or_path=$MODEL_NAME \
71
+ --train_data_dir=$DATA_DIR \
72
+ --learnable_property="object" \
73
+ --placeholder_token="<cat-toy>" \
74
+ --initializer_token="toy" \
75
+ --resolution=512 \
76
+ --train_batch_size=1 \
77
+ --gradient_accumulation_steps=4 \
78
+ --max_train_steps=3000 \
79
+ --learning_rate=5.0e-04 \
80
+ --scale_lr \
81
+ --lr_scheduler="constant" \
82
+ --lr_warmup_steps=0 \
83
+ --push_to_hub \
84
+ --output_dir="textual_inversion_cat"
85
+ ```
86
+
87
+ A full training run takes ~1 hour on one V100 GPU.
88
+
89
+ **Note**: As described in [the official paper](https://huggingface.co/papers/2208.01618)
90
+ only one embedding vector is used for the placeholder token, *e.g.* `"<cat-toy>"`.
91
+ However, one can also add multiple embedding vectors for the placeholder token
92
+ to increase the number of fine-tuneable parameters. This can help the model to learn
93
+ more complex details. To use multiple embedding vectors, you should define `--num_vectors`
94
+ to a number larger than one, *e.g.*:
95
+ ```bash
96
+ --num_vectors 5
97
+ ```
98
+
99
+ The saved textual inversion vectors will then be larger in size compared to the default case.
100
+
101
+ ### Inference
102
+
103
+ Once you have trained a model using above command, the inference can be done simply using the `StableDiffusionPipeline`. Make sure to include the `placeholder_token` in your prompt.
104
+
105
+ ```python
106
+ from diffusers import StableDiffusionPipeline
107
+ import torch
108
+
109
+ model_id = "path-to-your-trained-model"
110
+ pipe = StableDiffusionPipeline.from_pretrained(model_id,torch_dtype=torch.float16).to("cuda")
111
+
112
+ repo_id_embeds = "path-to-your-learned-embeds"
113
+ pipe.load_textual_inversion(repo_id_embeds)
114
+
115
+ prompt = "A <cat-toy> backpack"
116
+
117
+ image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
118
+
119
+ image.save("cat-backpack.png")
120
+ ```
121
+
122
+
123
+ ## Training with Flax/JAX
124
+
125
+ For faster training on TPUs and GPUs you can leverage the flax training example. Follow the instructions above to get the model and dataset before running the script.
126
+
127
+ Before running the scripts, make sure to install the library's training dependencies:
128
+
129
+ ```bash
130
+ pip install -U -r requirements_flax.txt
131
+ ```
132
+
133
+ ```bash
134
+ export MODEL_NAME="duongna/stable-diffusion-v1-4-flax"
135
+ export DATA_DIR="path-to-dir-containing-images"
136
+
137
+ python textual_inversion_flax.py \
138
+ --pretrained_model_name_or_path=$MODEL_NAME \
139
+ --train_data_dir=$DATA_DIR \
140
+ --learnable_property="object" \
141
+ --placeholder_token="<cat-toy>" \
142
+ --initializer_token="toy" \
143
+ --resolution=512 \
144
+ --train_batch_size=1 \
145
+ --max_train_steps=3000 \
146
+ --learning_rate=5.0e-04 \
147
+ --scale_lr \
148
+ --output_dir="textual_inversion_cat"
149
+ ```
150
+ It should be at least 70% faster than the PyTorch script with the same configuration.
151
+
152
+ ### Training with xformers:
153
+ You can enable memory efficient attention by [installing xFormers](https://github.com/facebookresearch/xformers#installing-xformers) and padding the `--enable_xformers_memory_efficient_attention` argument to the script. This is not available with the Flax/JAX implementation.
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/README_sdxl.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Textual Inversion fine-tuning example for SDXL
2
+
3
+ ```sh
4
+ export MODEL_NAME="stabilityai/stable-diffusion-xl-base-1.0"
5
+ export DATA_DIR="./cat"
6
+
7
+ accelerate launch textual_inversion_sdxl.py \
8
+ --pretrained_model_name_or_path=$MODEL_NAME \
9
+ --train_data_dir=$DATA_DIR \
10
+ --learnable_property="object" \
11
+ --placeholder_token="<cat-toy>" \
12
+ --initializer_token="toy" \
13
+ --mixed_precision="bf16" \
14
+ --resolution=768 \
15
+ --train_batch_size=1 \
16
+ --gradient_accumulation_steps=4 \
17
+ --max_train_steps=500 \
18
+ --learning_rate=5.0e-04 \
19
+ --scale_lr \
20
+ --lr_scheduler="constant" \
21
+ --lr_warmup_steps=0 \
22
+ --save_as_full_pipeline \
23
+ --output_dir="./textual_inversion_cat_sdxl"
24
+ ```
25
+
26
+ Training of both text encoders is supported.
27
+
28
+ ### Inference Example
29
+
30
+ Once you have trained a model using above command, the inference can be done simply using the `StableDiffusionXLPipeline`.
31
+ Make sure to include the `placeholder_token` in your prompt.
32
+
33
+ ```python
34
+ from diffusers import StableDiffusionXLPipeline
35
+ import torch
36
+
37
+ model_id = "./textual_inversion_cat_sdxl"
38
+ pipe = StableDiffusionXLPipeline.from_pretrained(model_id,torch_dtype=torch.float16).to("cuda")
39
+
40
+ prompt = "A <cat-toy> backpack"
41
+
42
+ image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
43
+ image.save("cat-backpack.png")
44
+
45
+ image = pipe(prompt="", prompt_2=prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
46
+ image.save("cat-backpack-prompt_2.png")
47
+ ```
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ ftfy
5
+ tensorboard
6
+ Jinja2
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/requirements_flax.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ transformers>=4.25.1
2
+ flax
3
+ optax
4
+ torch
5
+ torchvision
6
+ ftfy
7
+ tensorboard
8
+ Jinja2
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/test_textual_inversion.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+
21
+
22
+ sys.path.append("..")
23
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
24
+
25
+
26
+ logging.basicConfig(level=logging.DEBUG)
27
+
28
+ logger = logging.getLogger()
29
+ stream_handler = logging.StreamHandler(sys.stdout)
30
+ logger.addHandler(stream_handler)
31
+
32
+
33
+ class TextualInversion(ExamplesTestsAccelerate):
34
+ def test_textual_inversion(self):
35
+ with tempfile.TemporaryDirectory() as tmpdir:
36
+ test_args = f"""
37
+ examples/textual_inversion/textual_inversion.py
38
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-pipe
39
+ --train_data_dir docs/source/en/imgs
40
+ --learnable_property object
41
+ --placeholder_token <cat-toy>
42
+ --initializer_token a
43
+ --save_steps 1
44
+ --num_vectors 2
45
+ --resolution 64
46
+ --train_batch_size 1
47
+ --gradient_accumulation_steps 1
48
+ --max_train_steps 2
49
+ --learning_rate 5.0e-04
50
+ --scale_lr
51
+ --lr_scheduler constant
52
+ --lr_warmup_steps 0
53
+ --output_dir {tmpdir}
54
+ """.split()
55
+
56
+ run_command(self._launch_args + test_args)
57
+ # save_pretrained smoke test
58
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "learned_embeds.safetensors")))
59
+
60
+ def test_textual_inversion_checkpointing(self):
61
+ with tempfile.TemporaryDirectory() as tmpdir:
62
+ test_args = f"""
63
+ examples/textual_inversion/textual_inversion.py
64
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-pipe
65
+ --train_data_dir docs/source/en/imgs
66
+ --learnable_property object
67
+ --placeholder_token <cat-toy>
68
+ --initializer_token a
69
+ --save_steps 1
70
+ --num_vectors 2
71
+ --resolution 64
72
+ --train_batch_size 1
73
+ --gradient_accumulation_steps 1
74
+ --max_train_steps 3
75
+ --learning_rate 5.0e-04
76
+ --scale_lr
77
+ --lr_scheduler constant
78
+ --lr_warmup_steps 0
79
+ --output_dir {tmpdir}
80
+ --checkpointing_steps=1
81
+ --checkpoints_total_limit=2
82
+ """.split()
83
+
84
+ run_command(self._launch_args + test_args)
85
+
86
+ # check checkpoint directories exist
87
+ self.assertEqual(
88
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
89
+ {"checkpoint-2", "checkpoint-3"},
90
+ )
91
+
92
+ def test_textual_inversion_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
93
+ with tempfile.TemporaryDirectory() as tmpdir:
94
+ test_args = f"""
95
+ examples/textual_inversion/textual_inversion.py
96
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-pipe
97
+ --train_data_dir docs/source/en/imgs
98
+ --learnable_property object
99
+ --placeholder_token <cat-toy>
100
+ --initializer_token a
101
+ --save_steps 1
102
+ --num_vectors 2
103
+ --resolution 64
104
+ --train_batch_size 1
105
+ --gradient_accumulation_steps 1
106
+ --max_train_steps 2
107
+ --learning_rate 5.0e-04
108
+ --scale_lr
109
+ --lr_scheduler constant
110
+ --lr_warmup_steps 0
111
+ --output_dir {tmpdir}
112
+ --checkpointing_steps=1
113
+ """.split()
114
+
115
+ run_command(self._launch_args + test_args)
116
+
117
+ # check checkpoint directories exist
118
+ self.assertEqual(
119
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
120
+ {"checkpoint-1", "checkpoint-2"},
121
+ )
122
+
123
+ resume_run_args = f"""
124
+ examples/textual_inversion/textual_inversion.py
125
+ --pretrained_model_name_or_path hf-internal-testing/tiny-stable-diffusion-pipe
126
+ --train_data_dir docs/source/en/imgs
127
+ --learnable_property object
128
+ --placeholder_token <cat-toy>
129
+ --initializer_token a
130
+ --save_steps 1
131
+ --num_vectors 2
132
+ --resolution 64
133
+ --train_batch_size 1
134
+ --gradient_accumulation_steps 1
135
+ --max_train_steps 2
136
+ --learning_rate 5.0e-04
137
+ --scale_lr
138
+ --lr_scheduler constant
139
+ --lr_warmup_steps 0
140
+ --output_dir {tmpdir}
141
+ --checkpointing_steps=1
142
+ --resume_from_checkpoint=checkpoint-2
143
+ --checkpoints_total_limit=2
144
+ """.split()
145
+
146
+ run_command(self._launch_args + resume_run_args)
147
+
148
+ # check checkpoint directories exist
149
+ self.assertEqual(
150
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
151
+ {"checkpoint-2", "checkpoint-3"},
152
+ )
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/test_textual_inversion_sdxl.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+
21
+
22
+ sys.path.append("..")
23
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
24
+
25
+
26
+ logging.basicConfig(level=logging.DEBUG)
27
+
28
+ logger = logging.getLogger()
29
+ stream_handler = logging.StreamHandler(sys.stdout)
30
+ logger.addHandler(stream_handler)
31
+
32
+
33
+ class TextualInversionSdxl(ExamplesTestsAccelerate):
34
+ def test_textual_inversion_sdxl(self):
35
+ with tempfile.TemporaryDirectory() as tmpdir:
36
+ test_args = f"""
37
+ examples/textual_inversion/textual_inversion_sdxl.py
38
+ --pretrained_model_name_or_path hf-internal-testing/tiny-sdxl-pipe
39
+ --train_data_dir docs/source/en/imgs
40
+ --learnable_property object
41
+ --placeholder_token <cat-toy>
42
+ --initializer_token a
43
+ --save_steps 1
44
+ --num_vectors 2
45
+ --resolution 64
46
+ --train_batch_size 1
47
+ --gradient_accumulation_steps 1
48
+ --max_train_steps 2
49
+ --learning_rate 5.0e-04
50
+ --scale_lr
51
+ --lr_scheduler constant
52
+ --lr_warmup_steps 0
53
+ --output_dir {tmpdir}
54
+ """.split()
55
+
56
+ run_command(self._launch_args + test_args)
57
+ # save_pretrained smoke test
58
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "learned_embeds.safetensors")))
59
+
60
+ def test_textual_inversion_sdxl_checkpointing(self):
61
+ with tempfile.TemporaryDirectory() as tmpdir:
62
+ test_args = f"""
63
+ examples/textual_inversion/textual_inversion_sdxl.py
64
+ --pretrained_model_name_or_path hf-internal-testing/tiny-sdxl-pipe
65
+ --train_data_dir docs/source/en/imgs
66
+ --learnable_property object
67
+ --placeholder_token <cat-toy>
68
+ --initializer_token a
69
+ --save_steps 1
70
+ --num_vectors 2
71
+ --resolution 64
72
+ --train_batch_size 1
73
+ --gradient_accumulation_steps 1
74
+ --max_train_steps 3
75
+ --learning_rate 5.0e-04
76
+ --scale_lr
77
+ --lr_scheduler constant
78
+ --lr_warmup_steps 0
79
+ --output_dir {tmpdir}
80
+ --checkpointing_steps=1
81
+ --checkpoints_total_limit=2
82
+ """.split()
83
+
84
+ run_command(self._launch_args + test_args)
85
+
86
+ # check checkpoint directories exist
87
+ self.assertEqual(
88
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
89
+ {"checkpoint-2", "checkpoint-3"},
90
+ )
91
+
92
+ def test_textual_inversion_sdxl_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
93
+ with tempfile.TemporaryDirectory() as tmpdir:
94
+ test_args = f"""
95
+ examples/textual_inversion/textual_inversion_sdxl.py
96
+ --pretrained_model_name_or_path hf-internal-testing/tiny-sdxl-pipe
97
+ --train_data_dir docs/source/en/imgs
98
+ --learnable_property object
99
+ --placeholder_token <cat-toy>
100
+ --initializer_token a
101
+ --save_steps 1
102
+ --num_vectors 2
103
+ --resolution 64
104
+ --train_batch_size 1
105
+ --gradient_accumulation_steps 1
106
+ --max_train_steps 2
107
+ --learning_rate 5.0e-04
108
+ --scale_lr
109
+ --lr_scheduler constant
110
+ --lr_warmup_steps 0
111
+ --output_dir {tmpdir}
112
+ --checkpointing_steps=1
113
+ """.split()
114
+
115
+ run_command(self._launch_args + test_args)
116
+
117
+ # check checkpoint directories exist
118
+ self.assertEqual(
119
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
120
+ {"checkpoint-1", "checkpoint-2"},
121
+ )
122
+
123
+ resume_run_args = f"""
124
+ examples/textual_inversion/textual_inversion_sdxl.py
125
+ --pretrained_model_name_or_path hf-internal-testing/tiny-sdxl-pipe
126
+ --train_data_dir docs/source/en/imgs
127
+ --learnable_property object
128
+ --placeholder_token <cat-toy>
129
+ --initializer_token a
130
+ --save_steps 1
131
+ --num_vectors 2
132
+ --resolution 64
133
+ --train_batch_size 1
134
+ --gradient_accumulation_steps 1
135
+ --max_train_steps 2
136
+ --learning_rate 5.0e-04
137
+ --scale_lr
138
+ --lr_scheduler constant
139
+ --lr_warmup_steps 0
140
+ --output_dir {tmpdir}
141
+ --checkpointing_steps=1
142
+ --resume_from_checkpoint=checkpoint-2
143
+ --checkpoints_total_limit=2
144
+ """.split()
145
+
146
+ run_command(self._launch_args + resume_run_args)
147
+
148
+ # check checkpoint directories exist
149
+ self.assertEqual(
150
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
151
+ {"checkpoint-2", "checkpoint-3"},
152
+ )
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion.py ADDED
@@ -0,0 +1,1024 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
19
+ import math
20
+ import os
21
+ import random
22
+ import shutil
23
+ import warnings
24
+ from contextlib import nullcontext
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import PIL
29
+ import safetensors
30
+ import torch
31
+ import torch.nn.functional as F
32
+ import torch.utils.checkpoint
33
+ import transformers
34
+ from accelerate import Accelerator
35
+ from accelerate.logging import get_logger
36
+ from accelerate.utils import ProjectConfiguration, set_seed
37
+ from huggingface_hub import create_repo, upload_folder
38
+
39
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
40
+ from packaging import version
41
+ from PIL import Image
42
+ from torch.utils.data import Dataset
43
+ from torchvision import transforms
44
+ from tqdm.auto import tqdm
45
+ from transformers import CLIPTextModel, CLIPTokenizer
46
+
47
+ import diffusers
48
+ from diffusers import (
49
+ AutoencoderKL,
50
+ DDPMScheduler,
51
+ DiffusionPipeline,
52
+ DPMSolverMultistepScheduler,
53
+ StableDiffusionPipeline,
54
+ UNet2DConditionModel,
55
+ )
56
+ from diffusers.optimization import get_scheduler
57
+ from diffusers.utils import check_min_version, is_wandb_available
58
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
59
+ from diffusers.utils.import_utils import is_xformers_available
60
+
61
+
62
+ if is_wandb_available():
63
+ import wandb
64
+
65
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
66
+ PIL_INTERPOLATION = {
67
+ "linear": PIL.Image.Resampling.BILINEAR,
68
+ "bilinear": PIL.Image.Resampling.BILINEAR,
69
+ "bicubic": PIL.Image.Resampling.BICUBIC,
70
+ "lanczos": PIL.Image.Resampling.LANCZOS,
71
+ "nearest": PIL.Image.Resampling.NEAREST,
72
+ }
73
+ else:
74
+ PIL_INTERPOLATION = {
75
+ "linear": PIL.Image.LINEAR,
76
+ "bilinear": PIL.Image.BILINEAR,
77
+ "bicubic": PIL.Image.BICUBIC,
78
+ "lanczos": PIL.Image.LANCZOS,
79
+ "nearest": PIL.Image.NEAREST,
80
+ }
81
+ # ------------------------------------------------------------------------------
82
+
83
+
84
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
85
+ check_min_version("0.39.0.dev0")
86
+
87
+ logger = get_logger(__name__)
88
+
89
+
90
+ def save_model_card(repo_id: str, images: list = None, base_model: str = None, repo_folder: str = None):
91
+ img_str = ""
92
+ if images is not None:
93
+ for i, image in enumerate(images):
94
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
95
+ img_str += f"![img_{i}](./image_{i}.png)\n"
96
+ model_description = f"""
97
+ # Textual inversion text2image fine-tuning - {repo_id}
98
+ These are textual inversion adaption weights for {base_model}. You can find some example images in the following. \n
99
+ {img_str}
100
+ """
101
+ model_card = load_or_create_model_card(
102
+ repo_id_or_path=repo_id,
103
+ from_training=True,
104
+ license="creativeml-openrail-m",
105
+ base_model=base_model,
106
+ model_description=model_description,
107
+ inference=True,
108
+ )
109
+
110
+ tags = [
111
+ "stable-diffusion",
112
+ "stable-diffusion-diffusers",
113
+ "text-to-image",
114
+ "diffusers",
115
+ "textual_inversion",
116
+ "diffusers-training",
117
+ ]
118
+ model_card = populate_model_card(model_card, tags=tags)
119
+
120
+ model_card.save(os.path.join(repo_folder, "README.md"))
121
+
122
+
123
+ def log_validation(text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch):
124
+ logger.info(
125
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
126
+ f" {args.validation_prompt}."
127
+ )
128
+ # create pipeline (note: unet and vae are loaded again in float32)
129
+ pipeline = DiffusionPipeline.from_pretrained(
130
+ args.pretrained_model_name_or_path,
131
+ text_encoder=accelerator.unwrap_model(text_encoder),
132
+ tokenizer=tokenizer,
133
+ unet=unet,
134
+ vae=vae,
135
+ safety_checker=None,
136
+ revision=args.revision,
137
+ variant=args.variant,
138
+ torch_dtype=weight_dtype,
139
+ )
140
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
141
+ pipeline = pipeline.to(accelerator.device)
142
+ pipeline.set_progress_bar_config(disable=True)
143
+
144
+ # run inference
145
+ generator = None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)
146
+ images = []
147
+ for _ in range(args.num_validation_images):
148
+ if torch.backends.mps.is_available():
149
+ autocast_ctx = nullcontext()
150
+ else:
151
+ autocast_ctx = torch.autocast(accelerator.device.type)
152
+
153
+ with autocast_ctx:
154
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
155
+ images.append(image)
156
+
157
+ for tracker in accelerator.trackers:
158
+ if tracker.name == "tensorboard":
159
+ np_images = np.stack([np.asarray(img) for img in images])
160
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
161
+ if tracker.name == "wandb":
162
+ tracker.log(
163
+ {
164
+ "validation": [
165
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
166
+ ]
167
+ }
168
+ )
169
+
170
+ del pipeline
171
+ torch.cuda.empty_cache()
172
+ return images
173
+
174
+
175
+ def save_progress(text_encoder, placeholder_token_ids, accelerator, args, save_path, safe_serialization=True):
176
+ logger.info("Saving embeddings")
177
+ learned_embeds = (
178
+ accelerator.unwrap_model(text_encoder)
179
+ .get_input_embeddings()
180
+ .weight[min(placeholder_token_ids) : max(placeholder_token_ids) + 1]
181
+ )
182
+ learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
183
+
184
+ if safe_serialization:
185
+ safetensors.torch.save_file(learned_embeds_dict, save_path, metadata={"format": "pt"})
186
+ else:
187
+ torch.save(learned_embeds_dict, save_path)
188
+
189
+
190
+ def parse_args():
191
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
192
+ parser.add_argument(
193
+ "--save_steps",
194
+ type=int,
195
+ default=500,
196
+ help="Save learned_embeds.bin every X updates steps.",
197
+ )
198
+ parser.add_argument(
199
+ "--save_as_full_pipeline",
200
+ action="store_true",
201
+ help="Save the complete stable diffusion pipeline.",
202
+ )
203
+ parser.add_argument(
204
+ "--num_vectors",
205
+ type=int,
206
+ default=1,
207
+ help="How many textual inversion vectors shall be used to learn the concept.",
208
+ )
209
+ parser.add_argument(
210
+ "--pretrained_model_name_or_path",
211
+ type=str,
212
+ default=None,
213
+ required=True,
214
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
215
+ )
216
+ parser.add_argument(
217
+ "--revision",
218
+ type=str,
219
+ default=None,
220
+ required=False,
221
+ help="Revision of pretrained model identifier from huggingface.co/models.",
222
+ )
223
+ parser.add_argument(
224
+ "--variant",
225
+ type=str,
226
+ default=None,
227
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
228
+ )
229
+ parser.add_argument(
230
+ "--tokenizer_name",
231
+ type=str,
232
+ default=None,
233
+ help="Pretrained tokenizer name or path if not the same as model_name",
234
+ )
235
+ parser.add_argument(
236
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
237
+ )
238
+ parser.add_argument(
239
+ "--placeholder_token",
240
+ type=str,
241
+ default=None,
242
+ required=True,
243
+ help="A token to use as a placeholder for the concept.",
244
+ )
245
+ parser.add_argument(
246
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
247
+ )
248
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
249
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
250
+ parser.add_argument(
251
+ "--output_dir",
252
+ type=str,
253
+ default="text-inversion-model",
254
+ help="The output directory where the model predictions and checkpoints will be written.",
255
+ )
256
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
257
+ parser.add_argument(
258
+ "--resolution",
259
+ type=int,
260
+ default=512,
261
+ help=(
262
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
263
+ " resolution"
264
+ ),
265
+ )
266
+ parser.add_argument(
267
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
268
+ )
269
+ parser.add_argument(
270
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
271
+ )
272
+ parser.add_argument("--num_train_epochs", type=int, default=100)
273
+ parser.add_argument(
274
+ "--max_train_steps",
275
+ type=int,
276
+ default=5000,
277
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
278
+ )
279
+ parser.add_argument(
280
+ "--gradient_accumulation_steps",
281
+ type=int,
282
+ default=1,
283
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
284
+ )
285
+ parser.add_argument(
286
+ "--gradient_checkpointing",
287
+ action="store_true",
288
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
289
+ )
290
+ parser.add_argument(
291
+ "--learning_rate",
292
+ type=float,
293
+ default=1e-4,
294
+ help="Initial learning rate (after the potential warmup period) to use.",
295
+ )
296
+ parser.add_argument(
297
+ "--scale_lr",
298
+ action="store_true",
299
+ default=False,
300
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
301
+ )
302
+ parser.add_argument(
303
+ "--lr_scheduler",
304
+ type=str,
305
+ default="constant",
306
+ help=(
307
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
308
+ ' "constant", "constant_with_warmup"]'
309
+ ),
310
+ )
311
+ parser.add_argument(
312
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
313
+ )
314
+ parser.add_argument(
315
+ "--lr_num_cycles",
316
+ type=int,
317
+ default=1,
318
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
319
+ )
320
+ parser.add_argument(
321
+ "--dataloader_num_workers",
322
+ type=int,
323
+ default=0,
324
+ help=(
325
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
326
+ ),
327
+ )
328
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
329
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
330
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
331
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
332
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
333
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
334
+ parser.add_argument(
335
+ "--hub_model_id",
336
+ type=str,
337
+ default=None,
338
+ help="The name of the repository to keep in sync with the local `output_dir`.",
339
+ )
340
+ parser.add_argument(
341
+ "--logging_dir",
342
+ type=str,
343
+ default="logs",
344
+ help=(
345
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
346
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
347
+ ),
348
+ )
349
+ parser.add_argument(
350
+ "--mixed_precision",
351
+ type=str,
352
+ default="no",
353
+ choices=["no", "fp16", "bf16"],
354
+ help=(
355
+ "Whether to use mixed precision. Choose"
356
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
357
+ "and Nvidia Ampere GPU or Intel Gen 4 Xeon (and later) ."
358
+ ),
359
+ )
360
+ parser.add_argument(
361
+ "--allow_tf32",
362
+ action="store_true",
363
+ help=(
364
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
365
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
366
+ ),
367
+ )
368
+ parser.add_argument(
369
+ "--report_to",
370
+ type=str,
371
+ default="tensorboard",
372
+ help=(
373
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
374
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
375
+ ),
376
+ )
377
+ parser.add_argument(
378
+ "--validation_prompt",
379
+ type=str,
380
+ default=None,
381
+ help="A prompt that is used during validation to verify that the model is learning.",
382
+ )
383
+ parser.add_argument(
384
+ "--num_validation_images",
385
+ type=int,
386
+ default=4,
387
+ help="Number of images that should be generated during validation with `validation_prompt`.",
388
+ )
389
+ parser.add_argument(
390
+ "--validation_steps",
391
+ type=int,
392
+ default=100,
393
+ help=(
394
+ "Run validation every X steps. Validation consists of running the prompt"
395
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
396
+ " and logging the images."
397
+ ),
398
+ )
399
+ parser.add_argument(
400
+ "--validation_epochs",
401
+ type=int,
402
+ default=None,
403
+ help=(
404
+ "Deprecated in favor of validation_steps. Run validation every X epochs. Validation consists of running the prompt"
405
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
406
+ " and logging the images."
407
+ ),
408
+ )
409
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
410
+ parser.add_argument(
411
+ "--checkpointing_steps",
412
+ type=int,
413
+ default=500,
414
+ help=(
415
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
416
+ " training using `--resume_from_checkpoint`."
417
+ ),
418
+ )
419
+ parser.add_argument(
420
+ "--checkpoints_total_limit",
421
+ type=int,
422
+ default=None,
423
+ help=("Max number of checkpoints to store."),
424
+ )
425
+ parser.add_argument(
426
+ "--resume_from_checkpoint",
427
+ type=str,
428
+ default=None,
429
+ help=(
430
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
431
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
432
+ ),
433
+ )
434
+ parser.add_argument(
435
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
436
+ )
437
+ parser.add_argument(
438
+ "--no_safe_serialization",
439
+ action="store_true",
440
+ help="If specified save the checkpoint not in `safetensors` format, but in original PyTorch format instead.",
441
+ )
442
+
443
+ args = parser.parse_args()
444
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
445
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
446
+ args.local_rank = env_local_rank
447
+
448
+ if args.train_data_dir is None:
449
+ raise ValueError("You must specify a train data directory.")
450
+
451
+ return args
452
+
453
+
454
+ imagenet_templates_small = [
455
+ "a photo of a {}",
456
+ "a rendering of a {}",
457
+ "a cropped photo of the {}",
458
+ "the photo of a {}",
459
+ "a photo of a clean {}",
460
+ "a photo of a dirty {}",
461
+ "a dark photo of the {}",
462
+ "a photo of my {}",
463
+ "a photo of the cool {}",
464
+ "a close-up photo of a {}",
465
+ "a bright photo of the {}",
466
+ "a cropped photo of a {}",
467
+ "a photo of the {}",
468
+ "a good photo of the {}",
469
+ "a photo of one {}",
470
+ "a close-up photo of the {}",
471
+ "a rendition of the {}",
472
+ "a photo of the clean {}",
473
+ "a rendition of a {}",
474
+ "a photo of a nice {}",
475
+ "a good photo of a {}",
476
+ "a photo of the nice {}",
477
+ "a photo of the small {}",
478
+ "a photo of the weird {}",
479
+ "a photo of the large {}",
480
+ "a photo of a cool {}",
481
+ "a photo of a small {}",
482
+ ]
483
+
484
+ imagenet_style_templates_small = [
485
+ "a painting in the style of {}",
486
+ "a rendering in the style of {}",
487
+ "a cropped painting in the style of {}",
488
+ "the painting in the style of {}",
489
+ "a clean painting in the style of {}",
490
+ "a dirty painting in the style of {}",
491
+ "a dark painting in the style of {}",
492
+ "a picture in the style of {}",
493
+ "a cool painting in the style of {}",
494
+ "a close-up painting in the style of {}",
495
+ "a bright painting in the style of {}",
496
+ "a cropped painting in the style of {}",
497
+ "a good painting in the style of {}",
498
+ "a close-up painting in the style of {}",
499
+ "a rendition in the style of {}",
500
+ "a nice painting in the style of {}",
501
+ "a small painting in the style of {}",
502
+ "a weird painting in the style of {}",
503
+ "a large painting in the style of {}",
504
+ ]
505
+
506
+
507
+ class TextualInversionDataset(Dataset):
508
+ def __init__(
509
+ self,
510
+ data_root,
511
+ tokenizer,
512
+ learnable_property="object", # [object, style]
513
+ size=512,
514
+ repeats=100,
515
+ interpolation="bicubic",
516
+ flip_p=0.5,
517
+ set="train",
518
+ placeholder_token="*",
519
+ center_crop=False,
520
+ ):
521
+ self.data_root = data_root
522
+ self.tokenizer = tokenizer
523
+ self.learnable_property = learnable_property
524
+ self.size = size
525
+ self.placeholder_token = placeholder_token
526
+ self.center_crop = center_crop
527
+ self.flip_p = flip_p
528
+
529
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
530
+
531
+ self.num_images = len(self.image_paths)
532
+ self._length = self.num_images
533
+
534
+ if set == "train":
535
+ self._length = self.num_images * repeats
536
+
537
+ self.interpolation = {
538
+ "linear": PIL_INTERPOLATION["linear"],
539
+ "bilinear": PIL_INTERPOLATION["bilinear"],
540
+ "bicubic": PIL_INTERPOLATION["bicubic"],
541
+ "lanczos": PIL_INTERPOLATION["lanczos"],
542
+ }[interpolation]
543
+
544
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
545
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
546
+
547
+ def __len__(self):
548
+ return self._length
549
+
550
+ def __getitem__(self, i):
551
+ example = {}
552
+ image = Image.open(self.image_paths[i % self.num_images])
553
+
554
+ if not image.mode == "RGB":
555
+ image = image.convert("RGB")
556
+
557
+ placeholder_string = self.placeholder_token
558
+ text = random.choice(self.templates).format(placeholder_string)
559
+
560
+ example["input_ids"] = self.tokenizer(
561
+ text,
562
+ padding="max_length",
563
+ truncation=True,
564
+ max_length=self.tokenizer.model_max_length,
565
+ return_tensors="pt",
566
+ ).input_ids[0]
567
+
568
+ # default to score-sde preprocessing
569
+ img = np.array(image).astype(np.uint8)
570
+
571
+ if self.center_crop:
572
+ crop = min(img.shape[0], img.shape[1])
573
+ (
574
+ h,
575
+ w,
576
+ ) = (
577
+ img.shape[0],
578
+ img.shape[1],
579
+ )
580
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
581
+
582
+ image = Image.fromarray(img)
583
+ image = image.resize((self.size, self.size), resample=self.interpolation)
584
+
585
+ image = self.flip_transform(image)
586
+ image = np.array(image).astype(np.uint8)
587
+ image = (image / 127.5 - 1.0).astype(np.float32)
588
+
589
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
590
+ return example
591
+
592
+
593
+ def main():
594
+ args = parse_args()
595
+ if args.report_to == "wandb" and args.hub_token is not None:
596
+ raise ValueError(
597
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
598
+ " Please use `hf auth login` to authenticate with the Hub."
599
+ )
600
+
601
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
602
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
603
+ accelerator = Accelerator(
604
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
605
+ mixed_precision=args.mixed_precision,
606
+ log_with=args.report_to,
607
+ project_config=accelerator_project_config,
608
+ )
609
+
610
+ # Disable AMP for MPS.
611
+ if torch.backends.mps.is_available():
612
+ accelerator.native_amp = False
613
+
614
+ if args.report_to == "wandb":
615
+ if not is_wandb_available():
616
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
617
+
618
+ # Make one log on every process with the configuration for debugging.
619
+ logging.basicConfig(
620
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
621
+ datefmt="%m/%d/%Y %H:%M:%S",
622
+ level=logging.INFO,
623
+ )
624
+ logger.info(accelerator.state, main_process_only=False)
625
+ if accelerator.is_local_main_process:
626
+ transformers.utils.logging.set_verbosity_warning()
627
+ diffusers.utils.logging.set_verbosity_info()
628
+ else:
629
+ transformers.utils.logging.set_verbosity_error()
630
+ diffusers.utils.logging.set_verbosity_error()
631
+
632
+ # If passed along, set the training seed now.
633
+ if args.seed is not None:
634
+ set_seed(args.seed)
635
+
636
+ # Handle the repository creation
637
+ if accelerator.is_main_process:
638
+ if args.output_dir is not None:
639
+ os.makedirs(args.output_dir, exist_ok=True)
640
+
641
+ if args.push_to_hub:
642
+ repo_id = create_repo(
643
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
644
+ ).repo_id
645
+
646
+ # Load tokenizer
647
+ if args.tokenizer_name:
648
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
649
+ elif args.pretrained_model_name_or_path:
650
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
651
+
652
+ # Load scheduler and models
653
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
654
+ text_encoder = CLIPTextModel.from_pretrained(
655
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
656
+ )
657
+ vae = AutoencoderKL.from_pretrained(
658
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
659
+ )
660
+ unet = UNet2DConditionModel.from_pretrained(
661
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
662
+ )
663
+
664
+ # Add the placeholder token in tokenizer
665
+ placeholder_tokens = [args.placeholder_token]
666
+
667
+ if args.num_vectors < 1:
668
+ raise ValueError(f"--num_vectors has to be larger or equal to 1, but is {args.num_vectors}")
669
+
670
+ # add dummy tokens for multi-vector
671
+ additional_tokens = []
672
+ for i in range(1, args.num_vectors):
673
+ additional_tokens.append(f"{args.placeholder_token}_{i}")
674
+ placeholder_tokens += additional_tokens
675
+
676
+ num_added_tokens = tokenizer.add_tokens(placeholder_tokens)
677
+ if num_added_tokens != args.num_vectors:
678
+ raise ValueError(
679
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
680
+ " `placeholder_token` that is not already in the tokenizer."
681
+ )
682
+
683
+ # Convert the initializer_token, placeholder_token to ids
684
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
685
+ # Check if initializer_token is a single token or a sequence of tokens
686
+ if len(token_ids) > 1:
687
+ raise ValueError("The initializer token must be a single token.")
688
+
689
+ initializer_token_id = token_ids[0]
690
+ placeholder_token_ids = tokenizer.convert_tokens_to_ids(placeholder_tokens)
691
+
692
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
693
+ text_encoder.resize_token_embeddings(len(tokenizer))
694
+
695
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
696
+ token_embeds = text_encoder.get_input_embeddings().weight.data
697
+ with torch.no_grad():
698
+ for token_id in placeholder_token_ids:
699
+ token_embeds[token_id] = token_embeds[initializer_token_id].clone()
700
+
701
+ # Freeze vae and unet
702
+ vae.requires_grad_(False)
703
+ unet.requires_grad_(False)
704
+ # Freeze all parameters except for the token embeddings in text encoder
705
+ text_module = text_encoder.text_model if hasattr(text_encoder, "text_model") else text_encoder
706
+ text_module.encoder.requires_grad_(False)
707
+ text_module.final_layer_norm.requires_grad_(False)
708
+ text_module.embeddings.position_embedding.requires_grad_(False)
709
+
710
+ if args.gradient_checkpointing:
711
+ # Keep unet in train mode if we are using gradient checkpointing to save memory.
712
+ # The dropout cannot be != 0 so it doesn't matter if we are in eval or train mode.
713
+ unet.train()
714
+ text_encoder.gradient_checkpointing_enable()
715
+ unet.enable_gradient_checkpointing()
716
+
717
+ if args.enable_xformers_memory_efficient_attention:
718
+ if is_xformers_available():
719
+ import xformers
720
+
721
+ xformers_version = version.parse(xformers.__version__)
722
+ if xformers_version == version.parse("0.0.16"):
723
+ logger.warning(
724
+ "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."
725
+ )
726
+ unet.enable_xformers_memory_efficient_attention()
727
+ else:
728
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
729
+
730
+ # Enable TF32 for faster training on Ampere GPUs,
731
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
732
+ if args.allow_tf32:
733
+ torch.backends.cuda.matmul.allow_tf32 = True
734
+
735
+ if args.scale_lr:
736
+ args.learning_rate = (
737
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
738
+ )
739
+
740
+ # Initialize the optimizer
741
+ optimizer = torch.optim.AdamW(
742
+ text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
743
+ lr=args.learning_rate,
744
+ betas=(args.adam_beta1, args.adam_beta2),
745
+ weight_decay=args.adam_weight_decay,
746
+ eps=args.adam_epsilon,
747
+ )
748
+
749
+ # Dataset and DataLoaders creation:
750
+ train_dataset = TextualInversionDataset(
751
+ data_root=args.train_data_dir,
752
+ tokenizer=tokenizer,
753
+ size=args.resolution,
754
+ placeholder_token=(" ".join(tokenizer.convert_ids_to_tokens(placeholder_token_ids))),
755
+ repeats=args.repeats,
756
+ learnable_property=args.learnable_property,
757
+ center_crop=args.center_crop,
758
+ set="train",
759
+ )
760
+ train_dataloader = torch.utils.data.DataLoader(
761
+ train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
762
+ )
763
+ if args.validation_epochs is not None:
764
+ warnings.warn(
765
+ f"FutureWarning: You are doing logging with validation_epochs={args.validation_epochs}."
766
+ " Deprecated validation_epochs in favor of `validation_steps`"
767
+ f"Setting `args.validation_steps` to {args.validation_epochs * len(train_dataset)}",
768
+ FutureWarning,
769
+ stacklevel=2,
770
+ )
771
+ args.validation_steps = args.validation_epochs * len(train_dataset)
772
+
773
+ # Scheduler and math around the number of training steps.
774
+ overrode_max_train_steps = False
775
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
776
+ if args.max_train_steps is None:
777
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
778
+ overrode_max_train_steps = True
779
+
780
+ lr_scheduler = get_scheduler(
781
+ args.lr_scheduler,
782
+ optimizer=optimizer,
783
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
784
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
785
+ num_cycles=args.lr_num_cycles,
786
+ )
787
+
788
+ text_encoder.train()
789
+ # Prepare everything with our `accelerator`.
790
+ text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
791
+ text_encoder, optimizer, train_dataloader, lr_scheduler
792
+ )
793
+
794
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
795
+ # as these weights are only used for inference, keeping weights in full precision is not required.
796
+ weight_dtype = torch.float32
797
+ if accelerator.mixed_precision == "fp16":
798
+ weight_dtype = torch.float16
799
+ elif accelerator.mixed_precision == "bf16":
800
+ weight_dtype = torch.bfloat16
801
+
802
+ # Move vae and unet to device and cast to weight_dtype
803
+ unet.to(accelerator.device, dtype=weight_dtype)
804
+ vae.to(accelerator.device, dtype=weight_dtype)
805
+
806
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
807
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
808
+ if overrode_max_train_steps:
809
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
810
+ # Afterwards we recalculate our number of training epochs
811
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
812
+
813
+ # We need to initialize the trackers we use, and also store our configuration.
814
+ # The trackers initializes automatically on the main process.
815
+ if accelerator.is_main_process:
816
+ accelerator.init_trackers("textual_inversion", config=vars(args))
817
+
818
+ # Train!
819
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
820
+
821
+ logger.info("***** Running training *****")
822
+ logger.info(f" Num examples = {len(train_dataset)}")
823
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
824
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
825
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
826
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
827
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
828
+ global_step = 0
829
+ first_epoch = 0
830
+ # Potentially load in the weights and states from a previous save
831
+ if args.resume_from_checkpoint:
832
+ if args.resume_from_checkpoint != "latest":
833
+ path = os.path.basename(args.resume_from_checkpoint)
834
+ else:
835
+ # Get the most recent checkpoint
836
+ dirs = os.listdir(args.output_dir)
837
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
838
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
839
+ path = dirs[-1] if len(dirs) > 0 else None
840
+
841
+ if path is None:
842
+ accelerator.print(
843
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
844
+ )
845
+ args.resume_from_checkpoint = None
846
+ initial_global_step = 0
847
+ else:
848
+ accelerator.print(f"Resuming from checkpoint {path}")
849
+ accelerator.load_state(os.path.join(args.output_dir, path))
850
+ global_step = int(path.split("-")[1])
851
+
852
+ initial_global_step = global_step
853
+ first_epoch = global_step // num_update_steps_per_epoch
854
+
855
+ else:
856
+ initial_global_step = 0
857
+
858
+ progress_bar = tqdm(
859
+ range(0, args.max_train_steps),
860
+ initial=initial_global_step,
861
+ desc="Steps",
862
+ # Only show the progress bar once on each machine.
863
+ disable=not accelerator.is_local_main_process,
864
+ )
865
+
866
+ # keep original embeddings as reference
867
+ orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone()
868
+
869
+ for epoch in range(first_epoch, args.num_train_epochs):
870
+ text_encoder.train()
871
+ for step, batch in enumerate(train_dataloader):
872
+ with accelerator.accumulate(text_encoder):
873
+ # Convert images to latent space
874
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()
875
+ latents = latents * vae.config.scaling_factor
876
+
877
+ # Sample noise that we'll add to the latents
878
+ noise = torch.randn_like(latents)
879
+ bsz = latents.shape[0]
880
+ # Sample a random timestep for each image
881
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
882
+ timesteps = timesteps.long()
883
+
884
+ # Add noise to the latents according to the noise magnitude at each timestep
885
+ # (this is the forward diffusion process)
886
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
887
+
888
+ # Get the text embedding for conditioning
889
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype)
890
+
891
+ # Predict the noise residual
892
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
893
+
894
+ # Get the target for loss depending on the prediction type
895
+ if noise_scheduler.config.prediction_type == "epsilon":
896
+ target = noise
897
+ elif noise_scheduler.config.prediction_type == "v_prediction":
898
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
899
+ else:
900
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
901
+
902
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
903
+
904
+ accelerator.backward(loss)
905
+
906
+ optimizer.step()
907
+ lr_scheduler.step()
908
+ optimizer.zero_grad()
909
+
910
+ # Let's make sure we don't update any embedding weights besides the newly added token
911
+ index_no_updates = torch.ones((len(tokenizer),), dtype=torch.bool)
912
+ index_no_updates[min(placeholder_token_ids) : max(placeholder_token_ids) + 1] = False
913
+
914
+ with torch.no_grad():
915
+ accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[index_no_updates] = (
916
+ orig_embeds_params[index_no_updates]
917
+ )
918
+
919
+ # Checks if the accelerator has performed an optimization step behind the scenes
920
+ if accelerator.sync_gradients:
921
+ images = []
922
+ progress_bar.update(1)
923
+ global_step += 1
924
+ if global_step % args.save_steps == 0:
925
+ weight_name = (
926
+ f"learned_embeds-steps-{global_step}.bin"
927
+ if args.no_safe_serialization
928
+ else f"learned_embeds-steps-{global_step}.safetensors"
929
+ )
930
+ save_path = os.path.join(args.output_dir, weight_name)
931
+ save_progress(
932
+ text_encoder,
933
+ placeholder_token_ids,
934
+ accelerator,
935
+ args,
936
+ save_path,
937
+ safe_serialization=not args.no_safe_serialization,
938
+ )
939
+
940
+ if accelerator.is_main_process:
941
+ if global_step % args.checkpointing_steps == 0:
942
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
943
+ if args.checkpoints_total_limit is not None:
944
+ checkpoints = os.listdir(args.output_dir)
945
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
946
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
947
+
948
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
949
+ if len(checkpoints) >= args.checkpoints_total_limit:
950
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
951
+ removing_checkpoints = checkpoints[0:num_to_remove]
952
+
953
+ logger.info(
954
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
955
+ )
956
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
957
+
958
+ for removing_checkpoint in removing_checkpoints:
959
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
960
+ shutil.rmtree(removing_checkpoint)
961
+
962
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
963
+ accelerator.save_state(save_path)
964
+ logger.info(f"Saved state to {save_path}")
965
+
966
+ if args.validation_prompt is not None and global_step % args.validation_steps == 0:
967
+ images = log_validation(
968
+ text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch
969
+ )
970
+
971
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
972
+ progress_bar.set_postfix(**logs)
973
+ accelerator.log(logs, step=global_step)
974
+
975
+ if global_step >= args.max_train_steps:
976
+ break
977
+ # Create the pipeline using the trained modules and save it.
978
+ accelerator.wait_for_everyone()
979
+ if accelerator.is_main_process:
980
+ if args.push_to_hub and not args.save_as_full_pipeline:
981
+ logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
982
+ save_full_model = True
983
+ else:
984
+ save_full_model = args.save_as_full_pipeline
985
+ if save_full_model:
986
+ pipeline = StableDiffusionPipeline.from_pretrained(
987
+ args.pretrained_model_name_or_path,
988
+ text_encoder=accelerator.unwrap_model(text_encoder),
989
+ vae=vae,
990
+ unet=unet,
991
+ tokenizer=tokenizer,
992
+ )
993
+ pipeline.save_pretrained(args.output_dir)
994
+ # Save the newly trained embeddings
995
+ weight_name = "learned_embeds.bin" if args.no_safe_serialization else "learned_embeds.safetensors"
996
+ save_path = os.path.join(args.output_dir, weight_name)
997
+ save_progress(
998
+ text_encoder,
999
+ placeholder_token_ids,
1000
+ accelerator,
1001
+ args,
1002
+ save_path,
1003
+ safe_serialization=not args.no_safe_serialization,
1004
+ )
1005
+
1006
+ if args.push_to_hub:
1007
+ save_model_card(
1008
+ repo_id,
1009
+ images=images,
1010
+ base_model=args.pretrained_model_name_or_path,
1011
+ repo_folder=args.output_dir,
1012
+ )
1013
+ upload_folder(
1014
+ repo_id=repo_id,
1015
+ folder_path=args.output_dir,
1016
+ commit_message="End of training",
1017
+ ignore_patterns=["step_*", "epoch_*"],
1018
+ )
1019
+
1020
+ accelerator.end_training()
1021
+
1022
+
1023
+ if __name__ == "__main__":
1024
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion_flax.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import math
4
+ import os
5
+ import random
6
+ from pathlib import Path
7
+
8
+ import jax
9
+ import jax.numpy as jnp
10
+ import numpy as np
11
+ import optax
12
+ import PIL
13
+ import torch
14
+ import torch.utils.checkpoint
15
+ import transformers
16
+ from flax import jax_utils
17
+ from flax.training import train_state
18
+ from flax.training.common_utils import shard
19
+ from huggingface_hub import create_repo, upload_folder
20
+
21
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
22
+ from packaging import version
23
+ from PIL import Image
24
+ from torch.utils.data import Dataset
25
+ from torchvision import transforms
26
+ from tqdm.auto import tqdm
27
+ from transformers import CLIPImageProcessor, CLIPTokenizer, FlaxCLIPTextModel, set_seed
28
+
29
+ from diffusers import (
30
+ FlaxAutoencoderKL,
31
+ FlaxDDPMScheduler,
32
+ FlaxPNDMScheduler,
33
+ FlaxStableDiffusionPipeline,
34
+ FlaxUNet2DConditionModel,
35
+ )
36
+ from diffusers.pipelines.stable_diffusion import FlaxStableDiffusionSafetyChecker
37
+ from diffusers.utils import check_min_version
38
+
39
+
40
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
41
+ PIL_INTERPOLATION = {
42
+ "linear": PIL.Image.Resampling.BILINEAR,
43
+ "bilinear": PIL.Image.Resampling.BILINEAR,
44
+ "bicubic": PIL.Image.Resampling.BICUBIC,
45
+ "lanczos": PIL.Image.Resampling.LANCZOS,
46
+ "nearest": PIL.Image.Resampling.NEAREST,
47
+ }
48
+ else:
49
+ PIL_INTERPOLATION = {
50
+ "linear": PIL.Image.LINEAR,
51
+ "bilinear": PIL.Image.BILINEAR,
52
+ "bicubic": PIL.Image.BICUBIC,
53
+ "lanczos": PIL.Image.LANCZOS,
54
+ "nearest": PIL.Image.NEAREST,
55
+ }
56
+ # ------------------------------------------------------------------------------
57
+
58
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
59
+ check_min_version("0.39.0.dev0")
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+
64
+ def parse_args():
65
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
66
+ parser.add_argument(
67
+ "--pretrained_model_name_or_path",
68
+ type=str,
69
+ default=None,
70
+ required=True,
71
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
72
+ )
73
+ parser.add_argument(
74
+ "--tokenizer_name",
75
+ type=str,
76
+ default=None,
77
+ help="Pretrained tokenizer name or path if not the same as model_name",
78
+ )
79
+ parser.add_argument(
80
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
81
+ )
82
+ parser.add_argument(
83
+ "--placeholder_token",
84
+ type=str,
85
+ default=None,
86
+ required=True,
87
+ help="A token to use as a placeholder for the concept.",
88
+ )
89
+ parser.add_argument(
90
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
91
+ )
92
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
93
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
94
+ parser.add_argument(
95
+ "--output_dir",
96
+ type=str,
97
+ default="text-inversion-model",
98
+ help="The output directory where the model predictions and checkpoints will be written.",
99
+ )
100
+ parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible training.")
101
+ parser.add_argument(
102
+ "--resolution",
103
+ type=int,
104
+ default=512,
105
+ help=(
106
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
107
+ " resolution"
108
+ ),
109
+ )
110
+ parser.add_argument(
111
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
112
+ )
113
+ parser.add_argument(
114
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
115
+ )
116
+ parser.add_argument("--num_train_epochs", type=int, default=100)
117
+ parser.add_argument(
118
+ "--max_train_steps",
119
+ type=int,
120
+ default=5000,
121
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
122
+ )
123
+ parser.add_argument(
124
+ "--save_steps",
125
+ type=int,
126
+ default=500,
127
+ help="Save learned_embeds.bin every X updates steps.",
128
+ )
129
+ parser.add_argument(
130
+ "--learning_rate",
131
+ type=float,
132
+ default=1e-4,
133
+ help="Initial learning rate (after the potential warmup period) to use.",
134
+ )
135
+ parser.add_argument(
136
+ "--scale_lr",
137
+ action="store_true",
138
+ default=True,
139
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
140
+ )
141
+ parser.add_argument(
142
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
143
+ )
144
+ parser.add_argument(
145
+ "--revision",
146
+ type=str,
147
+ default=None,
148
+ required=False,
149
+ help="Revision of pretrained model identifier from huggingface.co/models.",
150
+ )
151
+ parser.add_argument(
152
+ "--lr_scheduler",
153
+ type=str,
154
+ default="constant",
155
+ help=(
156
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
157
+ ' "constant", "constant_with_warmup"]'
158
+ ),
159
+ )
160
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
161
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
162
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
163
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
164
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
165
+ parser.add_argument(
166
+ "--use_auth_token",
167
+ action="store_true",
168
+ help=(
169
+ "Will use the token generated when running `hf auth login` (necessary to use this script with"
170
+ " private models)."
171
+ ),
172
+ )
173
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
174
+ parser.add_argument(
175
+ "--hub_model_id",
176
+ type=str,
177
+ default=None,
178
+ help="The name of the repository to keep in sync with the local `output_dir`.",
179
+ )
180
+ parser.add_argument(
181
+ "--logging_dir",
182
+ type=str,
183
+ default="logs",
184
+ help=(
185
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
186
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
187
+ ),
188
+ )
189
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
190
+
191
+ args = parser.parse_args()
192
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
193
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
194
+ args.local_rank = env_local_rank
195
+
196
+ if args.train_data_dir is None:
197
+ raise ValueError("You must specify a train data directory.")
198
+
199
+ return args
200
+
201
+
202
+ imagenet_templates_small = [
203
+ "a photo of a {}",
204
+ "a rendering of a {}",
205
+ "a cropped photo of the {}",
206
+ "the photo of a {}",
207
+ "a photo of a clean {}",
208
+ "a photo of a dirty {}",
209
+ "a dark photo of the {}",
210
+ "a photo of my {}",
211
+ "a photo of the cool {}",
212
+ "a close-up photo of a {}",
213
+ "a bright photo of the {}",
214
+ "a cropped photo of a {}",
215
+ "a photo of the {}",
216
+ "a good photo of the {}",
217
+ "a photo of one {}",
218
+ "a close-up photo of the {}",
219
+ "a rendition of the {}",
220
+ "a photo of the clean {}",
221
+ "a rendition of a {}",
222
+ "a photo of a nice {}",
223
+ "a good photo of a {}",
224
+ "a photo of the nice {}",
225
+ "a photo of the small {}",
226
+ "a photo of the weird {}",
227
+ "a photo of the large {}",
228
+ "a photo of a cool {}",
229
+ "a photo of a small {}",
230
+ ]
231
+
232
+ imagenet_style_templates_small = [
233
+ "a painting in the style of {}",
234
+ "a rendering in the style of {}",
235
+ "a cropped painting in the style of {}",
236
+ "the painting in the style of {}",
237
+ "a clean painting in the style of {}",
238
+ "a dirty painting in the style of {}",
239
+ "a dark painting in the style of {}",
240
+ "a picture in the style of {}",
241
+ "a cool painting in the style of {}",
242
+ "a close-up painting in the style of {}",
243
+ "a bright painting in the style of {}",
244
+ "a cropped painting in the style of {}",
245
+ "a good painting in the style of {}",
246
+ "a close-up painting in the style of {}",
247
+ "a rendition in the style of {}",
248
+ "a nice painting in the style of {}",
249
+ "a small painting in the style of {}",
250
+ "a weird painting in the style of {}",
251
+ "a large painting in the style of {}",
252
+ ]
253
+
254
+
255
+ class TextualInversionDataset(Dataset):
256
+ def __init__(
257
+ self,
258
+ data_root,
259
+ tokenizer,
260
+ learnable_property="object", # [object, style]
261
+ size=512,
262
+ repeats=100,
263
+ interpolation="bicubic",
264
+ flip_p=0.5,
265
+ set="train",
266
+ placeholder_token="*",
267
+ center_crop=False,
268
+ ):
269
+ self.data_root = data_root
270
+ self.tokenizer = tokenizer
271
+ self.learnable_property = learnable_property
272
+ self.size = size
273
+ self.placeholder_token = placeholder_token
274
+ self.center_crop = center_crop
275
+ self.flip_p = flip_p
276
+
277
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
278
+
279
+ self.num_images = len(self.image_paths)
280
+ self._length = self.num_images
281
+
282
+ if set == "train":
283
+ self._length = self.num_images * repeats
284
+
285
+ self.interpolation = {
286
+ "linear": PIL_INTERPOLATION["linear"],
287
+ "bilinear": PIL_INTERPOLATION["bilinear"],
288
+ "bicubic": PIL_INTERPOLATION["bicubic"],
289
+ "lanczos": PIL_INTERPOLATION["lanczos"],
290
+ }[interpolation]
291
+
292
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
293
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
294
+
295
+ def __len__(self):
296
+ return self._length
297
+
298
+ def __getitem__(self, i):
299
+ example = {}
300
+ image = Image.open(self.image_paths[i % self.num_images])
301
+
302
+ if not image.mode == "RGB":
303
+ image = image.convert("RGB")
304
+
305
+ placeholder_string = self.placeholder_token
306
+ text = random.choice(self.templates).format(placeholder_string)
307
+
308
+ example["input_ids"] = self.tokenizer(
309
+ text,
310
+ padding="max_length",
311
+ truncation=True,
312
+ max_length=self.tokenizer.model_max_length,
313
+ return_tensors="pt",
314
+ ).input_ids[0]
315
+
316
+ # default to score-sde preprocessing
317
+ img = np.array(image).astype(np.uint8)
318
+
319
+ if self.center_crop:
320
+ crop = min(img.shape[0], img.shape[1])
321
+ (
322
+ h,
323
+ w,
324
+ ) = (
325
+ img.shape[0],
326
+ img.shape[1],
327
+ )
328
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
329
+
330
+ image = Image.fromarray(img)
331
+ image = image.resize((self.size, self.size), resample=self.interpolation)
332
+
333
+ image = self.flip_transform(image)
334
+ image = np.array(image).astype(np.uint8)
335
+ image = (image / 127.5 - 1.0).astype(np.float32)
336
+
337
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
338
+ return example
339
+
340
+
341
+ def resize_token_embeddings(model, new_num_tokens, initializer_token_id, placeholder_token_id, rng):
342
+ if model.config.vocab_size == new_num_tokens or new_num_tokens is None:
343
+ return
344
+ model.config.vocab_size = new_num_tokens
345
+
346
+ params = model.params
347
+ old_embeddings = params["text_model"]["embeddings"]["token_embedding"]["embedding"]
348
+ old_num_tokens, emb_dim = old_embeddings.shape
349
+
350
+ initializer = jax.nn.initializers.normal()
351
+
352
+ new_embeddings = initializer(rng, (new_num_tokens, emb_dim))
353
+ new_embeddings = new_embeddings.at[:old_num_tokens].set(old_embeddings)
354
+ new_embeddings = new_embeddings.at[placeholder_token_id].set(new_embeddings[initializer_token_id])
355
+ params["text_model"]["embeddings"]["token_embedding"]["embedding"] = new_embeddings
356
+
357
+ model.params = params
358
+ return model
359
+
360
+
361
+ def get_params_to_save(params):
362
+ return jax.device_get(jax.tree_util.tree_map(lambda x: x[0], params))
363
+
364
+
365
+ def main():
366
+ args = parse_args()
367
+
368
+ if args.seed is not None:
369
+ set_seed(args.seed)
370
+
371
+ if jax.process_index() == 0:
372
+ if args.output_dir is not None:
373
+ os.makedirs(args.output_dir, exist_ok=True)
374
+
375
+ if args.push_to_hub:
376
+ repo_id = create_repo(
377
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
378
+ ).repo_id
379
+
380
+ # Make one log on every process with the configuration for debugging.
381
+ logging.basicConfig(
382
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
383
+ datefmt="%m/%d/%Y %H:%M:%S",
384
+ level=logging.INFO,
385
+ )
386
+ # Setup logging, we only want one process per machine to log things on the screen.
387
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
388
+ if jax.process_index() == 0:
389
+ transformers.utils.logging.set_verbosity_info()
390
+ else:
391
+ transformers.utils.logging.set_verbosity_error()
392
+
393
+ # Load the tokenizer and add the placeholder token as a additional special token
394
+ if args.tokenizer_name:
395
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
396
+ elif args.pretrained_model_name_or_path:
397
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
398
+
399
+ # Add the placeholder token in tokenizer
400
+ num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
401
+ if num_added_tokens == 0:
402
+ raise ValueError(
403
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
404
+ " `placeholder_token` that is not already in the tokenizer."
405
+ )
406
+
407
+ # Convert the initializer_token, placeholder_token to ids
408
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
409
+ # Check if initializer_token is a single token or a sequence of tokens
410
+ if len(token_ids) > 1:
411
+ raise ValueError("The initializer token must be a single token.")
412
+
413
+ initializer_token_id = token_ids[0]
414
+ placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
415
+
416
+ # Load models and create wrapper for stable diffusion
417
+ text_encoder = FlaxCLIPTextModel.from_pretrained(
418
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
419
+ )
420
+ vae, vae_params = FlaxAutoencoderKL.from_pretrained(
421
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision
422
+ )
423
+ unet, unet_params = FlaxUNet2DConditionModel.from_pretrained(
424
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
425
+ )
426
+
427
+ # Create sampling rng
428
+ rng = jax.random.PRNGKey(args.seed)
429
+ rng, _ = jax.random.split(rng)
430
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
431
+ text_encoder = resize_token_embeddings(
432
+ text_encoder, len(tokenizer), initializer_token_id, placeholder_token_id, rng
433
+ )
434
+ original_token_embeds = text_encoder.params["text_model"]["embeddings"]["token_embedding"]["embedding"]
435
+
436
+ train_dataset = TextualInversionDataset(
437
+ data_root=args.train_data_dir,
438
+ tokenizer=tokenizer,
439
+ size=args.resolution,
440
+ placeholder_token=args.placeholder_token,
441
+ repeats=args.repeats,
442
+ learnable_property=args.learnable_property,
443
+ center_crop=args.center_crop,
444
+ set="train",
445
+ )
446
+
447
+ def collate_fn(examples):
448
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
449
+ input_ids = torch.stack([example["input_ids"] for example in examples])
450
+
451
+ batch = {"pixel_values": pixel_values, "input_ids": input_ids}
452
+ batch = {k: v.numpy() for k, v in batch.items()}
453
+
454
+ return batch
455
+
456
+ total_train_batch_size = args.train_batch_size * jax.local_device_count()
457
+ train_dataloader = torch.utils.data.DataLoader(
458
+ train_dataset, batch_size=total_train_batch_size, shuffle=True, drop_last=True, collate_fn=collate_fn
459
+ )
460
+
461
+ # Optimization
462
+ if args.scale_lr:
463
+ args.learning_rate = args.learning_rate * total_train_batch_size
464
+
465
+ constant_scheduler = optax.constant_schedule(args.learning_rate)
466
+
467
+ optimizer = optax.adamw(
468
+ learning_rate=constant_scheduler,
469
+ b1=args.adam_beta1,
470
+ b2=args.adam_beta2,
471
+ eps=args.adam_epsilon,
472
+ weight_decay=args.adam_weight_decay,
473
+ )
474
+
475
+ def create_mask(params, label_fn):
476
+ def _map(params, mask, label_fn):
477
+ for k in params:
478
+ if label_fn(k):
479
+ mask[k] = "token_embedding"
480
+ else:
481
+ if isinstance(params[k], dict):
482
+ mask[k] = {}
483
+ _map(params[k], mask[k], label_fn)
484
+ else:
485
+ mask[k] = "zero"
486
+
487
+ mask = {}
488
+ _map(params, mask, label_fn)
489
+ return mask
490
+
491
+ def zero_grads():
492
+ # from https://github.com/deepmind/optax/issues/159#issuecomment-896459491
493
+ def init_fn(_):
494
+ return ()
495
+
496
+ def update_fn(updates, state, params=None):
497
+ return jax.tree_util.tree_map(jnp.zeros_like, updates), ()
498
+
499
+ return optax.GradientTransformation(init_fn, update_fn)
500
+
501
+ # Zero out gradients of layers other than the token embedding layer
502
+ tx = optax.multi_transform(
503
+ {"token_embedding": optimizer, "zero": zero_grads()},
504
+ create_mask(text_encoder.params, lambda s: s == "token_embedding"),
505
+ )
506
+
507
+ state = train_state.TrainState.create(apply_fn=text_encoder.__call__, params=text_encoder.params, tx=tx)
508
+
509
+ noise_scheduler = FlaxDDPMScheduler(
510
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000
511
+ )
512
+ noise_scheduler_state = noise_scheduler.create_state()
513
+
514
+ # Initialize our training
515
+ train_rngs = jax.random.split(rng, jax.local_device_count())
516
+
517
+ # Define gradient train step fn
518
+ def train_step(state, vae_params, unet_params, batch, train_rng):
519
+ dropout_rng, sample_rng, new_train_rng = jax.random.split(train_rng, 3)
520
+
521
+ def compute_loss(params):
522
+ vae_outputs = vae.apply(
523
+ {"params": vae_params}, batch["pixel_values"], deterministic=True, method=vae.encode
524
+ )
525
+ latents = vae_outputs.latent_dist.sample(sample_rng)
526
+ # (NHWC) -> (NCHW)
527
+ latents = jnp.transpose(latents, (0, 3, 1, 2))
528
+ latents = latents * vae.config.scaling_factor
529
+
530
+ noise_rng, timestep_rng = jax.random.split(sample_rng)
531
+ noise = jax.random.normal(noise_rng, latents.shape)
532
+ bsz = latents.shape[0]
533
+ timesteps = jax.random.randint(
534
+ timestep_rng,
535
+ (bsz,),
536
+ 0,
537
+ noise_scheduler.config.num_train_timesteps,
538
+ )
539
+ noisy_latents = noise_scheduler.add_noise(noise_scheduler_state, latents, noise, timesteps)
540
+ encoder_hidden_states = state.apply_fn(
541
+ batch["input_ids"], params=params, dropout_rng=dropout_rng, train=True
542
+ )[0]
543
+ # Predict the noise residual and compute loss
544
+ model_pred = unet.apply(
545
+ {"params": unet_params}, noisy_latents, timesteps, encoder_hidden_states, train=False
546
+ ).sample
547
+
548
+ # Get the target for loss depending on the prediction type
549
+ if noise_scheduler.config.prediction_type == "epsilon":
550
+ target = noise
551
+ elif noise_scheduler.config.prediction_type == "v_prediction":
552
+ target = noise_scheduler.get_velocity(noise_scheduler_state, latents, noise, timesteps)
553
+ else:
554
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
555
+
556
+ loss = (target - model_pred) ** 2
557
+ loss = loss.mean()
558
+
559
+ return loss
560
+
561
+ grad_fn = jax.value_and_grad(compute_loss)
562
+ loss, grad = grad_fn(state.params)
563
+ grad = jax.lax.pmean(grad, "batch")
564
+ new_state = state.apply_gradients(grads=grad)
565
+
566
+ # Keep the token embeddings fixed except the newly added embeddings for the concept,
567
+ # as we only want to optimize the concept embeddings
568
+ token_embeds = original_token_embeds.at[placeholder_token_id].set(
569
+ new_state.params["text_model"]["embeddings"]["token_embedding"]["embedding"][placeholder_token_id]
570
+ )
571
+ new_state.params["text_model"]["embeddings"]["token_embedding"]["embedding"] = token_embeds
572
+
573
+ metrics = {"loss": loss}
574
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
575
+ return new_state, metrics, new_train_rng
576
+
577
+ # Create parallel version of the train and eval step
578
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
579
+
580
+ # Replicate the train state on each device
581
+ state = jax_utils.replicate(state)
582
+ vae_params = jax_utils.replicate(vae_params)
583
+ unet_params = jax_utils.replicate(unet_params)
584
+
585
+ # Train!
586
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader))
587
+
588
+ # Scheduler and math around the number of training steps.
589
+ if args.max_train_steps is None:
590
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
591
+
592
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
593
+
594
+ logger.info("***** Running training *****")
595
+ logger.info(f" Num examples = {len(train_dataset)}")
596
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
597
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
598
+ logger.info(f" Total train batch size (w. parallel & distributed) = {total_train_batch_size}")
599
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
600
+
601
+ global_step = 0
602
+
603
+ epochs = tqdm(range(args.num_train_epochs), desc=f"Epoch ... (1/{args.num_train_epochs})", position=0)
604
+ for epoch in epochs:
605
+ # ======================== Training ================================
606
+
607
+ train_metrics = []
608
+
609
+ steps_per_epoch = len(train_dataset) // total_train_batch_size
610
+ train_step_progress_bar = tqdm(total=steps_per_epoch, desc="Training...", position=1, leave=False)
611
+ # train
612
+ for batch in train_dataloader:
613
+ batch = shard(batch)
614
+ state, train_metric, train_rngs = p_train_step(state, vae_params, unet_params, batch, train_rngs)
615
+ train_metrics.append(train_metric)
616
+
617
+ train_step_progress_bar.update(1)
618
+ global_step += 1
619
+
620
+ if global_step >= args.max_train_steps:
621
+ break
622
+ if global_step % args.save_steps == 0:
623
+ learned_embeds = get_params_to_save(state.params)["text_model"]["embeddings"]["token_embedding"][
624
+ "embedding"
625
+ ][placeholder_token_id]
626
+ learned_embeds_dict = {args.placeholder_token: learned_embeds}
627
+ jnp.save(
628
+ os.path.join(args.output_dir, "learned_embeds-" + str(global_step) + ".npy"), learned_embeds_dict
629
+ )
630
+
631
+ train_metric = jax_utils.unreplicate(train_metric)
632
+
633
+ train_step_progress_bar.close()
634
+ epochs.write(f"Epoch... ({epoch + 1}/{args.num_train_epochs} | Loss: {train_metric['loss']})")
635
+
636
+ # Create the pipeline using using the trained modules and save it.
637
+ if jax.process_index() == 0:
638
+ scheduler = FlaxPNDMScheduler(
639
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", skip_prk_steps=True
640
+ )
641
+ safety_checker = FlaxStableDiffusionSafetyChecker.from_pretrained(
642
+ "CompVis/stable-diffusion-safety-checker", from_pt=True
643
+ )
644
+ pipeline = FlaxStableDiffusionPipeline(
645
+ text_encoder=text_encoder,
646
+ vae=vae,
647
+ unet=unet,
648
+ tokenizer=tokenizer,
649
+ scheduler=scheduler,
650
+ safety_checker=safety_checker,
651
+ feature_extractor=CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32"),
652
+ )
653
+
654
+ pipeline.save_pretrained(
655
+ args.output_dir,
656
+ params={
657
+ "text_encoder": get_params_to_save(state.params),
658
+ "vae": get_params_to_save(vae_params),
659
+ "unet": get_params_to_save(unet_params),
660
+ "safety_checker": safety_checker.params,
661
+ },
662
+ )
663
+
664
+ # Also save the newly trained embeddings
665
+ learned_embeds = get_params_to_save(state.params)["text_model"]["embeddings"]["token_embedding"]["embedding"][
666
+ placeholder_token_id
667
+ ]
668
+ learned_embeds_dict = {args.placeholder_token: learned_embeds}
669
+ jnp.save(os.path.join(args.output_dir, "learned_embeds.npy"), learned_embeds_dict)
670
+
671
+ if args.push_to_hub:
672
+ upload_folder(
673
+ repo_id=repo_id,
674
+ folder_path=args.output_dir,
675
+ commit_message="End of training",
676
+ ignore_patterns=["step_*", "epoch_*"],
677
+ )
678
+
679
+
680
+ if __name__ == "__main__":
681
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/textual_inversion/textual_inversion_sdxl.py ADDED
@@ -0,0 +1,1140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 logging
19
+ import math
20
+ import os
21
+ import random
22
+ import shutil
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import PIL
27
+ import safetensors
28
+ import torch
29
+ import torch.nn.functional as F
30
+ import torch.utils.checkpoint
31
+ import transformers
32
+ from accelerate import Accelerator
33
+ from accelerate.logging import get_logger
34
+ from accelerate.utils import ProjectConfiguration, set_seed
35
+ from huggingface_hub import create_repo, upload_folder
36
+ from packaging import version
37
+ from PIL import Image
38
+ from torch.utils.data import Dataset
39
+ from torchvision import transforms
40
+ from tqdm.auto import tqdm
41
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
42
+
43
+ import diffusers
44
+ from diffusers import (
45
+ AutoencoderKL,
46
+ DDPMScheduler,
47
+ DiffusionPipeline,
48
+ DPMSolverMultistepScheduler,
49
+ UNet2DConditionModel,
50
+ )
51
+ from diffusers.optimization import get_scheduler
52
+ from diffusers.utils import check_min_version, is_wandb_available
53
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
54
+ from diffusers.utils.import_utils import is_xformers_available
55
+
56
+
57
+ if is_wandb_available():
58
+ import wandb
59
+
60
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
61
+ PIL_INTERPOLATION = {
62
+ "linear": PIL.Image.Resampling.BILINEAR,
63
+ "bilinear": PIL.Image.Resampling.BILINEAR,
64
+ "bicubic": PIL.Image.Resampling.BICUBIC,
65
+ "lanczos": PIL.Image.Resampling.LANCZOS,
66
+ "nearest": PIL.Image.Resampling.NEAREST,
67
+ }
68
+ else:
69
+ PIL_INTERPOLATION = {
70
+ "linear": PIL.Image.LINEAR,
71
+ "bilinear": PIL.Image.BILINEAR,
72
+ "bicubic": PIL.Image.BICUBIC,
73
+ "lanczos": PIL.Image.LANCZOS,
74
+ "nearest": PIL.Image.NEAREST,
75
+ }
76
+ # ------------------------------------------------------------------------------
77
+
78
+
79
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
80
+ check_min_version("0.39.0.dev0")
81
+
82
+ logger = get_logger(__name__)
83
+
84
+
85
+ def save_model_card(repo_id: str, images=None, base_model=str, repo_folder=None):
86
+ img_str = ""
87
+ for i, image in enumerate(images):
88
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
89
+ img_str += f"![img_{i}](./image_{i}.png)\n"
90
+
91
+ model_description = f"""
92
+ # Textual inversion text2image fine-tuning - {repo_id}
93
+ These are textual inversion adaption weights for {base_model}. You can find some example images in the following. \n
94
+ {img_str}
95
+ """
96
+ model_card = load_or_create_model_card(
97
+ repo_id_or_path=repo_id,
98
+ from_training=True,
99
+ license="creativeml-openrail-m",
100
+ base_model=base_model,
101
+ model_description=model_description,
102
+ inference=True,
103
+ )
104
+
105
+ tags = [
106
+ "stable-diffusion-xl",
107
+ "stable-diffusion-xl-diffusers",
108
+ "text-to-image",
109
+ "diffusers",
110
+ "diffusers-training",
111
+ "textual_inversion",
112
+ ]
113
+
114
+ model_card = populate_model_card(model_card, tags=tags)
115
+
116
+ model_card.save(os.path.join(repo_folder, "README.md"))
117
+
118
+
119
+ def log_validation(
120
+ text_encoder_1,
121
+ text_encoder_2,
122
+ tokenizer_1,
123
+ tokenizer_2,
124
+ unet,
125
+ vae,
126
+ args,
127
+ accelerator,
128
+ weight_dtype,
129
+ epoch,
130
+ is_final_validation=False,
131
+ ):
132
+ logger.info(
133
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
134
+ f" {args.validation_prompt}."
135
+ )
136
+ pipeline = DiffusionPipeline.from_pretrained(
137
+ args.pretrained_model_name_or_path,
138
+ text_encoder=accelerator.unwrap_model(text_encoder_1),
139
+ text_encoder_2=accelerator.unwrap_model(text_encoder_2),
140
+ tokenizer=tokenizer_1,
141
+ tokenizer_2=tokenizer_2,
142
+ unet=unet,
143
+ vae=vae,
144
+ safety_checker=None,
145
+ revision=args.revision,
146
+ variant=args.variant,
147
+ torch_dtype=weight_dtype,
148
+ )
149
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
150
+ pipeline = pipeline.to(accelerator.device)
151
+ pipeline.set_progress_bar_config(disable=True)
152
+
153
+ # run inference
154
+ generator = None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)
155
+ images = []
156
+ for _ in range(args.num_validation_images):
157
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
158
+ images.append(image)
159
+
160
+ tracker_key = "test" if is_final_validation else "validation"
161
+ for tracker in accelerator.trackers:
162
+ if tracker.name == "tensorboard":
163
+ np_images = np.stack([np.asarray(img) for img in images])
164
+ tracker.writer.add_images(tracker_key, np_images, epoch, dataformats="NHWC")
165
+ if tracker.name == "wandb":
166
+ tracker.log(
167
+ {
168
+ tracker_key: [
169
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
170
+ ]
171
+ }
172
+ )
173
+
174
+ del pipeline
175
+ torch.cuda.empty_cache()
176
+ return images
177
+
178
+
179
+ def save_progress(text_encoder, placeholder_token_ids, accelerator, args, save_path, safe_serialization=True):
180
+ logger.info("Saving embeddings")
181
+ learned_embeds = (
182
+ accelerator.unwrap_model(text_encoder)
183
+ .get_input_embeddings()
184
+ .weight[min(placeholder_token_ids) : max(placeholder_token_ids) + 1]
185
+ )
186
+ learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
187
+
188
+ if safe_serialization:
189
+ safetensors.torch.save_file(learned_embeds_dict, save_path, metadata={"format": "pt"})
190
+ else:
191
+ torch.save(learned_embeds_dict, save_path)
192
+
193
+
194
+ def parse_args():
195
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
196
+ parser.add_argument(
197
+ "--save_steps",
198
+ type=int,
199
+ default=500,
200
+ help="Save learned_embeds.bin every X updates steps.",
201
+ )
202
+ parser.add_argument(
203
+ "--save_as_full_pipeline",
204
+ action="store_true",
205
+ help="Save the complete stable diffusion pipeline.",
206
+ )
207
+ parser.add_argument(
208
+ "--num_vectors",
209
+ type=int,
210
+ default=1,
211
+ help="How many textual inversion vectors shall be used to learn the concept.",
212
+ )
213
+ parser.add_argument(
214
+ "--pretrained_model_name_or_path",
215
+ type=str,
216
+ default=None,
217
+ required=True,
218
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
219
+ )
220
+ parser.add_argument(
221
+ "--revision",
222
+ type=str,
223
+ default=None,
224
+ required=False,
225
+ help="Revision of pretrained model identifier from huggingface.co/models.",
226
+ )
227
+ parser.add_argument(
228
+ "--variant",
229
+ type=str,
230
+ default=None,
231
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
232
+ )
233
+ parser.add_argument(
234
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
235
+ )
236
+ parser.add_argument(
237
+ "--placeholder_token",
238
+ type=str,
239
+ default=None,
240
+ required=True,
241
+ help="A token to use as a placeholder for the concept.",
242
+ )
243
+ parser.add_argument(
244
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
245
+ )
246
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
247
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
248
+ parser.add_argument(
249
+ "--output_dir",
250
+ type=str,
251
+ default="text-inversion-model",
252
+ help="The output directory where the model predictions and checkpoints will be written.",
253
+ )
254
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
255
+ parser.add_argument(
256
+ "--resolution",
257
+ type=int,
258
+ default=512,
259
+ help=(
260
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
261
+ " resolution"
262
+ ),
263
+ )
264
+ parser.add_argument(
265
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
266
+ )
267
+ parser.add_argument(
268
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
269
+ )
270
+ parser.add_argument("--num_train_epochs", type=int, default=100)
271
+ parser.add_argument(
272
+ "--max_train_steps",
273
+ type=int,
274
+ default=5000,
275
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
276
+ )
277
+ parser.add_argument(
278
+ "--gradient_accumulation_steps",
279
+ type=int,
280
+ default=1,
281
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
282
+ )
283
+ parser.add_argument(
284
+ "--gradient_checkpointing",
285
+ action="store_true",
286
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
287
+ )
288
+ parser.add_argument(
289
+ "--learning_rate",
290
+ type=float,
291
+ default=1e-4,
292
+ help="Initial learning rate (after the potential warmup period) to use.",
293
+ )
294
+ parser.add_argument(
295
+ "--scale_lr",
296
+ action="store_true",
297
+ default=False,
298
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
299
+ )
300
+ parser.add_argument(
301
+ "--lr_scheduler",
302
+ type=str,
303
+ default="constant",
304
+ help=(
305
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
306
+ ' "constant", "constant_with_warmup"]'
307
+ ),
308
+ )
309
+ parser.add_argument(
310
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
311
+ )
312
+ parser.add_argument(
313
+ "--lr_num_cycles",
314
+ type=int,
315
+ default=1,
316
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
317
+ )
318
+ parser.add_argument(
319
+ "--dataloader_num_workers",
320
+ type=int,
321
+ default=0,
322
+ help=(
323
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
324
+ ),
325
+ )
326
+ parser.add_argument(
327
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
328
+ )
329
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
330
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
331
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
332
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
333
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
334
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
335
+ parser.add_argument(
336
+ "--hub_model_id",
337
+ type=str,
338
+ default=None,
339
+ help="The name of the repository to keep in sync with the local `output_dir`.",
340
+ )
341
+ parser.add_argument(
342
+ "--logging_dir",
343
+ type=str,
344
+ default="logs",
345
+ help=(
346
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
347
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
348
+ ),
349
+ )
350
+ parser.add_argument(
351
+ "--mixed_precision",
352
+ type=str,
353
+ default="no",
354
+ choices=["no", "fp16", "bf16"],
355
+ help=(
356
+ "Whether to use mixed precision. Choose"
357
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
358
+ "and an Nvidia Ampere GPU."
359
+ ),
360
+ )
361
+ parser.add_argument(
362
+ "--allow_tf32",
363
+ action="store_true",
364
+ help=(
365
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
366
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
367
+ ),
368
+ )
369
+ parser.add_argument(
370
+ "--report_to",
371
+ type=str,
372
+ default="tensorboard",
373
+ help=(
374
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
375
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
376
+ ),
377
+ )
378
+ parser.add_argument(
379
+ "--validation_prompt",
380
+ type=str,
381
+ default=None,
382
+ help="A prompt that is used during validation to verify that the model is learning.",
383
+ )
384
+ parser.add_argument(
385
+ "--num_validation_images",
386
+ type=int,
387
+ default=4,
388
+ help="Number of images that should be generated during validation with `validation_prompt`.",
389
+ )
390
+ parser.add_argument(
391
+ "--validation_steps",
392
+ type=int,
393
+ default=100,
394
+ help=(
395
+ "Run validation every X steps. Validation consists of running the prompt"
396
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
397
+ " and logging the images."
398
+ ),
399
+ )
400
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
401
+ parser.add_argument(
402
+ "--checkpointing_steps",
403
+ type=int,
404
+ default=500,
405
+ help=(
406
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
407
+ " training using `--resume_from_checkpoint`."
408
+ ),
409
+ )
410
+ parser.add_argument(
411
+ "--checkpoints_total_limit",
412
+ type=int,
413
+ default=None,
414
+ help=("Max number of checkpoints to store."),
415
+ )
416
+ parser.add_argument(
417
+ "--resume_from_checkpoint",
418
+ type=str,
419
+ default=None,
420
+ help=(
421
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
422
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
423
+ ),
424
+ )
425
+ parser.add_argument(
426
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
427
+ )
428
+
429
+ args = parser.parse_args()
430
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
431
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
432
+ args.local_rank = env_local_rank
433
+
434
+ if args.train_data_dir is None:
435
+ raise ValueError("You must specify a train data directory.")
436
+
437
+ return args
438
+
439
+
440
+ imagenet_templates_small = [
441
+ "a photo of a {}",
442
+ "a rendering of a {}",
443
+ "a cropped photo of the {}",
444
+ "the photo of a {}",
445
+ "a photo of a clean {}",
446
+ "a photo of a dirty {}",
447
+ "a dark photo of the {}",
448
+ "a photo of my {}",
449
+ "a photo of the cool {}",
450
+ "a close-up photo of a {}",
451
+ "a bright photo of the {}",
452
+ "a cropped photo of a {}",
453
+ "a photo of the {}",
454
+ "a good photo of the {}",
455
+ "a photo of one {}",
456
+ "a close-up photo of the {}",
457
+ "a rendition of the {}",
458
+ "a photo of the clean {}",
459
+ "a rendition of a {}",
460
+ "a photo of a nice {}",
461
+ "a good photo of a {}",
462
+ "a photo of the nice {}",
463
+ "a photo of the small {}",
464
+ "a photo of the weird {}",
465
+ "a photo of the large {}",
466
+ "a photo of a cool {}",
467
+ "a photo of a small {}",
468
+ ]
469
+
470
+ imagenet_style_templates_small = [
471
+ "a painting in the style of {}",
472
+ "a rendering in the style of {}",
473
+ "a cropped painting in the style of {}",
474
+ "the painting in the style of {}",
475
+ "a clean painting in the style of {}",
476
+ "a dirty painting in the style of {}",
477
+ "a dark painting in the style of {}",
478
+ "a picture in the style of {}",
479
+ "a cool painting in the style of {}",
480
+ "a close-up painting in the style of {}",
481
+ "a bright painting in the style of {}",
482
+ "a cropped painting in the style of {}",
483
+ "a good painting in the style of {}",
484
+ "a close-up painting in the style of {}",
485
+ "a rendition in the style of {}",
486
+ "a nice painting in the style of {}",
487
+ "a small painting in the style of {}",
488
+ "a weird painting in the style of {}",
489
+ "a large painting in the style of {}",
490
+ ]
491
+
492
+
493
+ class TextualInversionDataset(Dataset):
494
+ def __init__(
495
+ self,
496
+ data_root,
497
+ tokenizer_1,
498
+ tokenizer_2,
499
+ learnable_property="object", # [object, style]
500
+ size=512,
501
+ repeats=100,
502
+ interpolation="bicubic",
503
+ flip_p=0.5,
504
+ set="train",
505
+ placeholder_token="*",
506
+ center_crop=False,
507
+ ):
508
+ self.data_root = data_root
509
+ self.tokenizer_1 = tokenizer_1
510
+ self.tokenizer_2 = tokenizer_2
511
+ self.learnable_property = learnable_property
512
+ self.size = size
513
+ self.placeholder_token = placeholder_token
514
+ self.center_crop = center_crop
515
+ self.flip_p = flip_p
516
+
517
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
518
+
519
+ self.num_images = len(self.image_paths)
520
+ self._length = self.num_images
521
+
522
+ if set == "train":
523
+ self._length = self.num_images * repeats
524
+
525
+ self.interpolation = {
526
+ "linear": PIL_INTERPOLATION["linear"],
527
+ "bilinear": PIL_INTERPOLATION["bilinear"],
528
+ "bicubic": PIL_INTERPOLATION["bicubic"],
529
+ "lanczos": PIL_INTERPOLATION["lanczos"],
530
+ }[interpolation]
531
+
532
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
533
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
534
+ self.crop = transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size)
535
+
536
+ def __len__(self):
537
+ return self._length
538
+
539
+ def __getitem__(self, i):
540
+ example = {}
541
+ image = Image.open(self.image_paths[i % self.num_images])
542
+
543
+ if not image.mode == "RGB":
544
+ image = image.convert("RGB")
545
+
546
+ placeholder_string = self.placeholder_token
547
+ text = random.choice(self.templates).format(placeholder_string)
548
+
549
+ example["original_size"] = (image.height, image.width)
550
+
551
+ image = image.resize((self.size, self.size), resample=self.interpolation)
552
+
553
+ if self.center_crop:
554
+ y1 = max(0, int(round((image.height - self.size) / 2.0)))
555
+ x1 = max(0, int(round((image.width - self.size) / 2.0)))
556
+ image = self.crop(image)
557
+ else:
558
+ y1, x1, h, w = self.crop.get_params(image, (self.size, self.size))
559
+ image = transforms.functional.crop(image, y1, x1, h, w)
560
+
561
+ example["crop_top_left"] = (y1, x1)
562
+
563
+ example["input_ids_1"] = self.tokenizer_1(
564
+ text,
565
+ padding="max_length",
566
+ truncation=True,
567
+ max_length=self.tokenizer_1.model_max_length,
568
+ return_tensors="pt",
569
+ ).input_ids[0]
570
+
571
+ example["input_ids_2"] = self.tokenizer_2(
572
+ text,
573
+ padding="max_length",
574
+ truncation=True,
575
+ max_length=self.tokenizer_2.model_max_length,
576
+ return_tensors="pt",
577
+ ).input_ids[0]
578
+
579
+ # default to score-sde preprocessing
580
+ img = np.array(image).astype(np.uint8)
581
+
582
+ image = Image.fromarray(img)
583
+
584
+ image = self.flip_transform(image)
585
+ image = np.array(image).astype(np.uint8)
586
+ image = (image / 127.5 - 1.0).astype(np.float32)
587
+
588
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
589
+ return example
590
+
591
+
592
+ def main():
593
+ args = parse_args()
594
+ if args.report_to == "wandb" and args.hub_token is not None:
595
+ raise ValueError(
596
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
597
+ " Please use `hf auth login` to authenticate with the Hub."
598
+ )
599
+
600
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
601
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
602
+ accelerator = Accelerator(
603
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
604
+ mixed_precision=args.mixed_precision,
605
+ log_with=args.report_to,
606
+ project_config=accelerator_project_config,
607
+ )
608
+
609
+ # Disable AMP for MPS.
610
+ if torch.backends.mps.is_available():
611
+ accelerator.native_amp = False
612
+
613
+ if args.report_to == "wandb":
614
+ if not is_wandb_available():
615
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
616
+
617
+ # Make one log on every process with the configuration for debugging.
618
+ logging.basicConfig(
619
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
620
+ datefmt="%m/%d/%Y %H:%M:%S",
621
+ level=logging.INFO,
622
+ )
623
+ logger.info(accelerator.state, main_process_only=False)
624
+ if accelerator.is_local_main_process:
625
+ transformers.utils.logging.set_verbosity_warning()
626
+ diffusers.utils.logging.set_verbosity_info()
627
+ else:
628
+ transformers.utils.logging.set_verbosity_error()
629
+ diffusers.utils.logging.set_verbosity_error()
630
+
631
+ # If passed along, set the training seed now.
632
+ if args.seed is not None:
633
+ set_seed(args.seed)
634
+
635
+ # Handle the repository creation
636
+ if accelerator.is_main_process:
637
+ if args.output_dir is not None:
638
+ os.makedirs(args.output_dir, exist_ok=True)
639
+
640
+ if args.push_to_hub:
641
+ repo_id = create_repo(
642
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
643
+ ).repo_id
644
+
645
+ # Load tokenizer
646
+ tokenizer_1 = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
647
+ tokenizer_2 = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer_2")
648
+
649
+ # Load scheduler and models
650
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
651
+ text_encoder_1 = CLIPTextModel.from_pretrained(
652
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
653
+ )
654
+ text_encoder_2 = CLIPTextModelWithProjection.from_pretrained(
655
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision
656
+ )
657
+ vae = AutoencoderKL.from_pretrained(
658
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
659
+ )
660
+ unet = UNet2DConditionModel.from_pretrained(
661
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
662
+ )
663
+
664
+ # Add the placeholder token in tokenizer_1
665
+ placeholder_tokens = [args.placeholder_token]
666
+
667
+ if args.num_vectors < 1:
668
+ raise ValueError(f"--num_vectors has to be larger or equal to 1, but is {args.num_vectors}")
669
+
670
+ # add dummy tokens for multi-vector
671
+ additional_tokens = []
672
+ for i in range(1, args.num_vectors):
673
+ additional_tokens.append(f"{args.placeholder_token}_{i}")
674
+ placeholder_tokens += additional_tokens
675
+
676
+ num_added_tokens = tokenizer_1.add_tokens(placeholder_tokens)
677
+ if num_added_tokens != args.num_vectors:
678
+ raise ValueError(
679
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
680
+ " `placeholder_token` that is not already in the tokenizer."
681
+ )
682
+ num_added_tokens = tokenizer_2.add_tokens(placeholder_tokens)
683
+ if num_added_tokens != args.num_vectors:
684
+ raise ValueError(
685
+ f"The 2nd tokenizer already contains the token {args.placeholder_token}. Please pass a different"
686
+ " `placeholder_token` that is not already in the tokenizer."
687
+ )
688
+
689
+ # Convert the initializer_token, placeholder_token to ids
690
+ token_ids = tokenizer_1.encode(args.initializer_token, add_special_tokens=False)
691
+ token_ids_2 = tokenizer_2.encode(args.initializer_token, add_special_tokens=False)
692
+
693
+ # Check if initializer_token is a single token or a sequence of tokens
694
+ if len(token_ids) > 1 or len(token_ids_2) > 1:
695
+ raise ValueError("The initializer token must be a single token.")
696
+
697
+ initializer_token_id = token_ids[0]
698
+ placeholder_token_ids = tokenizer_1.convert_tokens_to_ids(placeholder_tokens)
699
+ initializer_token_id_2 = token_ids_2[0]
700
+ placeholder_token_ids_2 = tokenizer_2.convert_tokens_to_ids(placeholder_tokens)
701
+
702
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
703
+ text_encoder_1.resize_token_embeddings(len(tokenizer_1))
704
+ text_encoder_2.resize_token_embeddings(len(tokenizer_2))
705
+
706
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
707
+ token_embeds = text_encoder_1.get_input_embeddings().weight.data
708
+ token_embeds_2 = text_encoder_2.get_input_embeddings().weight.data
709
+ with torch.no_grad():
710
+ for token_id in placeholder_token_ids:
711
+ token_embeds[token_id] = token_embeds[initializer_token_id].clone()
712
+ for token_id in placeholder_token_ids_2:
713
+ token_embeds_2[token_id] = token_embeds_2[initializer_token_id_2].clone()
714
+
715
+ # Freeze vae and unet
716
+ vae.requires_grad_(False)
717
+ unet.requires_grad_(False)
718
+
719
+ # Freeze all parameters except for the token embeddings in text encoder
720
+ text_module_1 = text_encoder_1.text_model if hasattr(text_encoder_1, "text_model") else text_encoder_1
721
+ text_module_1.encoder.requires_grad_(False)
722
+ text_module_1.final_layer_norm.requires_grad_(False)
723
+ text_module_1.embeddings.position_embedding.requires_grad_(False)
724
+ text_module_2 = text_encoder_2.text_model if hasattr(text_encoder_2, "text_model") else text_encoder_2
725
+ text_module_2.encoder.requires_grad_(False)
726
+ text_module_2.final_layer_norm.requires_grad_(False)
727
+ text_module_2.embeddings.position_embedding.requires_grad_(False)
728
+
729
+ if args.gradient_checkpointing:
730
+ text_encoder_1.gradient_checkpointing_enable()
731
+ text_encoder_2.gradient_checkpointing_enable()
732
+
733
+ if args.enable_xformers_memory_efficient_attention:
734
+ if is_xformers_available():
735
+ import xformers
736
+
737
+ xformers_version = version.parse(xformers.__version__)
738
+ if xformers_version == version.parse("0.0.16"):
739
+ logger.warning(
740
+ "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."
741
+ )
742
+ unet.enable_xformers_memory_efficient_attention()
743
+ else:
744
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
745
+
746
+ # Enable TF32 for faster training on Ampere GPUs,
747
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
748
+ if args.allow_tf32:
749
+ torch.backends.cuda.matmul.allow_tf32 = True
750
+
751
+ if args.scale_lr:
752
+ args.learning_rate = (
753
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
754
+ )
755
+
756
+ # Initialize the optimizer
757
+ if args.use_8bit_adam:
758
+ try:
759
+ import bitsandbytes as bnb
760
+ except ImportError:
761
+ raise ImportError(
762
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
763
+ )
764
+
765
+ optimizer_class = bnb.optim.AdamW8bit
766
+ else:
767
+ optimizer_class = torch.optim.AdamW
768
+
769
+ optimizer = optimizer_class(
770
+ # only optimize the embeddings
771
+ [
772
+ (
773
+ text_encoder_1.text_model if hasattr(text_encoder_1, "text_model") else text_encoder_1
774
+ ).embeddings.token_embedding.weight,
775
+ (
776
+ text_encoder_2.text_model if hasattr(text_encoder_2, "text_model") else text_encoder_2
777
+ ).embeddings.token_embedding.weight,
778
+ ],
779
+ lr=args.learning_rate,
780
+ betas=(args.adam_beta1, args.adam_beta2),
781
+ weight_decay=args.adam_weight_decay,
782
+ eps=args.adam_epsilon,
783
+ )
784
+
785
+ placeholder_token = " ".join(tokenizer_1.convert_ids_to_tokens(placeholder_token_ids))
786
+ # Dataset and DataLoaders creation:
787
+ train_dataset = TextualInversionDataset(
788
+ data_root=args.train_data_dir,
789
+ tokenizer_1=tokenizer_1,
790
+ tokenizer_2=tokenizer_2,
791
+ size=args.resolution,
792
+ placeholder_token=placeholder_token,
793
+ repeats=args.repeats,
794
+ learnable_property=args.learnable_property,
795
+ center_crop=args.center_crop,
796
+ set="train",
797
+ )
798
+ train_dataloader = torch.utils.data.DataLoader(
799
+ train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
800
+ )
801
+
802
+ # Scheduler and math around the number of training steps.
803
+ # Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
804
+ num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
805
+ if args.max_train_steps is None:
806
+ len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
807
+ num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
808
+ num_training_steps_for_scheduler = (
809
+ args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
810
+ )
811
+ else:
812
+ num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
813
+
814
+ lr_scheduler = get_scheduler(
815
+ args.lr_scheduler,
816
+ optimizer=optimizer,
817
+ num_warmup_steps=num_warmup_steps_for_scheduler,
818
+ num_training_steps=num_training_steps_for_scheduler,
819
+ num_cycles=args.lr_num_cycles,
820
+ )
821
+
822
+ text_encoder_1.train()
823
+ text_encoder_2.train()
824
+ # Prepare everything with our `accelerator`.
825
+ text_encoder_1, text_encoder_2, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
826
+ text_encoder_1, text_encoder_2, optimizer, train_dataloader, lr_scheduler
827
+ )
828
+
829
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
830
+ # as these weights are only used for inference, keeping weights in full precision is not required.
831
+ weight_dtype = torch.float32
832
+ if accelerator.mixed_precision == "fp16":
833
+ weight_dtype = torch.float16
834
+ elif accelerator.mixed_precision == "bf16":
835
+ weight_dtype = torch.bfloat16
836
+
837
+ # Move vae and unet and text_encoder_2 to device and cast to weight_dtype
838
+ unet.to(accelerator.device, dtype=weight_dtype)
839
+ vae.to(accelerator.device, dtype=weight_dtype)
840
+ text_encoder_2.to(accelerator.device, dtype=weight_dtype)
841
+
842
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
843
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
844
+ if args.max_train_steps is None:
845
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
846
+ if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
847
+ logger.warning(
848
+ f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
849
+ f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
850
+ f"This inconsistency may result in the learning rate scheduler not functioning properly."
851
+ )
852
+ # Afterwards we recalculate our number of training epochs
853
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
854
+
855
+ # We need to initialize the trackers we use, and also store our configuration.
856
+ # The trackers initializes automatically on the main process.
857
+ if accelerator.is_main_process:
858
+ accelerator.init_trackers("textual_inversion", config=vars(args))
859
+
860
+ # Train!
861
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
862
+
863
+ logger.info("***** Running training *****")
864
+ logger.info(f" Num examples = {len(train_dataset)}")
865
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
866
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
867
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
868
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
869
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
870
+ global_step = 0
871
+ first_epoch = 0
872
+ # Potentially load in the weights and states from a previous save
873
+ if args.resume_from_checkpoint:
874
+ if args.resume_from_checkpoint != "latest":
875
+ path = os.path.basename(args.resume_from_checkpoint)
876
+ else:
877
+ # Get the most recent checkpoint
878
+ dirs = os.listdir(args.output_dir)
879
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
880
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
881
+ path = dirs[-1] if len(dirs) > 0 else None
882
+
883
+ if path is None:
884
+ accelerator.print(
885
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
886
+ )
887
+ args.resume_from_checkpoint = None
888
+ initial_global_step = 0
889
+ else:
890
+ accelerator.print(f"Resuming from checkpoint {path}")
891
+ accelerator.load_state(os.path.join(args.output_dir, path))
892
+ global_step = int(path.split("-")[1])
893
+
894
+ initial_global_step = global_step
895
+ first_epoch = global_step // num_update_steps_per_epoch
896
+
897
+ else:
898
+ initial_global_step = 0
899
+
900
+ progress_bar = tqdm(
901
+ range(0, args.max_train_steps),
902
+ initial=initial_global_step,
903
+ desc="Steps",
904
+ # Only show the progress bar once on each machine.
905
+ disable=not accelerator.is_local_main_process,
906
+ )
907
+
908
+ # keep original embeddings as reference
909
+ orig_embeds_params = accelerator.unwrap_model(text_encoder_1).get_input_embeddings().weight.data.clone()
910
+ orig_embeds_params_2 = accelerator.unwrap_model(text_encoder_2).get_input_embeddings().weight.data.clone()
911
+
912
+ for epoch in range(first_epoch, args.num_train_epochs):
913
+ text_encoder_1.train()
914
+ text_encoder_2.train()
915
+ for step, batch in enumerate(train_dataloader):
916
+ with accelerator.accumulate([text_encoder_1, text_encoder_2]):
917
+ # Convert images to latent space
918
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()
919
+ latents = latents * vae.config.scaling_factor
920
+
921
+ # Sample noise that we'll add to the latents
922
+ noise = torch.randn_like(latents)
923
+ bsz = latents.shape[0]
924
+ # Sample a random timestep for each image
925
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
926
+ timesteps = timesteps.long()
927
+
928
+ # Add noise to the latents according to the noise magnitude at each timestep
929
+ # (this is the forward diffusion process)
930
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
931
+
932
+ # Get the text embedding for conditioning
933
+ encoder_hidden_states_1 = (
934
+ text_encoder_1(batch["input_ids_1"], output_hidden_states=True)
935
+ .hidden_states[-2]
936
+ .to(dtype=weight_dtype)
937
+ )
938
+ encoder_output_2 = text_encoder_2(batch["input_ids_2"], output_hidden_states=True)
939
+ encoder_hidden_states_2 = encoder_output_2.hidden_states[-2].to(dtype=weight_dtype)
940
+ original_size = [
941
+ (batch["original_size"][0][i].item(), batch["original_size"][1][i].item())
942
+ for i in range(args.train_batch_size)
943
+ ]
944
+ crop_top_left = [
945
+ (batch["crop_top_left"][0][i].item(), batch["crop_top_left"][1][i].item())
946
+ for i in range(args.train_batch_size)
947
+ ]
948
+ target_size = (args.resolution, args.resolution)
949
+ add_time_ids = torch.cat(
950
+ [
951
+ torch.tensor(original_size[i] + crop_top_left[i] + target_size)
952
+ for i in range(args.train_batch_size)
953
+ ]
954
+ ).to(accelerator.device, dtype=weight_dtype)
955
+ added_cond_kwargs = {"text_embeds": encoder_output_2[0], "time_ids": add_time_ids}
956
+ encoder_hidden_states = torch.cat([encoder_hidden_states_1, encoder_hidden_states_2], dim=-1)
957
+
958
+ # Predict the noise residual
959
+ model_pred = unet(
960
+ noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
961
+ ).sample
962
+
963
+ # Get the target for loss depending on the prediction type
964
+ if noise_scheduler.config.prediction_type == "epsilon":
965
+ target = noise
966
+ elif noise_scheduler.config.prediction_type == "v_prediction":
967
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
968
+ else:
969
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
970
+
971
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
972
+
973
+ accelerator.backward(loss)
974
+
975
+ optimizer.step()
976
+ lr_scheduler.step()
977
+ optimizer.zero_grad()
978
+
979
+ # Let's make sure we don't update any embedding weights besides the newly added token
980
+ index_no_updates = torch.ones((len(tokenizer_1),), dtype=torch.bool)
981
+ index_no_updates[min(placeholder_token_ids) : max(placeholder_token_ids) + 1] = False
982
+ index_no_updates_2 = torch.ones((len(tokenizer_2),), dtype=torch.bool)
983
+ index_no_updates_2[min(placeholder_token_ids_2) : max(placeholder_token_ids_2) + 1] = False
984
+
985
+ with torch.no_grad():
986
+ accelerator.unwrap_model(text_encoder_1).get_input_embeddings().weight[index_no_updates] = (
987
+ orig_embeds_params[index_no_updates]
988
+ )
989
+ accelerator.unwrap_model(text_encoder_2).get_input_embeddings().weight[index_no_updates_2] = (
990
+ orig_embeds_params_2[index_no_updates_2]
991
+ )
992
+
993
+ # Checks if the accelerator has performed an optimization step behind the scenes
994
+ if accelerator.sync_gradients:
995
+ images = []
996
+ progress_bar.update(1)
997
+ global_step += 1
998
+ if global_step % args.save_steps == 0:
999
+ weight_name = f"learned_embeds-steps-{global_step}.safetensors"
1000
+ save_path = os.path.join(args.output_dir, weight_name)
1001
+ save_progress(
1002
+ text_encoder_1,
1003
+ placeholder_token_ids,
1004
+ accelerator,
1005
+ args,
1006
+ save_path,
1007
+ safe_serialization=True,
1008
+ )
1009
+ weight_name = f"learned_embeds_2-steps-{global_step}.safetensors"
1010
+ save_path = os.path.join(args.output_dir, weight_name)
1011
+ save_progress(
1012
+ text_encoder_2,
1013
+ placeholder_token_ids_2,
1014
+ accelerator,
1015
+ args,
1016
+ save_path,
1017
+ safe_serialization=True,
1018
+ )
1019
+
1020
+ if accelerator.is_main_process:
1021
+ if global_step % args.checkpointing_steps == 0:
1022
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1023
+ if args.checkpoints_total_limit is not None:
1024
+ checkpoints = os.listdir(args.output_dir)
1025
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1026
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1027
+
1028
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1029
+ if len(checkpoints) >= args.checkpoints_total_limit:
1030
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1031
+ removing_checkpoints = checkpoints[0:num_to_remove]
1032
+
1033
+ logger.info(
1034
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1035
+ )
1036
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1037
+
1038
+ for removing_checkpoint in removing_checkpoints:
1039
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1040
+ shutil.rmtree(removing_checkpoint)
1041
+
1042
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1043
+ accelerator.save_state(save_path)
1044
+ logger.info(f"Saved state to {save_path}")
1045
+
1046
+ if args.validation_prompt is not None and global_step % args.validation_steps == 0:
1047
+ images = log_validation(
1048
+ text_encoder_1,
1049
+ text_encoder_2,
1050
+ tokenizer_1,
1051
+ tokenizer_2,
1052
+ unet,
1053
+ vae,
1054
+ args,
1055
+ accelerator,
1056
+ weight_dtype,
1057
+ epoch,
1058
+ )
1059
+
1060
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1061
+ progress_bar.set_postfix(**logs)
1062
+ accelerator.log(logs, step=global_step)
1063
+
1064
+ if global_step >= args.max_train_steps:
1065
+ break
1066
+ # Create the pipeline using the trained modules and save it.
1067
+ accelerator.wait_for_everyone()
1068
+ if accelerator.is_main_process:
1069
+ if args.validation_prompt:
1070
+ images = log_validation(
1071
+ text_encoder_1,
1072
+ text_encoder_2,
1073
+ tokenizer_1,
1074
+ tokenizer_2,
1075
+ unet,
1076
+ vae,
1077
+ args,
1078
+ accelerator,
1079
+ weight_dtype,
1080
+ epoch,
1081
+ is_final_validation=True,
1082
+ )
1083
+
1084
+ if args.push_to_hub and not args.save_as_full_pipeline:
1085
+ logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
1086
+ save_full_model = True
1087
+ else:
1088
+ save_full_model = args.save_as_full_pipeline
1089
+ if save_full_model:
1090
+ pipeline = DiffusionPipeline.from_pretrained(
1091
+ args.pretrained_model_name_or_path,
1092
+ text_encoder=accelerator.unwrap_model(text_encoder_1),
1093
+ text_encoder_2=accelerator.unwrap_model(text_encoder_2),
1094
+ vae=vae,
1095
+ unet=unet,
1096
+ tokenizer=tokenizer_1,
1097
+ tokenizer_2=tokenizer_2,
1098
+ )
1099
+ pipeline.save_pretrained(args.output_dir)
1100
+ # Save the newly trained embeddings
1101
+ weight_name = "learned_embeds.safetensors"
1102
+ save_path = os.path.join(args.output_dir, weight_name)
1103
+ save_progress(
1104
+ text_encoder_1,
1105
+ placeholder_token_ids,
1106
+ accelerator,
1107
+ args,
1108
+ save_path,
1109
+ safe_serialization=True,
1110
+ )
1111
+ weight_name = "learned_embeds_2.safetensors"
1112
+ save_path = os.path.join(args.output_dir, weight_name)
1113
+ save_progress(
1114
+ text_encoder_2,
1115
+ placeholder_token_ids_2,
1116
+ accelerator,
1117
+ args,
1118
+ save_path,
1119
+ safe_serialization=True,
1120
+ )
1121
+
1122
+ if args.push_to_hub:
1123
+ save_model_card(
1124
+ repo_id,
1125
+ images=images,
1126
+ base_model=args.pretrained_model_name_or_path,
1127
+ repo_folder=args.output_dir,
1128
+ )
1129
+ upload_folder(
1130
+ repo_id=repo_id,
1131
+ folder_path=args.output_dir,
1132
+ commit_message="End of training",
1133
+ ignore_patterns=["step_*", "epoch_*"],
1134
+ )
1135
+
1136
+ accelerator.end_training()
1137
+
1138
+
1139
+ if __name__ == "__main__":
1140
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/README.md ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Training an unconditional diffusion model
2
+
3
+ Creating a training image set is [described in a different document](https://huggingface.co/docs/datasets/image_process#image-datasets).
4
+
5
+ ### Installing the dependencies
6
+
7
+ Before running the scripts, make sure to install the library's training dependencies:
8
+
9
+ **Important**
10
+
11
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
12
+ ```bash
13
+ git clone https://github.com/huggingface/diffusers
14
+ cd diffusers
15
+ pip install .
16
+ ```
17
+
18
+ Then cd in the example folder and run
19
+ ```bash
20
+ pip install -r requirements.txt
21
+ ```
22
+
23
+
24
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
25
+
26
+ ```bash
27
+ accelerate config
28
+ ```
29
+
30
+ ### Unconditional Flowers
31
+
32
+ The command to train a DDPM UNet model on the Oxford Flowers dataset:
33
+
34
+ ```bash
35
+ accelerate launch train_unconditional.py \
36
+ --dataset_name="huggan/flowers-102-categories" \
37
+ --resolution=64 --center_crop --random_flip \
38
+ --output_dir="ddpm-ema-flowers-64" \
39
+ --train_batch_size=16 \
40
+ --num_epochs=100 \
41
+ --gradient_accumulation_steps=1 \
42
+ --use_ema \
43
+ --learning_rate=1e-4 \
44
+ --lr_warmup_steps=500 \
45
+ --mixed_precision=no \
46
+ --push_to_hub
47
+ ```
48
+ An example trained model: https://huggingface.co/anton-l/ddpm-ema-flowers-64
49
+
50
+ A full training run takes 2 hours on 4xV100 GPUs.
51
+
52
+ <img src="https://user-images.githubusercontent.com/26864830/180248660-a0b143d0-b89a-42c5-8656-2ebf6ece7e52.png" width="700" />
53
+
54
+
55
+ ### Unconditional Pokemon
56
+
57
+ The command to train a DDPM UNet model on the Pokemon dataset:
58
+
59
+ ```bash
60
+ accelerate launch train_unconditional.py \
61
+ --dataset_name="huggan/pokemon" \
62
+ --resolution=64 --center_crop --random_flip \
63
+ --output_dir="ddpm-ema-pokemon-64" \
64
+ --train_batch_size=16 \
65
+ --num_epochs=100 \
66
+ --gradient_accumulation_steps=1 \
67
+ --use_ema \
68
+ --learning_rate=1e-4 \
69
+ --lr_warmup_steps=500 \
70
+ --mixed_precision=no \
71
+ --push_to_hub
72
+ ```
73
+ An example trained model: https://huggingface.co/anton-l/ddpm-ema-pokemon-64
74
+
75
+ A full training run takes 2 hours on 4xV100 GPUs.
76
+
77
+ <img src="https://user-images.githubusercontent.com/26864830/180248200-928953b4-db38-48db-b0c6-8b740fe6786f.png" width="700" />
78
+
79
+ ### Training with multiple GPUs
80
+
81
+ `accelerate` allows for seamless multi-GPU training. Follow the instructions [here](https://huggingface.co/docs/accelerate/basic_tutorials/launch)
82
+ for running distributed training with `accelerate`. Here is an example command:
83
+
84
+ ```bash
85
+ accelerate launch --mixed_precision="fp16" --multi_gpu train_unconditional.py \
86
+ --dataset_name="huggan/pokemon" \
87
+ --resolution=64 --center_crop --random_flip \
88
+ --output_dir="ddpm-ema-pokemon-64" \
89
+ --train_batch_size=16 \
90
+ --num_epochs=100 \
91
+ --gradient_accumulation_steps=1 \
92
+ --use_ema \
93
+ --learning_rate=1e-4 \
94
+ --lr_warmup_steps=500 \
95
+ --mixed_precision="fp16" \
96
+ --logger="wandb"
97
+ ```
98
+
99
+ To be able to use Weights and Biases (`wandb`) as a logger you need to install the library: `pip install wandb`.
100
+
101
+ ### Using your own data
102
+
103
+ To use your own dataset, there are 2 ways:
104
+ - you can either provide your own folder as `--train_data_dir`
105
+ - or you can upload your dataset to the hub (possibly as a private repo, if you prefer so), and simply pass the `--dataset_name` argument.
106
+
107
+ If your dataset contains 16 or 32-bit channels (for example, medical TIFFs), add the `--preserve_input_precision` flag so the preprocessing keeps the original precision while still training a 3-channel model. Precision still depends on the decoder: Pillow keeps 16-bit grayscale and float inputs, but many 16-bit RGB files are decoded as 8-bit RGB, and the flag cannot recover precision lost at load time.
108
+
109
+ Below, we explain both in more detail.
110
+
111
+ #### Provide the dataset as a folder
112
+
113
+ If you provide your own folders with images, the script expects the following directory structure:
114
+
115
+ ```bash
116
+ data_dir/xxx.png
117
+ data_dir/xxy.png
118
+ data_dir/[...]/xxz.png
119
+ ```
120
+
121
+ In other words, the script will take care of gathering all images inside the folder. You can then run the script like this:
122
+
123
+ ```bash
124
+ accelerate launch train_unconditional.py \
125
+ --train_data_dir <path-to-train-directory> \
126
+ <other-arguments>
127
+ ```
128
+
129
+ Internally, the script will use the [`ImageFolder`](https://huggingface.co/docs/datasets/v2.0.0/en/image_process#imagefolder) feature which will automatically turn the folders into 🤗 Dataset objects.
130
+
131
+ #### Upload your data to the hub, as a (possibly private) repo
132
+
133
+ It's very easy (and convenient) to upload your image dataset to the hub using the [`ImageFolder`](https://huggingface.co/docs/datasets/v2.0.0/en/image_process#imagefolder) feature available in 🤗 Datasets. Simply do the following:
134
+
135
+ ```python
136
+ from datasets import load_dataset
137
+
138
+ # example 1: local folder
139
+ dataset = load_dataset("imagefolder", data_dir="path_to_your_folder")
140
+
141
+ # example 2: local files (supported formats are tar, gzip, zip, xz, rar, zstd)
142
+ dataset = load_dataset("imagefolder", data_files="path_to_zip_file")
143
+
144
+ # example 3: remote files (supported formats are tar, gzip, zip, xz, rar, zstd)
145
+ dataset = load_dataset("imagefolder", data_files="https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip")
146
+
147
+ # example 4: providing several splits
148
+ dataset = load_dataset("imagefolder", data_files={"train": ["path/to/file1", "path/to/file2"], "test": ["path/to/file3", "path/to/file4"]})
149
+ ```
150
+
151
+ `ImageFolder` will create an `image` column containing the PIL-encoded images.
152
+
153
+ Next, push it to the hub!
154
+
155
+ ```python
156
+ # assuming you have ran the hf auth login command in a terminal
157
+ dataset.push_to_hub("name_of_your_dataset")
158
+
159
+ # if you want to push to a private repo, simply pass private=True:
160
+ dataset.push_to_hub("name_of_your_dataset", private=True)
161
+ ```
162
+
163
+ and that's it! You can now train your model by simply setting the `--dataset_name` argument to the name of your dataset on the hub.
164
+
165
+ More on this can also be found in [this blog post](https://huggingface.co/blog/image-search-datasets).
tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ datasets
tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/test_unconditional.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+
21
+
22
+ sys.path.append("..")
23
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
24
+
25
+
26
+ logging.basicConfig(level=logging.DEBUG)
27
+
28
+ logger = logging.getLogger()
29
+ stream_handler = logging.StreamHandler(sys.stdout)
30
+ logger.addHandler(stream_handler)
31
+
32
+
33
+ class Unconditional(ExamplesTestsAccelerate):
34
+ def test_train_unconditional(self):
35
+ with tempfile.TemporaryDirectory() as tmpdir:
36
+ test_args = f"""
37
+ examples/unconditional_image_generation/train_unconditional.py
38
+ --dataset_name hf-internal-testing/dummy_image_class_data
39
+ --model_config_name_or_path diffusers/ddpm_dummy
40
+ --resolution 64
41
+ --output_dir {tmpdir}
42
+ --train_batch_size 2
43
+ --num_epochs 1
44
+ --gradient_accumulation_steps 1
45
+ --ddpm_num_inference_steps 2
46
+ --learning_rate 1e-3
47
+ --lr_warmup_steps 5
48
+ """.split()
49
+
50
+ run_command(self._launch_args + test_args, return_stdout=True)
51
+ # save_pretrained smoke test
52
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "unet", "diffusion_pytorch_model.safetensors")))
53
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "scheduler", "scheduler_config.json")))
54
+
55
+ def test_unconditional_checkpointing_checkpoints_total_limit(self):
56
+ with tempfile.TemporaryDirectory() as tmpdir:
57
+ initial_run_args = f"""
58
+ examples/unconditional_image_generation/train_unconditional.py
59
+ --dataset_name hf-internal-testing/dummy_image_class_data
60
+ --model_config_name_or_path diffusers/ddpm_dummy
61
+ --resolution 64
62
+ --output_dir {tmpdir}
63
+ --train_batch_size 1
64
+ --num_epochs 1
65
+ --gradient_accumulation_steps 1
66
+ --ddpm_num_inference_steps 2
67
+ --learning_rate 1e-3
68
+ --lr_warmup_steps 5
69
+ --checkpointing_steps=2
70
+ --checkpoints_total_limit=2
71
+ """.split()
72
+
73
+ run_command(self._launch_args + initial_run_args)
74
+
75
+ # check checkpoint directories exist
76
+ self.assertEqual(
77
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
78
+ # checkpoint-2 should have been deleted
79
+ {"checkpoint-4", "checkpoint-6"},
80
+ )
81
+
82
+ def test_unconditional_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
83
+ with tempfile.TemporaryDirectory() as tmpdir:
84
+ initial_run_args = f"""
85
+ examples/unconditional_image_generation/train_unconditional.py
86
+ --dataset_name hf-internal-testing/dummy_image_class_data
87
+ --model_config_name_or_path diffusers/ddpm_dummy
88
+ --resolution 64
89
+ --output_dir {tmpdir}
90
+ --train_batch_size 1
91
+ --num_epochs 1
92
+ --gradient_accumulation_steps 1
93
+ --ddpm_num_inference_steps 1
94
+ --learning_rate 1e-3
95
+ --lr_warmup_steps 5
96
+ --checkpointing_steps=2
97
+ """.split()
98
+
99
+ run_command(self._launch_args + initial_run_args)
100
+
101
+ # check checkpoint directories exist
102
+ self.assertEqual(
103
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
104
+ {"checkpoint-2", "checkpoint-4", "checkpoint-6"},
105
+ )
106
+
107
+ resume_run_args = f"""
108
+ examples/unconditional_image_generation/train_unconditional.py
109
+ --dataset_name hf-internal-testing/dummy_image_class_data
110
+ --model_config_name_or_path diffusers/ddpm_dummy
111
+ --resolution 64
112
+ --output_dir {tmpdir}
113
+ --train_batch_size 1
114
+ --num_epochs 2
115
+ --gradient_accumulation_steps 1
116
+ --ddpm_num_inference_steps 1
117
+ --learning_rate 1e-3
118
+ --lr_warmup_steps 5
119
+ --resume_from_checkpoint=checkpoint-6
120
+ --checkpointing_steps=2
121
+ --checkpoints_total_limit=2
122
+ """.split()
123
+
124
+ run_command(self._launch_args + resume_run_args)
125
+
126
+ # check checkpoint directories exist
127
+ self.assertEqual(
128
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
129
+ {"checkpoint-10", "checkpoint-12"},
130
+ )
tasks/tasksmith-ee553a5e62c1/environment/source/examples/unconditional_image_generation/train_unconditional.py ADDED
@@ -0,0 +1,749 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+ import logging
4
+ import math
5
+ import os
6
+ import shutil
7
+ from datetime import timedelta
8
+ from pathlib import Path
9
+
10
+ import accelerate
11
+ import datasets
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from accelerate import Accelerator, InitProcessGroupKwargs
15
+ from accelerate.logging import get_logger
16
+ from accelerate.utils import ProjectConfiguration
17
+ from datasets import load_dataset
18
+ from huggingface_hub import create_repo, upload_folder
19
+ from packaging import version
20
+ from torchvision import transforms
21
+ from tqdm.auto import tqdm
22
+
23
+ import diffusers
24
+ from diffusers import DDPMPipeline, DDPMScheduler, UNet2DModel
25
+ from diffusers.optimization import get_scheduler
26
+ from diffusers.training_utils import EMAModel
27
+ from diffusers.utils import check_min_version, is_accelerate_version, is_tensorboard_available, is_wandb_available
28
+ from diffusers.utils.import_utils import is_xformers_available
29
+
30
+
31
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
32
+ check_min_version("0.39.0.dev0")
33
+
34
+ logger = get_logger(__name__, log_level="INFO")
35
+
36
+
37
+ def _extract_into_tensor(arr, timesteps, broadcast_shape):
38
+ """
39
+ Extract values from a 1-D numpy array for a batch of indices.
40
+
41
+ :param arr: the 1-D numpy array.
42
+ :param timesteps: a tensor of indices into the array to extract.
43
+ :param broadcast_shape: a larger shape of K dimensions with the batch
44
+ dimension equal to the length of timesteps.
45
+ :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
46
+ """
47
+ if not isinstance(arr, torch.Tensor):
48
+ arr = torch.from_numpy(arr)
49
+ res = arr[timesteps].float().to(timesteps.device)
50
+ while len(res.shape) < len(broadcast_shape):
51
+ res = res[..., None]
52
+ return res.expand(broadcast_shape)
53
+
54
+
55
+ def _ensure_three_channels(tensor: torch.Tensor) -> torch.Tensor:
56
+ """
57
+ Ensure the tensor has exactly three channels (C, H, W) by repeating or truncating channels when needed.
58
+ """
59
+ if tensor.ndim == 2:
60
+ tensor = tensor.unsqueeze(0)
61
+ channels = tensor.shape[0]
62
+ if channels == 3:
63
+ return tensor
64
+ if channels == 1:
65
+ return tensor.repeat(3, 1, 1)
66
+ if channels == 2:
67
+ return torch.cat([tensor, tensor[:1]], dim=0)
68
+ if channels > 3:
69
+ return tensor[:3]
70
+ raise ValueError(f"Unsupported number of channels: {channels}")
71
+
72
+
73
+ def parse_args():
74
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
75
+ parser.add_argument(
76
+ "--dataset_name",
77
+ type=str,
78
+ default=None,
79
+ help=(
80
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
81
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
82
+ " or to a folder containing files that HF Datasets can understand."
83
+ ),
84
+ )
85
+ parser.add_argument(
86
+ "--dataset_config_name",
87
+ type=str,
88
+ default=None,
89
+ help="The config of the Dataset, leave as None if there's only one config.",
90
+ )
91
+ parser.add_argument(
92
+ "--model_config_name_or_path",
93
+ type=str,
94
+ default=None,
95
+ help="The config of the UNet model to train, leave as None to use standard DDPM configuration.",
96
+ )
97
+ parser.add_argument(
98
+ "--train_data_dir",
99
+ type=str,
100
+ default=None,
101
+ help=(
102
+ "A folder containing the training data. Folder contents must follow the structure described in"
103
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
104
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
105
+ ),
106
+ )
107
+ parser.add_argument(
108
+ "--output_dir",
109
+ type=str,
110
+ default="ddpm-model-64",
111
+ help="The output directory where the model predictions and checkpoints will be written.",
112
+ )
113
+ parser.add_argument("--overwrite_output_dir", action="store_true")
114
+ parser.add_argument(
115
+ "--cache_dir",
116
+ type=str,
117
+ default=None,
118
+ help="The directory where the downloaded models and datasets will be stored.",
119
+ )
120
+ parser.add_argument(
121
+ "--resolution",
122
+ type=int,
123
+ default=64,
124
+ help=(
125
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
126
+ " resolution"
127
+ ),
128
+ )
129
+ parser.add_argument(
130
+ "--center_crop",
131
+ default=False,
132
+ action="store_true",
133
+ help=(
134
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
135
+ " cropped. The images will be resized to the resolution first before cropping."
136
+ ),
137
+ )
138
+ parser.add_argument(
139
+ "--random_flip",
140
+ default=False,
141
+ action="store_true",
142
+ help="whether to randomly flip images horizontally",
143
+ )
144
+ parser.add_argument(
145
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
146
+ )
147
+ parser.add_argument(
148
+ "--eval_batch_size", type=int, default=16, help="The number of images to generate for evaluation."
149
+ )
150
+ parser.add_argument(
151
+ "--dataloader_num_workers",
152
+ type=int,
153
+ default=0,
154
+ help=(
155
+ "The number of subprocesses to use for data loading. 0 means that the data will be loaded in the main"
156
+ " process."
157
+ ),
158
+ )
159
+ parser.add_argument("--num_epochs", type=int, default=100)
160
+ parser.add_argument("--save_images_epochs", type=int, default=10, help="How often to save images during training.")
161
+ parser.add_argument(
162
+ "--save_model_epochs", type=int, default=10, help="How often to save the model during training."
163
+ )
164
+ parser.add_argument(
165
+ "--gradient_accumulation_steps",
166
+ type=int,
167
+ default=1,
168
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
169
+ )
170
+ parser.add_argument(
171
+ "--learning_rate",
172
+ type=float,
173
+ default=1e-4,
174
+ help="Initial learning rate (after the potential warmup period) to use.",
175
+ )
176
+ parser.add_argument(
177
+ "--lr_scheduler",
178
+ type=str,
179
+ default="cosine",
180
+ help=(
181
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
182
+ ' "constant", "constant_with_warmup"]'
183
+ ),
184
+ )
185
+ parser.add_argument(
186
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
187
+ )
188
+ parser.add_argument("--adam_beta1", type=float, default=0.95, help="The beta1 parameter for the Adam optimizer.")
189
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
190
+ parser.add_argument(
191
+ "--adam_weight_decay", type=float, default=1e-6, help="Weight decay magnitude for the Adam optimizer."
192
+ )
193
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer.")
194
+ parser.add_argument(
195
+ "--use_ema",
196
+ action="store_true",
197
+ help="Whether to use Exponential Moving Average for the final model weights.",
198
+ )
199
+ parser.add_argument("--ema_inv_gamma", type=float, default=1.0, help="The inverse gamma value for the EMA decay.")
200
+ parser.add_argument("--ema_power", type=float, default=3 / 4, help="The power value for the EMA decay.")
201
+ parser.add_argument("--ema_max_decay", type=float, default=0.9999, help="The maximum decay magnitude for EMA.")
202
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
203
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
204
+ parser.add_argument(
205
+ "--hub_model_id",
206
+ type=str,
207
+ default=None,
208
+ help="The name of the repository to keep in sync with the local `output_dir`.",
209
+ )
210
+ parser.add_argument(
211
+ "--hub_private_repo", action="store_true", help="Whether or not to create a private repository."
212
+ )
213
+ parser.add_argument(
214
+ "--logger",
215
+ type=str,
216
+ default="tensorboard",
217
+ choices=["tensorboard", "wandb"],
218
+ help=(
219
+ "Whether to use [tensorboard](https://www.tensorflow.org/tensorboard) or [wandb](https://www.wandb.ai)"
220
+ " for experiment tracking and logging of model metrics and model checkpoints"
221
+ ),
222
+ )
223
+ parser.add_argument(
224
+ "--logging_dir",
225
+ type=str,
226
+ default="logs",
227
+ help=(
228
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
229
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
230
+ ),
231
+ )
232
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
233
+ parser.add_argument(
234
+ "--mixed_precision",
235
+ type=str,
236
+ default="no",
237
+ choices=["no", "fp16", "bf16"],
238
+ help=(
239
+ "Whether to use mixed precision. Choose"
240
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
241
+ "and an Nvidia Ampere GPU."
242
+ ),
243
+ )
244
+ parser.add_argument(
245
+ "--prediction_type",
246
+ type=str,
247
+ default="epsilon",
248
+ choices=["epsilon", "sample"],
249
+ help="Whether the model should predict the 'epsilon'/noise error or directly the reconstructed image 'x0'.",
250
+ )
251
+ parser.add_argument("--ddpm_num_steps", type=int, default=1000)
252
+ parser.add_argument("--ddpm_num_inference_steps", type=int, default=1000)
253
+ parser.add_argument("--ddpm_beta_schedule", type=str, default="linear")
254
+ parser.add_argument(
255
+ "--checkpointing_steps",
256
+ type=int,
257
+ default=500,
258
+ help=(
259
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
260
+ " training using `--resume_from_checkpoint`."
261
+ ),
262
+ )
263
+ parser.add_argument(
264
+ "--checkpoints_total_limit",
265
+ type=int,
266
+ default=None,
267
+ help=("Max number of checkpoints to store."),
268
+ )
269
+ parser.add_argument(
270
+ "--resume_from_checkpoint",
271
+ type=str,
272
+ default=None,
273
+ help=(
274
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
275
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
276
+ ),
277
+ )
278
+ parser.add_argument(
279
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
280
+ )
281
+ parser.add_argument(
282
+ "--preserve_input_precision",
283
+ action="store_true",
284
+ help="Preserve 16/32-bit image precision by avoiding 8-bit RGB conversion while still producing 3-channel tensors.",
285
+ )
286
+
287
+ args = parser.parse_args()
288
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
289
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
290
+ args.local_rank = env_local_rank
291
+
292
+ if args.dataset_name is None and args.train_data_dir is None:
293
+ raise ValueError("You must specify either a dataset name from the hub or a train data directory.")
294
+
295
+ return args
296
+
297
+
298
+ def main(args):
299
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
300
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
301
+
302
+ kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=7200)) # a big number for high resolution or big dataset
303
+ accelerator = Accelerator(
304
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
305
+ mixed_precision=args.mixed_precision,
306
+ log_with=args.logger,
307
+ project_config=accelerator_project_config,
308
+ kwargs_handlers=[kwargs],
309
+ )
310
+
311
+ if args.logger == "tensorboard":
312
+ if not is_tensorboard_available():
313
+ raise ImportError("Make sure to install tensorboard if you want to use it for logging during training.")
314
+
315
+ elif args.logger == "wandb":
316
+ if not is_wandb_available():
317
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
318
+ import wandb
319
+
320
+ # `accelerate` 0.16.0 will have better support for customized saving
321
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
322
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
323
+ def save_model_hook(models, weights, output_dir):
324
+ if accelerator.is_main_process:
325
+ if args.use_ema:
326
+ ema_model.save_pretrained(os.path.join(output_dir, "unet_ema"))
327
+
328
+ for i, model in enumerate(models):
329
+ model.save_pretrained(os.path.join(output_dir, "unet"))
330
+
331
+ # make sure to pop weight so that corresponding model is not saved again
332
+ weights.pop()
333
+
334
+ def load_model_hook(models, input_dir):
335
+ if args.use_ema:
336
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DModel)
337
+ ema_model.load_state_dict(load_model.state_dict())
338
+ ema_model.to(accelerator.device)
339
+ del load_model
340
+
341
+ for i in range(len(models)):
342
+ # pop models so that they are not loaded again
343
+ model = models.pop()
344
+
345
+ # load diffusers style into model
346
+ load_model = UNet2DModel.from_pretrained(input_dir, subfolder="unet")
347
+ model.register_to_config(**load_model.config)
348
+
349
+ model.load_state_dict(load_model.state_dict())
350
+ del load_model
351
+
352
+ accelerator.register_save_state_pre_hook(save_model_hook)
353
+ accelerator.register_load_state_pre_hook(load_model_hook)
354
+
355
+ # Make one log on every process with the configuration for debugging.
356
+ logging.basicConfig(
357
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
358
+ datefmt="%m/%d/%Y %H:%M:%S",
359
+ level=logging.INFO,
360
+ )
361
+ logger.info(accelerator.state, main_process_only=False)
362
+ if accelerator.is_local_main_process:
363
+ datasets.utils.logging.set_verbosity_warning()
364
+ diffusers.utils.logging.set_verbosity_info()
365
+ else:
366
+ datasets.utils.logging.set_verbosity_error()
367
+ diffusers.utils.logging.set_verbosity_error()
368
+
369
+ # Handle the repository creation
370
+ if accelerator.is_main_process:
371
+ if args.output_dir is not None:
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+
374
+ if args.push_to_hub:
375
+ repo_id = create_repo(
376
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
377
+ ).repo_id
378
+
379
+ # Initialize the model
380
+ if args.model_config_name_or_path is None:
381
+ model = UNet2DModel(
382
+ sample_size=args.resolution,
383
+ in_channels=3,
384
+ out_channels=3,
385
+ layers_per_block=2,
386
+ block_out_channels=(128, 128, 256, 256, 512, 512),
387
+ down_block_types=(
388
+ "DownBlock2D",
389
+ "DownBlock2D",
390
+ "DownBlock2D",
391
+ "DownBlock2D",
392
+ "AttnDownBlock2D",
393
+ "DownBlock2D",
394
+ ),
395
+ up_block_types=(
396
+ "UpBlock2D",
397
+ "AttnUpBlock2D",
398
+ "UpBlock2D",
399
+ "UpBlock2D",
400
+ "UpBlock2D",
401
+ "UpBlock2D",
402
+ ),
403
+ )
404
+ else:
405
+ config = UNet2DModel.load_config(args.model_config_name_or_path)
406
+ model = UNet2DModel.from_config(config)
407
+
408
+ # Create EMA for the model.
409
+ if args.use_ema:
410
+ ema_model = EMAModel(
411
+ model.parameters(),
412
+ decay=args.ema_max_decay,
413
+ use_ema_warmup=True,
414
+ inv_gamma=args.ema_inv_gamma,
415
+ power=args.ema_power,
416
+ model_cls=UNet2DModel,
417
+ model_config=model.config,
418
+ )
419
+
420
+ weight_dtype = torch.float32
421
+ if accelerator.mixed_precision == "fp16":
422
+ weight_dtype = torch.float16
423
+ args.mixed_precision = accelerator.mixed_precision
424
+ elif accelerator.mixed_precision == "bf16":
425
+ weight_dtype = torch.bfloat16
426
+ args.mixed_precision = accelerator.mixed_precision
427
+
428
+ if args.enable_xformers_memory_efficient_attention:
429
+ if is_xformers_available():
430
+ import xformers
431
+
432
+ xformers_version = version.parse(xformers.__version__)
433
+ if xformers_version == version.parse("0.0.16"):
434
+ logger.warning(
435
+ "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."
436
+ )
437
+ model.enable_xformers_memory_efficient_attention()
438
+ else:
439
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
440
+
441
+ # Initialize the scheduler
442
+ accepts_prediction_type = "prediction_type" in set(inspect.signature(DDPMScheduler.__init__).parameters.keys())
443
+ if accepts_prediction_type:
444
+ noise_scheduler = DDPMScheduler(
445
+ num_train_timesteps=args.ddpm_num_steps,
446
+ beta_schedule=args.ddpm_beta_schedule,
447
+ prediction_type=args.prediction_type,
448
+ )
449
+ else:
450
+ noise_scheduler = DDPMScheduler(num_train_timesteps=args.ddpm_num_steps, beta_schedule=args.ddpm_beta_schedule)
451
+
452
+ # Initialize the optimizer
453
+ optimizer = torch.optim.AdamW(
454
+ model.parameters(),
455
+ lr=args.learning_rate,
456
+ betas=(args.adam_beta1, args.adam_beta2),
457
+ weight_decay=args.adam_weight_decay,
458
+ eps=args.adam_epsilon,
459
+ )
460
+
461
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
462
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
463
+
464
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
465
+ # download the dataset.
466
+ if args.dataset_name is not None:
467
+ dataset = load_dataset(
468
+ args.dataset_name,
469
+ args.dataset_config_name,
470
+ cache_dir=args.cache_dir,
471
+ split="train",
472
+ )
473
+ else:
474
+ dataset = load_dataset("imagefolder", data_dir=args.train_data_dir, cache_dir=args.cache_dir, split="train")
475
+ # See more about loading custom images at
476
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
477
+
478
+ # Preprocessing the datasets and DataLoaders creation.
479
+ spatial_augmentations = [
480
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
481
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
482
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
483
+ ]
484
+
485
+ augmentations = transforms.Compose(
486
+ spatial_augmentations
487
+ + [
488
+ transforms.ToTensor(),
489
+ transforms.Normalize([0.5], [0.5]),
490
+ ]
491
+ )
492
+
493
+ precision_augmentations = transforms.Compose(
494
+ [
495
+ transforms.PILToTensor(),
496
+ transforms.Lambda(_ensure_three_channels),
497
+ transforms.ConvertImageDtype(torch.float32),
498
+ ]
499
+ + spatial_augmentations
500
+ + [transforms.Normalize([0.5], [0.5])]
501
+ )
502
+
503
+ def transform_images(examples):
504
+ processed = []
505
+ for image in examples["image"]:
506
+ if not args.preserve_input_precision:
507
+ processed.append(augmentations(image.convert("RGB")))
508
+ else:
509
+ precise_image = image
510
+ if precise_image.mode == "P":
511
+ precise_image = precise_image.convert("RGB")
512
+ processed.append(precision_augmentations(precise_image))
513
+ return {"input": processed}
514
+
515
+ logger.info(f"Dataset size: {len(dataset)}")
516
+
517
+ dataset.set_transform(transform_images)
518
+ train_dataloader = torch.utils.data.DataLoader(
519
+ dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
520
+ )
521
+
522
+ # Initialize the learning rate scheduler
523
+ lr_scheduler = get_scheduler(
524
+ args.lr_scheduler,
525
+ optimizer=optimizer,
526
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
527
+ num_training_steps=(len(train_dataloader) * args.num_epochs),
528
+ )
529
+
530
+ # Prepare everything with our `accelerator`.
531
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
532
+ model, optimizer, train_dataloader, lr_scheduler
533
+ )
534
+
535
+ if args.use_ema:
536
+ ema_model.to(accelerator.device)
537
+
538
+ # We need to initialize the trackers we use, and also store our configuration.
539
+ # The trackers initializes automatically on the main process.
540
+ if accelerator.is_main_process:
541
+ run = os.path.split(__file__)[-1].split(".")[0]
542
+ accelerator.init_trackers(run)
543
+
544
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
545
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
546
+ max_train_steps = args.num_epochs * num_update_steps_per_epoch
547
+
548
+ logger.info("***** Running training *****")
549
+ logger.info(f" Num examples = {len(dataset)}")
550
+ logger.info(f" Num Epochs = {args.num_epochs}")
551
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
552
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
553
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
554
+ logger.info(f" Total optimization steps = {max_train_steps}")
555
+
556
+ global_step = 0
557
+ first_epoch = 0
558
+
559
+ # Potentially load in the weights and states from a previous save
560
+ if args.resume_from_checkpoint:
561
+ if args.resume_from_checkpoint != "latest":
562
+ path = os.path.basename(args.resume_from_checkpoint)
563
+ else:
564
+ # Get the most recent checkpoint
565
+ dirs = os.listdir(args.output_dir)
566
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
567
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
568
+ path = dirs[-1] if len(dirs) > 0 else None
569
+
570
+ if path is None:
571
+ accelerator.print(
572
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
573
+ )
574
+ args.resume_from_checkpoint = None
575
+ else:
576
+ accelerator.print(f"Resuming from checkpoint {path}")
577
+ accelerator.load_state(os.path.join(args.output_dir, path))
578
+ global_step = int(path.split("-")[1])
579
+
580
+ resume_global_step = global_step * args.gradient_accumulation_steps
581
+ first_epoch = global_step // num_update_steps_per_epoch
582
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
583
+
584
+ # Train!
585
+ for epoch in range(first_epoch, args.num_epochs):
586
+ model.train()
587
+ progress_bar = tqdm(total=num_update_steps_per_epoch, disable=not accelerator.is_local_main_process)
588
+ progress_bar.set_description(f"Epoch {epoch}")
589
+ for step, batch in enumerate(train_dataloader):
590
+ # Skip steps until we reach the resumed step
591
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
592
+ if step % args.gradient_accumulation_steps == 0:
593
+ progress_bar.update(1)
594
+ continue
595
+
596
+ clean_images = batch["input"].to(weight_dtype)
597
+ # Sample noise that we'll add to the images
598
+ noise = torch.randn(clean_images.shape, dtype=weight_dtype, device=clean_images.device)
599
+ bsz = clean_images.shape[0]
600
+ # Sample a random timestep for each image
601
+ timesteps = torch.randint(
602
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=clean_images.device
603
+ ).long()
604
+
605
+ # Add noise to the clean images according to the noise magnitude at each timestep
606
+ # (this is the forward diffusion process)
607
+ noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
608
+
609
+ with accelerator.accumulate(model):
610
+ # Predict the noise residual
611
+ model_output = model(noisy_images, timesteps).sample
612
+
613
+ if args.prediction_type == "epsilon":
614
+ loss = F.mse_loss(model_output.float(), noise.float()) # this could have different weights!
615
+ elif args.prediction_type == "sample":
616
+ alpha_t = _extract_into_tensor(
617
+ noise_scheduler.alphas_cumprod, timesteps, (clean_images.shape[0], 1, 1, 1)
618
+ )
619
+ snr_weights = alpha_t / (1 - alpha_t)
620
+ # use SNR weighting from distillation paper
621
+ loss = snr_weights * F.mse_loss(model_output.float(), clean_images.float(), reduction="none")
622
+ loss = loss.mean()
623
+ else:
624
+ raise ValueError(f"Unsupported prediction type: {args.prediction_type}")
625
+
626
+ accelerator.backward(loss)
627
+
628
+ if accelerator.sync_gradients:
629
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
630
+ optimizer.step()
631
+ lr_scheduler.step()
632
+ optimizer.zero_grad()
633
+
634
+ # Checks if the accelerator has performed an optimization step behind the scenes
635
+ if accelerator.sync_gradients:
636
+ if args.use_ema:
637
+ ema_model.step(model.parameters())
638
+ progress_bar.update(1)
639
+ global_step += 1
640
+
641
+ if accelerator.is_main_process:
642
+ if global_step % args.checkpointing_steps == 0:
643
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
644
+ if args.checkpoints_total_limit is not None:
645
+ checkpoints = os.listdir(args.output_dir)
646
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
647
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
648
+
649
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
650
+ if len(checkpoints) >= args.checkpoints_total_limit:
651
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
652
+ removing_checkpoints = checkpoints[0:num_to_remove]
653
+
654
+ logger.info(
655
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
656
+ )
657
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
658
+
659
+ for removing_checkpoint in removing_checkpoints:
660
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
661
+ shutil.rmtree(removing_checkpoint)
662
+
663
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
664
+ accelerator.save_state(save_path)
665
+ logger.info(f"Saved state to {save_path}")
666
+
667
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
668
+ if args.use_ema:
669
+ logs["ema_decay"] = ema_model.cur_decay_value
670
+ progress_bar.set_postfix(**logs)
671
+ accelerator.log(logs, step=global_step)
672
+ progress_bar.close()
673
+
674
+ accelerator.wait_for_everyone()
675
+
676
+ # Generate sample images for visual inspection
677
+ if accelerator.is_main_process:
678
+ if epoch % args.save_images_epochs == 0 or epoch == args.num_epochs - 1:
679
+ unet = accelerator.unwrap_model(model)
680
+
681
+ if args.use_ema:
682
+ ema_model.store(unet.parameters())
683
+ ema_model.copy_to(unet.parameters())
684
+
685
+ pipeline = DDPMPipeline(
686
+ unet=unet,
687
+ scheduler=noise_scheduler,
688
+ )
689
+
690
+ generator = torch.Generator(device=pipeline.device).manual_seed(0)
691
+ # run pipeline in inference (sample random noise and denoise)
692
+ images = pipeline(
693
+ generator=generator,
694
+ batch_size=args.eval_batch_size,
695
+ num_inference_steps=args.ddpm_num_inference_steps,
696
+ output_type="np",
697
+ ).images
698
+
699
+ if args.use_ema:
700
+ ema_model.restore(unet.parameters())
701
+
702
+ # denormalize the images and save to tensorboard
703
+ images_processed = (images * 255).round().astype("uint8")
704
+
705
+ if args.logger == "tensorboard":
706
+ if is_accelerate_version(">=", "0.17.0.dev0"):
707
+ tracker = accelerator.get_tracker("tensorboard", unwrap=True)
708
+ else:
709
+ tracker = accelerator.get_tracker("tensorboard")
710
+ tracker.add_images("test_samples", images_processed.transpose(0, 3, 1, 2), epoch)
711
+ elif args.logger == "wandb":
712
+ # Upcoming `log_images` helper coming in https://github.com/huggingface/accelerate/pull/962/files
713
+ accelerator.get_tracker("wandb").log(
714
+ {"test_samples": [wandb.Image(img) for img in images_processed], "epoch": epoch},
715
+ step=global_step,
716
+ )
717
+
718
+ if epoch % args.save_model_epochs == 0 or epoch == args.num_epochs - 1:
719
+ # save the model
720
+ unet = accelerator.unwrap_model(model)
721
+
722
+ if args.use_ema:
723
+ ema_model.store(unet.parameters())
724
+ ema_model.copy_to(unet.parameters())
725
+
726
+ pipeline = DDPMPipeline(
727
+ unet=unet,
728
+ scheduler=noise_scheduler,
729
+ )
730
+
731
+ pipeline.save_pretrained(args.output_dir)
732
+
733
+ if args.use_ema:
734
+ ema_model.restore(unet.parameters())
735
+
736
+ if args.push_to_hub:
737
+ upload_folder(
738
+ repo_id=repo_id,
739
+ folder_path=args.output_dir,
740
+ commit_message=f"Epoch {epoch}",
741
+ ignore_patterns=["step_*", "epoch_*"],
742
+ )
743
+
744
+ accelerator.end_training()
745
+
746
+
747
+ if __name__ == "__main__":
748
+ args = parse_args()
749
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Training an VQGAN VAE
2
+ VQVAEs were first introduced in [Neural Discrete Representation Learning](https://huggingface.co/papers/1711.00937) and was combined with a GAN in the paper [Taming Transformers for High-Resolution Image Synthesis](https://huggingface.co/papers/2012.09841). The basic idea of a VQVAE is it's a type of a variational auto encoder with tokens as the latent space similar to tokens for LLMs. This script was adapted from a [pr to huggingface's open-muse project](https://github.com/huggingface/open-muse/pull/52) with general code following [lucidrian's implementation of the vqgan training script](https://github.com/lucidrains/muse-maskgit-pytorch/blob/main/muse_maskgit_pytorch/trainers.py) but both of these implementation follow from the [taming transformer repo](https://github.com/CompVis/taming-transformers?tab=readme-ov-file).
3
+
4
+
5
+ Creating a training image set is [described in a different document](https://huggingface.co/docs/datasets/image_process#image-datasets).
6
+
7
+ ### Installing the dependencies
8
+
9
+ Before running the scripts, make sure to install the library's training dependencies:
10
+
11
+ **Important**
12
+
13
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
14
+ ```bash
15
+ git clone https://github.com/huggingface/diffusers
16
+ cd diffusers
17
+ pip install .
18
+ ```
19
+
20
+ Then cd in the example folder and run
21
+ ```bash
22
+ pip install -r requirements.txt
23
+ ```
24
+
25
+
26
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
27
+
28
+ ```bash
29
+ accelerate config
30
+ ```
31
+
32
+ ### Training on CIFAR10
33
+
34
+ The command to train a VQGAN model on cifar10 dataset:
35
+
36
+ ```bash
37
+ accelerate launch train_vqgan.py \
38
+ --dataset_name=cifar10 \
39
+ --image_column=img \
40
+ --validation_images images/bird.jpg images/car.jpg images/dog.jpg images/frog.jpg \
41
+ --resolution=128 \
42
+ --train_batch_size=2 \
43
+ --gradient_accumulation_steps=8 \
44
+ --report_to=wandb
45
+ ```
46
+
47
+ An example training run is [here](https://wandb.ai/sayakpaul/vqgan-training/runs/0m5kzdfp) by @sayakpaul and a lower scale one [here](https://wandb.ai/dsbuddy27/vqgan-training/runs/eqd6xi4n?nw=nwuserisamu). The validation images can be obtained from [here](https://huggingface.co/datasets/diffusers/docs-images/tree/main/vqgan_validation_images).
48
+ The simplest way to improve the quality of a VQGAN model is to maximize the amount of information present in the bottleneck. The easiest way to do this is increasing the image resolution. However, other ways include, but not limited to, lowering compression by downsampling fewer times or increasing the vocabulary size which at most can be around 16384. How to do this is shown below.
49
+
50
+ # Modifying the architecture
51
+
52
+ To modify the architecture of the vqgan model you can save the config taken from [here](https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder/blob/main/movq/config.json) and then provide that to the script with the option --model_config_name_or_path. This config is below
53
+ ```
54
+ {
55
+ "_class_name": "VQModel",
56
+ "_diffusers_version": "0.17.0.dev0",
57
+ "act_fn": "silu",
58
+ "block_out_channels": [
59
+ 128,
60
+ 256,
61
+ 256,
62
+ 512
63
+ ],
64
+ "down_block_types": [
65
+ "DownEncoderBlock2D",
66
+ "DownEncoderBlock2D",
67
+ "DownEncoderBlock2D",
68
+ "AttnDownEncoderBlock2D"
69
+ ],
70
+ "in_channels": 3,
71
+ "latent_channels": 4,
72
+ "layers_per_block": 2,
73
+ "norm_num_groups": 32,
74
+ "norm_type": "spatial",
75
+ "num_vq_embeddings": 16384,
76
+ "out_channels": 3,
77
+ "sample_size": 32,
78
+ "scaling_factor": 0.18215,
79
+ "up_block_types": [
80
+ "AttnUpDecoderBlock2D",
81
+ "UpDecoderBlock2D",
82
+ "UpDecoderBlock2D",
83
+ "UpDecoderBlock2D"
84
+ ],
85
+ "vq_embed_dim": 4
86
+ }
87
+ ```
88
+ To lower the amount of layers in a VQGan, you can remove layers by modifying the block_out_channels, down_block_types, and up_block_types like below
89
+ ```
90
+ {
91
+ "_class_name": "VQModel",
92
+ "_diffusers_version": "0.17.0.dev0",
93
+ "act_fn": "silu",
94
+ "block_out_channels": [
95
+ 128,
96
+ 256,
97
+ 256,
98
+ ],
99
+ "down_block_types": [
100
+ "DownEncoderBlock2D",
101
+ "DownEncoderBlock2D",
102
+ "DownEncoderBlock2D",
103
+ ],
104
+ "in_channels": 3,
105
+ "latent_channels": 4,
106
+ "layers_per_block": 2,
107
+ "norm_num_groups": 32,
108
+ "norm_type": "spatial",
109
+ "num_vq_embeddings": 16384,
110
+ "out_channels": 3,
111
+ "sample_size": 32,
112
+ "scaling_factor": 0.18215,
113
+ "up_block_types": [
114
+ "UpDecoderBlock2D",
115
+ "UpDecoderBlock2D",
116
+ "UpDecoderBlock2D"
117
+ ],
118
+ "vq_embed_dim": 4
119
+ }
120
+ ```
121
+ For increasing the size of the vocabularies you can increase num_vq_embeddings. However, [some research](https://magvit.cs.cmu.edu/v2/) shows that the representation of VQGANs start degrading after 2^14~16384 vq embeddings so it's not recommended to go past that.
122
+
123
+ ## Extra training tips/ideas
124
+ During logging take care to make sure data_time is low. data_time is the amount spent loading the data and where the GPU is not active. So essentially, it's the time wasted. The easiest way to lower data time is to increase the --dataloader_num_workers to a higher number like 4. Due to a bug in Pytorch, this only works on linux based systems. For more details check [here](https://github.com/huggingface/diffusers/issues/7646)
125
+ Secondly, training should seem to be done when both the discriminator and the generator loss converges.
126
+ Thirdly, another low hanging fruit is just using ema using the --use_ema parameter. This tends to make the output images smoother. This has a con where you have to lower your batch size by 1 but it may be worth it.
127
+ Another more experimental low hanging fruit is changing from the vgg19 to different models for the lpips loss using the --timm_model_backend. If you do this, I recommend also changing the timm_model_layers parameter to the layer in your model which you think is best for representation. However, be careful with the feature map norms since this can easily overdominate the loss.
tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/discriminator.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ported from Paella
3
+ """
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.models.modeling_utils import ModelMixin
10
+
11
+
12
+ # Discriminator model ported from Paella https://github.com/dome272/Paella/blob/main/src_distributed/vqgan.py
13
+ class Discriminator(ModelMixin, ConfigMixin):
14
+ @register_to_config
15
+ def __init__(self, in_channels=3, cond_channels=0, hidden_channels=512, depth=6):
16
+ super().__init__()
17
+ d = max(depth - 3, 3)
18
+ layers = [
19
+ nn.utils.spectral_norm(
20
+ nn.Conv2d(in_channels, hidden_channels // (2**d), kernel_size=3, stride=2, padding=1)
21
+ ),
22
+ nn.LeakyReLU(0.2),
23
+ ]
24
+ for i in range(depth - 1):
25
+ c_in = hidden_channels // (2 ** max((d - i), 0))
26
+ c_out = hidden_channels // (2 ** max((d - 1 - i), 0))
27
+ layers.append(nn.utils.spectral_norm(nn.Conv2d(c_in, c_out, kernel_size=3, stride=2, padding=1)))
28
+ layers.append(nn.InstanceNorm2d(c_out))
29
+ layers.append(nn.LeakyReLU(0.2))
30
+ self.encoder = nn.Sequential(*layers)
31
+ self.shuffle = nn.Conv2d(
32
+ (hidden_channels + cond_channels) if cond_channels > 0 else hidden_channels, 1, kernel_size=1
33
+ )
34
+ self.logits = nn.Sigmoid()
35
+
36
+ def forward(self, x, cond=None):
37
+ x = self.encoder(x)
38
+ if cond is not None:
39
+ cond = cond.view(
40
+ cond.size(0),
41
+ cond.size(1),
42
+ 1,
43
+ 1,
44
+ ).expand(-1, -1, x.size(-2), x.size(-1))
45
+ x = torch.cat([x, cond], dim=1)
46
+ x = self.shuffle(x)
47
+ x = self.logits(x)
48
+ return x
tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ datasets
5
+ timm
6
+ numpy
7
+ tqdm
8
+ tensorboard
tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/test_vqgan.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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 json
18
+ import logging
19
+ import os
20
+ import shutil
21
+ import sys
22
+ import tempfile
23
+
24
+ import torch
25
+
26
+ from diffusers import VQModel
27
+
28
+
29
+ # Add parent directories to path to import from tests
30
+ sys.path.append("..")
31
+ repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
32
+ if repo_root not in sys.path:
33
+ sys.path.insert(0, repo_root)
34
+
35
+ from test_examples_utils import ExamplesTestsAccelerate, run_command # noqa: E402
36
+
37
+ from tests.testing_utils import require_timm # noqa
38
+
39
+
40
+ logging.basicConfig(level=logging.DEBUG)
41
+
42
+ logger = logging.getLogger()
43
+ stream_handler = logging.StreamHandler(sys.stdout)
44
+ logger.addHandler(stream_handler)
45
+
46
+
47
+ @require_timm
48
+ class TextToImage(ExamplesTestsAccelerate):
49
+ @property
50
+ def test_vqmodel_config(self):
51
+ return {
52
+ "_class_name": "VQModel",
53
+ "_diffusers_version": "0.17.0.dev0",
54
+ "act_fn": "silu",
55
+ "block_out_channels": [
56
+ 32,
57
+ ],
58
+ "down_block_types": [
59
+ "DownEncoderBlock2D",
60
+ ],
61
+ "in_channels": 3,
62
+ "latent_channels": 4,
63
+ "layers_per_block": 2,
64
+ "norm_num_groups": 32,
65
+ "norm_type": "spatial",
66
+ "num_vq_embeddings": 32,
67
+ "out_channels": 3,
68
+ "sample_size": 32,
69
+ "scaling_factor": 0.18215,
70
+ "up_block_types": [
71
+ "UpDecoderBlock2D",
72
+ ],
73
+ "vq_embed_dim": 4,
74
+ }
75
+
76
+ @property
77
+ def test_discriminator_config(self):
78
+ return {
79
+ "_class_name": "Discriminator",
80
+ "_diffusers_version": "0.27.0.dev0",
81
+ "in_channels": 3,
82
+ "cond_channels": 0,
83
+ "hidden_channels": 8,
84
+ "depth": 4,
85
+ }
86
+
87
+ def get_vq_and_discriminator_configs(self, tmpdir):
88
+ vqmodel_config_path = os.path.join(tmpdir, "vqmodel.json")
89
+ discriminator_config_path = os.path.join(tmpdir, "discriminator.json")
90
+ with open(vqmodel_config_path, "w") as fp:
91
+ json.dump(self.test_vqmodel_config, fp)
92
+ with open(discriminator_config_path, "w") as fp:
93
+ json.dump(self.test_discriminator_config, fp)
94
+ return vqmodel_config_path, discriminator_config_path
95
+
96
+ def test_vqmodel(self):
97
+ with tempfile.TemporaryDirectory() as tmpdir:
98
+ vqmodel_config_path, discriminator_config_path = self.get_vq_and_discriminator_configs(tmpdir)
99
+ test_args = f"""
100
+ examples/vqgan/train_vqgan.py
101
+ --dataset_name hf-internal-testing/dummy_image_text_data
102
+ --resolution 32
103
+ --image_column image
104
+ --train_batch_size 1
105
+ --gradient_accumulation_steps 1
106
+ --max_train_steps 2
107
+ --learning_rate 5.0e-04
108
+ --scale_lr
109
+ --lr_scheduler constant
110
+ --lr_warmup_steps 0
111
+ --model_config_name_or_path {vqmodel_config_path}
112
+ --discriminator_config_name_or_path {discriminator_config_path}
113
+ --output_dir {tmpdir}
114
+ """.split()
115
+
116
+ run_command(self._launch_args + test_args)
117
+ # save_pretrained smoke test
118
+ self.assertTrue(
119
+ os.path.isfile(os.path.join(tmpdir, "discriminator", "diffusion_pytorch_model.safetensors"))
120
+ )
121
+ self.assertTrue(os.path.isfile(os.path.join(tmpdir, "vqmodel", "diffusion_pytorch_model.safetensors")))
122
+
123
+ def test_vqmodel_checkpointing(self):
124
+ with tempfile.TemporaryDirectory() as tmpdir:
125
+ vqmodel_config_path, discriminator_config_path = self.get_vq_and_discriminator_configs(tmpdir)
126
+ # Run training script with checkpointing
127
+ # max_train_steps == 4, checkpointing_steps == 2
128
+ # Should create checkpoints at steps 2, 4
129
+
130
+ initial_run_args = f"""
131
+ examples/vqgan/train_vqgan.py
132
+ --dataset_name hf-internal-testing/dummy_image_text_data
133
+ --resolution 32
134
+ --image_column image
135
+ --train_batch_size 1
136
+ --gradient_accumulation_steps 1
137
+ --max_train_steps 4
138
+ --learning_rate 5.0e-04
139
+ --scale_lr
140
+ --lr_scheduler constant
141
+ --lr_warmup_steps 0
142
+ --model_config_name_or_path {vqmodel_config_path}
143
+ --discriminator_config_name_or_path {discriminator_config_path}
144
+ --checkpointing_steps=2
145
+ --output_dir {tmpdir}
146
+ --seed=0
147
+ """.split()
148
+
149
+ run_command(self._launch_args + initial_run_args)
150
+
151
+ # check checkpoint directories exist
152
+ self.assertEqual(
153
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
154
+ {"checkpoint-2", "checkpoint-4"},
155
+ )
156
+
157
+ # check can run an intermediate checkpoint
158
+ model = VQModel.from_pretrained(tmpdir, subfolder="checkpoint-2/vqmodel")
159
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
160
+ _ = model(image)
161
+
162
+ # Remove checkpoint 2 so that we can check only later checkpoints exist after resuming
163
+ shutil.rmtree(os.path.join(tmpdir, "checkpoint-2"))
164
+ self.assertEqual(
165
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
166
+ {"checkpoint-4"},
167
+ )
168
+
169
+ # Run training script for 2 total steps resuming from checkpoint 4
170
+
171
+ resume_run_args = f"""
172
+ examples/vqgan/train_vqgan.py
173
+ --dataset_name hf-internal-testing/dummy_image_text_data
174
+ --resolution 32
175
+ --image_column image
176
+ --train_batch_size 1
177
+ --gradient_accumulation_steps 1
178
+ --max_train_steps 6
179
+ --learning_rate 5.0e-04
180
+ --scale_lr
181
+ --lr_scheduler constant
182
+ --lr_warmup_steps 0
183
+ --model_config_name_or_path {vqmodel_config_path}
184
+ --discriminator_config_name_or_path {discriminator_config_path}
185
+ --checkpointing_steps=1
186
+ --resume_from_checkpoint={os.path.join(tmpdir, "checkpoint-4")}
187
+ --output_dir {tmpdir}
188
+ --seed=0
189
+ """.split()
190
+
191
+ run_command(self._launch_args + resume_run_args)
192
+
193
+ # check can run new fully trained pipeline
194
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
195
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
196
+ _ = model(image)
197
+
198
+ # no checkpoint-2 -> check old checkpoints do not exist
199
+ # check new checkpoints exist
200
+ # In the current script, checkpointing_steps 1 is equivalent to checkpointing_steps 2 as after the generator gets trained for one step,
201
+ # the discriminator gets trained and loss and saving happens after that. Thus we do not expect to get a checkpoint-5
202
+ self.assertEqual(
203
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
204
+ {"checkpoint-4", "checkpoint-6"},
205
+ )
206
+
207
+ def test_vqmodel_checkpointing_use_ema(self):
208
+ with tempfile.TemporaryDirectory() as tmpdir:
209
+ vqmodel_config_path, discriminator_config_path = self.get_vq_and_discriminator_configs(tmpdir)
210
+ # Run training script with checkpointing
211
+ # max_train_steps == 4, checkpointing_steps == 2
212
+ # Should create checkpoints at steps 2, 4
213
+
214
+ initial_run_args = f"""
215
+ examples/vqgan/train_vqgan.py
216
+ --dataset_name hf-internal-testing/dummy_image_text_data
217
+ --resolution 32
218
+ --image_column image
219
+ --train_batch_size 1
220
+ --gradient_accumulation_steps 1
221
+ --max_train_steps 4
222
+ --learning_rate 5.0e-04
223
+ --scale_lr
224
+ --lr_scheduler constant
225
+ --lr_warmup_steps 0
226
+ --model_config_name_or_path {vqmodel_config_path}
227
+ --discriminator_config_name_or_path {discriminator_config_path}
228
+ --checkpointing_steps=2
229
+ --output_dir {tmpdir}
230
+ --use_ema
231
+ --seed=0
232
+ """.split()
233
+
234
+ run_command(self._launch_args + initial_run_args)
235
+
236
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
237
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
238
+ _ = model(image)
239
+
240
+ # check checkpoint directories exist
241
+ self.assertEqual(
242
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
243
+ {"checkpoint-2", "checkpoint-4"},
244
+ )
245
+
246
+ # check can run an intermediate checkpoint
247
+ model = VQModel.from_pretrained(tmpdir, subfolder="checkpoint-2/vqmodel")
248
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
249
+ _ = model(image)
250
+
251
+ # Remove checkpoint 2 so that we can check only later checkpoints exist after resuming
252
+ shutil.rmtree(os.path.join(tmpdir, "checkpoint-2"))
253
+
254
+ # Run training script for 2 total steps resuming from checkpoint 4
255
+
256
+ resume_run_args = f"""
257
+ examples/vqgan/train_vqgan.py
258
+ --dataset_name hf-internal-testing/dummy_image_text_data
259
+ --resolution 32
260
+ --image_column image
261
+ --train_batch_size 1
262
+ --gradient_accumulation_steps 1
263
+ --max_train_steps 6
264
+ --learning_rate 5.0e-04
265
+ --scale_lr
266
+ --lr_scheduler constant
267
+ --lr_warmup_steps 0
268
+ --model_config_name_or_path {vqmodel_config_path}
269
+ --discriminator_config_name_or_path {discriminator_config_path}
270
+ --checkpointing_steps=1
271
+ --resume_from_checkpoint={os.path.join(tmpdir, "checkpoint-4")}
272
+ --output_dir {tmpdir}
273
+ --use_ema
274
+ --seed=0
275
+ """.split()
276
+
277
+ run_command(self._launch_args + resume_run_args)
278
+
279
+ # check can run new fully trained pipeline
280
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
281
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
282
+ _ = model(image)
283
+
284
+ # no checkpoint-2 -> check old checkpoints do not exist
285
+ # check new checkpoints exist
286
+ self.assertEqual(
287
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
288
+ {"checkpoint-4", "checkpoint-6"},
289
+ )
290
+
291
+ def test_vqmodel_checkpointing_checkpoints_total_limit(self):
292
+ with tempfile.TemporaryDirectory() as tmpdir:
293
+ vqmodel_config_path, discriminator_config_path = self.get_vq_and_discriminator_configs(tmpdir)
294
+ # Run training script with checkpointing
295
+ # max_train_steps == 6, checkpointing_steps == 2, checkpoints_total_limit == 2
296
+ # Should create checkpoints at steps 2, 4, 6
297
+ # with checkpoint at step 2 deleted
298
+
299
+ initial_run_args = f"""
300
+ examples/vqgan/train_vqgan.py
301
+ --dataset_name hf-internal-testing/dummy_image_text_data
302
+ --resolution 32
303
+ --image_column image
304
+ --train_batch_size 1
305
+ --gradient_accumulation_steps 1
306
+ --max_train_steps 6
307
+ --learning_rate 5.0e-04
308
+ --scale_lr
309
+ --lr_scheduler constant
310
+ --lr_warmup_steps 0
311
+ --model_config_name_or_path {vqmodel_config_path}
312
+ --discriminator_config_name_or_path {discriminator_config_path}
313
+ --output_dir {tmpdir}
314
+ --checkpointing_steps=2
315
+ --checkpoints_total_limit=2
316
+ --seed=0
317
+ """.split()
318
+
319
+ run_command(self._launch_args + initial_run_args)
320
+
321
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
322
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
323
+ _ = model(image)
324
+
325
+ # check checkpoint directories exist
326
+ # checkpoint-2 should have been deleted
327
+ self.assertEqual({x for x in os.listdir(tmpdir) if "checkpoint" in x}, {"checkpoint-4", "checkpoint-6"})
328
+
329
+ def test_vqmodel_checkpointing_checkpoints_total_limit_removes_multiple_checkpoints(self):
330
+ with tempfile.TemporaryDirectory() as tmpdir:
331
+ vqmodel_config_path, discriminator_config_path = self.get_vq_and_discriminator_configs(tmpdir)
332
+ # Run training script with checkpointing
333
+ # max_train_steps == 4, checkpointing_steps == 2
334
+ # Should create checkpoints at steps 2, 4
335
+
336
+ initial_run_args = f"""
337
+ examples/vqgan/train_vqgan.py
338
+ --dataset_name hf-internal-testing/dummy_image_text_data
339
+ --resolution 32
340
+ --image_column image
341
+ --train_batch_size 1
342
+ --gradient_accumulation_steps 1
343
+ --max_train_steps 4
344
+ --learning_rate 5.0e-04
345
+ --scale_lr
346
+ --lr_scheduler constant
347
+ --lr_warmup_steps 0
348
+ --model_config_name_or_path {vqmodel_config_path}
349
+ --discriminator_config_name_or_path {discriminator_config_path}
350
+ --checkpointing_steps=2
351
+ --output_dir {tmpdir}
352
+ --seed=0
353
+ """.split()
354
+
355
+ run_command(self._launch_args + initial_run_args)
356
+
357
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
358
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
359
+ _ = model(image)
360
+
361
+ # check checkpoint directories exist
362
+ self.assertEqual(
363
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
364
+ {"checkpoint-2", "checkpoint-4"},
365
+ )
366
+
367
+ # resume and we should try to checkpoint at 6, where we'll have to remove
368
+ # checkpoint-2 and checkpoint-4 instead of just a single previous checkpoint
369
+
370
+ resume_run_args = f"""
371
+ examples/vqgan/train_vqgan.py
372
+ --dataset_name hf-internal-testing/dummy_image_text_data
373
+ --resolution 32
374
+ --image_column image
375
+ --train_batch_size 1
376
+ --gradient_accumulation_steps 1
377
+ --max_train_steps 8
378
+ --learning_rate 5.0e-04
379
+ --scale_lr
380
+ --lr_scheduler constant
381
+ --lr_warmup_steps 0
382
+ --model_config_name_or_path {vqmodel_config_path}
383
+ --discriminator_config_name_or_path {discriminator_config_path}
384
+ --output_dir {tmpdir}
385
+ --checkpointing_steps=2
386
+ --resume_from_checkpoint={os.path.join(tmpdir, "checkpoint-4")}
387
+ --checkpoints_total_limit=2
388
+ --seed=0
389
+ """.split()
390
+
391
+ run_command(self._launch_args + resume_run_args)
392
+
393
+ model = VQModel.from_pretrained(tmpdir, subfolder="vqmodel")
394
+ image = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
395
+ _ = model(image)
396
+
397
+ # check checkpoint directories exist
398
+ self.assertEqual(
399
+ {x for x in os.listdir(tmpdir) if "checkpoint" in x},
400
+ {"checkpoint-6", "checkpoint-8"},
401
+ )
tasks/tasksmith-ee553a5e62c1/environment/source/examples/vqgan/train_vqgan.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import argparse
17
+ import math
18
+ import os
19
+ import shutil
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import accelerate
24
+ import numpy as np
25
+ import PIL
26
+ import PIL.Image
27
+ import timm
28
+ import torch
29
+ import torch.nn.functional as F
30
+ from accelerate import Accelerator
31
+ from accelerate.logging import get_logger
32
+ from accelerate.utils import DistributedType, ProjectConfiguration, set_seed
33
+ from datasets import load_dataset
34
+ from discriminator import Discriminator
35
+ from huggingface_hub import create_repo
36
+ from packaging import version
37
+ from PIL import Image
38
+ from timm.data import resolve_data_config
39
+ from timm.data.transforms_factory import create_transform
40
+ from torchvision import transforms
41
+ from tqdm import tqdm
42
+
43
+ from diffusers import VQModel
44
+ from diffusers.optimization import get_scheduler
45
+ from diffusers.training_utils import EMAModel
46
+ from diffusers.utils import check_min_version, is_wandb_available
47
+
48
+
49
+ if is_wandb_available():
50
+ import wandb
51
+
52
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
53
+ check_min_version("0.39.0.dev0")
54
+
55
+ logger = get_logger(__name__, log_level="INFO")
56
+
57
+
58
+ class AverageMeter(object):
59
+ """Computes and stores the average and current value"""
60
+
61
+ def __init__(self):
62
+ self.reset()
63
+
64
+ def reset(self):
65
+ self.val = 0
66
+ self.avg = 0
67
+ self.sum = 0
68
+ self.count = 0
69
+
70
+ def update(self, val, n=1):
71
+ self.val = val
72
+ self.sum += val * n
73
+ self.count += n
74
+ self.avg = self.sum / self.count
75
+
76
+
77
+ def _map_layer_to_idx(backbone, layers, offset=0):
78
+ """Maps set of layer names to indices of model. Ported from anomalib
79
+
80
+ Returns:
81
+ Feature map extracted from the CNN
82
+ """
83
+ idx = []
84
+ features = timm.create_model(
85
+ backbone,
86
+ pretrained=False,
87
+ features_only=False,
88
+ exportable=True,
89
+ )
90
+ for i in layers:
91
+ try:
92
+ idx.append(list(dict(features.named_children()).keys()).index(i) - offset)
93
+ except ValueError:
94
+ raise ValueError(
95
+ f"Layer {i} not found in model {backbone}. Select layer from {list(dict(features.named_children()).keys())}. The network architecture is {features}"
96
+ )
97
+ return idx
98
+
99
+
100
+ def get_perceptual_loss(pixel_values, fmap, timm_model, timm_model_resolution, timm_model_normalization):
101
+ img_timm_model_input = timm_model_normalization(F.interpolate(pixel_values, timm_model_resolution))
102
+ fmap_timm_model_input = timm_model_normalization(F.interpolate(fmap, timm_model_resolution))
103
+
104
+ if pixel_values.shape[1] == 1:
105
+ # handle grayscale for timm_model
106
+ img_timm_model_input, fmap_timm_model_input = (
107
+ t.repeat(1, 3, 1, 1) for t in (img_timm_model_input, fmap_timm_model_input)
108
+ )
109
+
110
+ img_timm_model_feats = timm_model(img_timm_model_input)
111
+ recon_timm_model_feats = timm_model(fmap_timm_model_input)
112
+ perceptual_loss = F.mse_loss(img_timm_model_feats[0], recon_timm_model_feats[0])
113
+ for i in range(1, len(img_timm_model_feats)):
114
+ perceptual_loss += F.mse_loss(img_timm_model_feats[i], recon_timm_model_feats[i])
115
+ perceptual_loss /= len(img_timm_model_feats)
116
+ return perceptual_loss
117
+
118
+
119
+ def grad_layer_wrt_loss(loss, layer):
120
+ return torch.autograd.grad(
121
+ outputs=loss,
122
+ inputs=layer,
123
+ grad_outputs=torch.ones_like(loss),
124
+ retain_graph=True,
125
+ )[0].detach()
126
+
127
+
128
+ def gradient_penalty(images, output, weight=10):
129
+ gradients = torch.autograd.grad(
130
+ outputs=output,
131
+ inputs=images,
132
+ grad_outputs=torch.ones(output.size(), device=images.device),
133
+ create_graph=True,
134
+ retain_graph=True,
135
+ only_inputs=True,
136
+ )[0]
137
+ bsz = gradients.shape[0]
138
+ gradients = torch.reshape(gradients, (bsz, -1))
139
+ return weight * ((gradients.norm(2, dim=1) - 1) ** 2).mean()
140
+
141
+
142
+ @torch.no_grad()
143
+ def log_validation(model, args, validation_transform, accelerator, global_step):
144
+ logger.info("Generating images...")
145
+ dtype = torch.float32
146
+ if accelerator.mixed_precision == "fp16":
147
+ dtype = torch.float16
148
+ elif accelerator.mixed_precision == "bf16":
149
+ dtype = torch.bfloat16
150
+ original_images = []
151
+ for image_path in args.validation_images:
152
+ image = PIL.Image.open(image_path)
153
+ if not image.mode == "RGB":
154
+ image = image.convert("RGB")
155
+ image = validation_transform(image).to(accelerator.device, dtype=dtype)
156
+ original_images.append(image[None])
157
+ # Generate images
158
+ model.eval()
159
+ images = []
160
+ for original_image in original_images:
161
+ image = accelerator.unwrap_model(model)(original_image).sample
162
+ images.append(image)
163
+ model.train()
164
+ original_images = torch.cat(original_images, dim=0)
165
+ images = torch.cat(images, dim=0)
166
+
167
+ # Convert to PIL images
168
+ images = torch.clamp(images, 0.0, 1.0)
169
+ original_images = torch.clamp(original_images, 0.0, 1.0)
170
+ images *= 255.0
171
+ original_images *= 255.0
172
+ images = images.permute(0, 2, 3, 1).cpu().numpy().astype(np.uint8)
173
+ original_images = original_images.permute(0, 2, 3, 1).cpu().numpy().astype(np.uint8)
174
+ images = np.concatenate([original_images, images], axis=2)
175
+ images = [Image.fromarray(image) for image in images]
176
+
177
+ # Log images
178
+ for tracker in accelerator.trackers:
179
+ if tracker.name == "tensorboard":
180
+ np_images = np.stack([np.asarray(img) for img in images])
181
+ tracker.writer.add_images("validation", np_images, global_step, dataformats="NHWC")
182
+ if tracker.name == "wandb":
183
+ tracker.log(
184
+ {
185
+ "validation": [
186
+ wandb.Image(image, caption=f"{i}: Original, Generated") for i, image in enumerate(images)
187
+ ]
188
+ },
189
+ step=global_step,
190
+ )
191
+ torch.cuda.empty_cache()
192
+ return images
193
+
194
+
195
+ def log_grad_norm(model, accelerator, global_step):
196
+ for name, param in model.named_parameters():
197
+ if param.grad is not None:
198
+ grads = param.grad.detach().data
199
+ grad_norm = (grads.norm(p=2) / grads.numel()).item()
200
+ accelerator.log({"grad_norm/" + name: grad_norm}, step=global_step)
201
+
202
+
203
+ def parse_args():
204
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
205
+ parser.add_argument(
206
+ "--log_grad_norm_steps",
207
+ type=int,
208
+ default=500,
209
+ help=("Print logs of gradient norms every X steps."),
210
+ )
211
+ parser.add_argument(
212
+ "--log_steps",
213
+ type=int,
214
+ default=50,
215
+ help=("Print logs every X steps."),
216
+ )
217
+ parser.add_argument(
218
+ "--validation_steps",
219
+ type=int,
220
+ default=100,
221
+ help=(
222
+ "Run validation every X steps. Validation consists of running reconstruction on images in"
223
+ " `args.validation_images` and logging the reconstructed images."
224
+ ),
225
+ )
226
+ parser.add_argument(
227
+ "--vae_loss",
228
+ type=str,
229
+ default="l2",
230
+ help="The loss function for vae reconstruction loss.",
231
+ )
232
+ parser.add_argument(
233
+ "--timm_model_offset",
234
+ type=int,
235
+ default=0,
236
+ help="Offset of timm layers to indices.",
237
+ )
238
+ parser.add_argument(
239
+ "--timm_model_layers",
240
+ type=str,
241
+ default="head",
242
+ help="The layers to get output from in the timm model.",
243
+ )
244
+ parser.add_argument(
245
+ "--timm_model_backend",
246
+ type=str,
247
+ default="vgg19",
248
+ help="Timm model used to get the lpips loss",
249
+ )
250
+ parser.add_argument(
251
+ "--pretrained_model_name_or_path",
252
+ type=str,
253
+ default=None,
254
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
255
+ )
256
+ parser.add_argument(
257
+ "--model_config_name_or_path",
258
+ type=str,
259
+ default=None,
260
+ help="The config of the Vq model to train, leave as None to use standard Vq model configuration.",
261
+ )
262
+ parser.add_argument(
263
+ "--discriminator_config_name_or_path",
264
+ type=str,
265
+ default=None,
266
+ help="The config of the discriminator model to train, leave as None to use standard Vq model configuration.",
267
+ )
268
+ parser.add_argument(
269
+ "--revision",
270
+ type=str,
271
+ default=None,
272
+ required=False,
273
+ help="Revision of pretrained model identifier from huggingface.co/models.",
274
+ )
275
+ parser.add_argument(
276
+ "--dataset_name",
277
+ type=str,
278
+ default=None,
279
+ help=(
280
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
281
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
282
+ " or to a folder containing files that 🤗 Datasets can understand."
283
+ ),
284
+ )
285
+ parser.add_argument(
286
+ "--dataset_config_name",
287
+ type=str,
288
+ default=None,
289
+ help="The config of the Dataset, leave as None if there's only one config.",
290
+ )
291
+ parser.add_argument(
292
+ "--train_data_dir",
293
+ type=str,
294
+ default=None,
295
+ help=(
296
+ "A folder containing the training data. Folder contents must follow the structure described in"
297
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
298
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
299
+ ),
300
+ )
301
+ parser.add_argument(
302
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
303
+ )
304
+ parser.add_argument(
305
+ "--max_train_samples",
306
+ type=int,
307
+ default=None,
308
+ help=(
309
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
310
+ "value if set."
311
+ ),
312
+ )
313
+ parser.add_argument(
314
+ "--validation_images",
315
+ type=str,
316
+ default=None,
317
+ nargs="+",
318
+ help=("A set of validation images evaluated every `--validation_steps` and logged to `--report_to`."),
319
+ )
320
+ parser.add_argument(
321
+ "--output_dir",
322
+ type=str,
323
+ default="vqgan-output",
324
+ help="The output directory where the model predictions and checkpoints will be written.",
325
+ )
326
+ parser.add_argument(
327
+ "--cache_dir",
328
+ type=str,
329
+ default=None,
330
+ help="The directory where the downloaded models and datasets will be stored.",
331
+ )
332
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
333
+ parser.add_argument(
334
+ "--resolution",
335
+ type=int,
336
+ default=512,
337
+ help=(
338
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
339
+ " resolution"
340
+ ),
341
+ )
342
+ parser.add_argument(
343
+ "--center_crop",
344
+ default=False,
345
+ action="store_true",
346
+ help=(
347
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
348
+ " cropped. The images will be resized to the resolution first before cropping."
349
+ ),
350
+ )
351
+ parser.add_argument(
352
+ "--random_flip",
353
+ action="store_true",
354
+ help="whether to randomly flip images horizontally",
355
+ )
356
+ parser.add_argument(
357
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
358
+ )
359
+ parser.add_argument("--num_train_epochs", type=int, default=100)
360
+ parser.add_argument(
361
+ "--max_train_steps",
362
+ type=int,
363
+ default=None,
364
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
365
+ )
366
+ parser.add_argument(
367
+ "--gradient_accumulation_steps",
368
+ type=int,
369
+ default=1,
370
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
371
+ )
372
+ parser.add_argument(
373
+ "--gradient_checkpointing",
374
+ action="store_true",
375
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
376
+ )
377
+ parser.add_argument(
378
+ "--discr_learning_rate",
379
+ type=float,
380
+ default=1e-4,
381
+ help="Initial learning rate (after the potential warmup period) to use.",
382
+ )
383
+ parser.add_argument(
384
+ "--learning_rate",
385
+ type=float,
386
+ default=1e-4,
387
+ help="Initial learning rate (after the potential warmup period) to use.",
388
+ )
389
+ parser.add_argument(
390
+ "--scale_lr",
391
+ action="store_true",
392
+ default=False,
393
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
394
+ )
395
+ parser.add_argument(
396
+ "--lr_scheduler",
397
+ type=str,
398
+ default="constant",
399
+ help=(
400
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
401
+ ' "constant", "constant_with_warmup"]'
402
+ ),
403
+ )
404
+ parser.add_argument(
405
+ "--discr_lr_scheduler",
406
+ type=str,
407
+ default="constant",
408
+ help=(
409
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
410
+ ' "constant", "constant_with_warmup"]'
411
+ ),
412
+ )
413
+ parser.add_argument(
414
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
415
+ )
416
+ parser.add_argument(
417
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
418
+ )
419
+ parser.add_argument(
420
+ "--allow_tf32",
421
+ action="store_true",
422
+ help=(
423
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
424
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
425
+ ),
426
+ )
427
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
428
+ parser.add_argument(
429
+ "--non_ema_revision",
430
+ type=str,
431
+ default=None,
432
+ required=False,
433
+ help=(
434
+ "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
435
+ " remote repository specified with --pretrained_model_name_or_path."
436
+ ),
437
+ )
438
+ parser.add_argument(
439
+ "--dataloader_num_workers",
440
+ type=int,
441
+ default=0,
442
+ help=(
443
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
444
+ ),
445
+ )
446
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
447
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
448
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
449
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
450
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
451
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
452
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
453
+ parser.add_argument(
454
+ "--prediction_type",
455
+ type=str,
456
+ default=None,
457
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediciton_type` is chosen.",
458
+ )
459
+ parser.add_argument(
460
+ "--hub_model_id",
461
+ type=str,
462
+ default=None,
463
+ help="The name of the repository to keep in sync with the local `output_dir`.",
464
+ )
465
+ parser.add_argument(
466
+ "--logging_dir",
467
+ type=str,
468
+ default="logs",
469
+ help=(
470
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
471
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
472
+ ),
473
+ )
474
+ parser.add_argument(
475
+ "--mixed_precision",
476
+ type=str,
477
+ default=None,
478
+ choices=["no", "fp16", "bf16"],
479
+ help=(
480
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
481
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
482
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
483
+ ),
484
+ )
485
+ parser.add_argument(
486
+ "--report_to",
487
+ type=str,
488
+ default="tensorboard",
489
+ help=(
490
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
491
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
492
+ ),
493
+ )
494
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
495
+ parser.add_argument(
496
+ "--checkpointing_steps",
497
+ type=int,
498
+ default=500,
499
+ help=(
500
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
501
+ " training using `--resume_from_checkpoint`."
502
+ ),
503
+ )
504
+ parser.add_argument(
505
+ "--checkpoints_total_limit",
506
+ type=int,
507
+ default=None,
508
+ help=("Max number of checkpoints to store."),
509
+ )
510
+ parser.add_argument(
511
+ "--resume_from_checkpoint",
512
+ type=str,
513
+ default=None,
514
+ help=(
515
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
516
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
517
+ ),
518
+ )
519
+ parser.add_argument(
520
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
521
+ )
522
+ parser.add_argument(
523
+ "--tracker_project_name",
524
+ type=str,
525
+ default="vqgan-training",
526
+ help=(
527
+ "The `project_name` argument passed to Accelerator.init_trackers for"
528
+ " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
529
+ ),
530
+ )
531
+
532
+ args = parser.parse_args()
533
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
534
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
535
+ args.local_rank = env_local_rank
536
+
537
+ # Sanity checks
538
+ if args.dataset_name is None and args.train_data_dir is None:
539
+ raise ValueError("Need either a dataset name or a training folder.")
540
+
541
+ # default to using the same revision for the non-ema model if not specified
542
+ if args.non_ema_revision is None:
543
+ args.non_ema_revision = args.revision
544
+
545
+ return args
546
+
547
+
548
+ def main():
549
+ #########################
550
+ # SETUP Accelerator #
551
+ #########################
552
+ args = parse_args()
553
+
554
+ # Enable TF32 on Ampere GPUs
555
+ if args.allow_tf32:
556
+ torch.backends.cuda.matmul.allow_tf32 = True
557
+ torch.backends.cudnn.benchmark = True
558
+ torch.backends.cudnn.deterministic = False
559
+
560
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
561
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
562
+
563
+ accelerator = Accelerator(
564
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
565
+ mixed_precision=args.mixed_precision,
566
+ log_with=args.report_to,
567
+ project_config=accelerator_project_config,
568
+ )
569
+
570
+ if accelerator.distributed_type == DistributedType.DEEPSPEED:
571
+ accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = args.train_batch_size
572
+
573
+ #####################################
574
+ # SETUP LOGGING, SEED and CONFIG #
575
+ #####################################
576
+
577
+ if accelerator.is_main_process:
578
+ tracker_config = dict(vars(args))
579
+ tracker_config.pop("validation_images")
580
+ accelerator.init_trackers(args.tracker_project_name, tracker_config)
581
+
582
+ # If passed along, set the training seed now.
583
+ if args.seed is not None:
584
+ set_seed(args.seed)
585
+
586
+ # Handle the repository creation
587
+ if accelerator.is_main_process:
588
+ if args.output_dir is not None:
589
+ os.makedirs(args.output_dir, exist_ok=True)
590
+
591
+ if args.push_to_hub:
592
+ create_repo(
593
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
594
+ ).repo_id
595
+
596
+ #########################
597
+ # MODELS and OPTIMIZER #
598
+ #########################
599
+ logger.info("Loading models and optimizer")
600
+
601
+ if args.model_config_name_or_path is None and args.pretrained_model_name_or_path is None:
602
+ # Taken from config of movq at kandinsky-community/kandinsky-2-2-decoder but without the attention layers
603
+ model = VQModel(
604
+ act_fn="silu",
605
+ block_out_channels=[
606
+ 128,
607
+ 256,
608
+ 512,
609
+ ],
610
+ down_block_types=[
611
+ "DownEncoderBlock2D",
612
+ "DownEncoderBlock2D",
613
+ "DownEncoderBlock2D",
614
+ ],
615
+ in_channels=3,
616
+ latent_channels=4,
617
+ layers_per_block=2,
618
+ norm_num_groups=32,
619
+ norm_type="spatial",
620
+ num_vq_embeddings=16384,
621
+ out_channels=3,
622
+ sample_size=32,
623
+ scaling_factor=0.18215,
624
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
625
+ vq_embed_dim=4,
626
+ )
627
+ elif args.pretrained_model_name_or_path is not None:
628
+ model = VQModel.from_pretrained(args.pretrained_model_name_or_path)
629
+ else:
630
+ config = VQModel.load_config(args.model_config_name_or_path)
631
+ model = VQModel.from_config(config)
632
+ if args.use_ema:
633
+ ema_model = EMAModel(model.parameters(), model_cls=VQModel, model_config=model.config)
634
+ if args.discriminator_config_name_or_path is None:
635
+ discriminator = Discriminator()
636
+ else:
637
+ config = Discriminator.load_config(args.discriminator_config_name_or_path)
638
+ discriminator = Discriminator.from_config(config)
639
+
640
+ idx = _map_layer_to_idx(args.timm_model_backend, args.timm_model_layers.split("|"), args.timm_model_offset)
641
+
642
+ timm_model = timm.create_model(
643
+ args.timm_model_backend,
644
+ pretrained=True,
645
+ features_only=True,
646
+ exportable=True,
647
+ out_indices=idx,
648
+ )
649
+ timm_model = timm_model.to(accelerator.device)
650
+ timm_model.requires_grad = False
651
+ timm_model.eval()
652
+ timm_transform = create_transform(**resolve_data_config(timm_model.pretrained_cfg, model=timm_model))
653
+ try:
654
+ # Gets the resolution of the timm transformation after centercrop
655
+ timm_centercrop_transform = timm_transform.transforms[1]
656
+ assert isinstance(timm_centercrop_transform, transforms.CenterCrop), (
657
+ f"Timm model {timm_model} is currently incompatible with this script. Try vgg19."
658
+ )
659
+ timm_model_resolution = timm_centercrop_transform.size[0]
660
+ # Gets final normalization
661
+ timm_model_normalization = timm_transform.transforms[-1]
662
+ assert isinstance(timm_model_normalization, transforms.Normalize), (
663
+ f"Timm model {timm_model} is currently incompatible with this script. Try vgg19."
664
+ )
665
+ except AssertionError as e:
666
+ raise NotImplementedError(e)
667
+ # Enable flash attention if asked
668
+ if args.enable_xformers_memory_efficient_attention:
669
+ model.enable_xformers_memory_efficient_attention()
670
+
671
+ # `accelerate` 0.16.0 will have better support for customized saving
672
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
673
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
674
+ def save_model_hook(models, weights, output_dir):
675
+ if accelerator.is_main_process:
676
+ if args.use_ema:
677
+ ema_model.save_pretrained(os.path.join(output_dir, "vqmodel_ema"))
678
+ vqmodel = models[0]
679
+ discriminator = models[1]
680
+ vqmodel.save_pretrained(os.path.join(output_dir, "vqmodel"))
681
+ discriminator.save_pretrained(os.path.join(output_dir, "discriminator"))
682
+ weights.pop()
683
+ weights.pop()
684
+
685
+ def load_model_hook(models, input_dir):
686
+ if args.use_ema:
687
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "vqmodel_ema"), VQModel)
688
+ ema_model.load_state_dict(load_model.state_dict())
689
+ ema_model.to(accelerator.device)
690
+ del load_model
691
+ discriminator = models.pop()
692
+ load_model = Discriminator.from_pretrained(input_dir, subfolder="discriminator")
693
+ discriminator.register_to_config(**load_model.config)
694
+ discriminator.load_state_dict(load_model.state_dict())
695
+ del load_model
696
+ vqmodel = models.pop()
697
+ load_model = VQModel.from_pretrained(input_dir, subfolder="vqmodel")
698
+ vqmodel.register_to_config(**load_model.config)
699
+ vqmodel.load_state_dict(load_model.state_dict())
700
+ del load_model
701
+
702
+ accelerator.register_save_state_pre_hook(save_model_hook)
703
+ accelerator.register_load_state_pre_hook(load_model_hook)
704
+
705
+ learning_rate = args.learning_rate
706
+ if args.scale_lr:
707
+ learning_rate = (
708
+ learning_rate * args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
709
+ )
710
+
711
+ # Initialize the optimizer
712
+ if args.use_8bit_adam:
713
+ try:
714
+ import bitsandbytes as bnb
715
+ except ImportError:
716
+ raise ImportError(
717
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
718
+ )
719
+
720
+ optimizer_cls = bnb.optim.AdamW8bit
721
+ else:
722
+ optimizer_cls = torch.optim.AdamW
723
+
724
+ optimizer = optimizer_cls(
725
+ list(model.parameters()),
726
+ lr=args.learning_rate,
727
+ betas=(args.adam_beta1, args.adam_beta2),
728
+ weight_decay=args.adam_weight_decay,
729
+ eps=args.adam_epsilon,
730
+ )
731
+ discr_optimizer = optimizer_cls(
732
+ list(discriminator.parameters()),
733
+ lr=args.discr_learning_rate,
734
+ betas=(args.adam_beta1, args.adam_beta2),
735
+ weight_decay=args.adam_weight_decay,
736
+ eps=args.adam_epsilon,
737
+ )
738
+
739
+ ##################################
740
+ # DATLOADER and LR-SCHEDULER #
741
+ #################################
742
+ logger.info("Creating dataloaders and lr_scheduler")
743
+
744
+ args.train_batch_size * accelerator.num_processes
745
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
746
+
747
+ # DataLoaders creation:
748
+ if args.dataset_name is not None:
749
+ # Downloading and loading a dataset from the hub.
750
+ dataset = load_dataset(
751
+ args.dataset_name,
752
+ args.dataset_config_name,
753
+ cache_dir=args.cache_dir,
754
+ data_dir=args.train_data_dir,
755
+ )
756
+ else:
757
+ data_files = {}
758
+ if args.train_data_dir is not None:
759
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
760
+ dataset = load_dataset(
761
+ "imagefolder",
762
+ data_files=data_files,
763
+ cache_dir=args.cache_dir,
764
+ )
765
+ # See more about loading custom images at
766
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
767
+
768
+ # Preprocessing the datasets.
769
+ # We need to tokenize inputs and targets.
770
+ column_names = dataset["train"].column_names
771
+
772
+ # 6. Get the column names for input/target.
773
+ assert args.image_column is not None
774
+ image_column = args.image_column
775
+ if image_column not in column_names:
776
+ raise ValueError(f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}")
777
+ # Preprocessing the datasets.
778
+ train_transforms = transforms.Compose(
779
+ [
780
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
781
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
782
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
783
+ transforms.ToTensor(),
784
+ ]
785
+ )
786
+ validation_transform = transforms.Compose(
787
+ [
788
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
789
+ transforms.ToTensor(),
790
+ ]
791
+ )
792
+
793
+ def preprocess_train(examples):
794
+ images = [image.convert("RGB") for image in examples[image_column]]
795
+ examples["pixel_values"] = [train_transforms(image) for image in images]
796
+ return examples
797
+
798
+ with accelerator.main_process_first():
799
+ if args.max_train_samples is not None:
800
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
801
+ train_dataset = dataset["train"].with_transform(preprocess_train)
802
+
803
+ def collate_fn(examples):
804
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
805
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
806
+ return {"pixel_values": pixel_values}
807
+
808
+ # DataLoaders creation:
809
+ train_dataloader = torch.utils.data.DataLoader(
810
+ train_dataset,
811
+ shuffle=True,
812
+ collate_fn=collate_fn,
813
+ batch_size=args.train_batch_size,
814
+ num_workers=args.dataloader_num_workers,
815
+ )
816
+
817
+ lr_scheduler = get_scheduler(
818
+ args.lr_scheduler,
819
+ optimizer=optimizer,
820
+ num_training_steps=args.max_train_steps,
821
+ num_warmup_steps=args.lr_warmup_steps,
822
+ )
823
+ discr_lr_scheduler = get_scheduler(
824
+ args.discr_lr_scheduler,
825
+ optimizer=discr_optimizer,
826
+ num_training_steps=args.max_train_steps,
827
+ num_warmup_steps=args.lr_warmup_steps,
828
+ )
829
+
830
+ # Prepare everything with accelerator
831
+ logger.info("Preparing model, optimizer and dataloaders")
832
+ # The dataloader are already aware of distributed training, so we don't need to prepare them.
833
+ model, discriminator, optimizer, discr_optimizer, lr_scheduler, discr_lr_scheduler = accelerator.prepare(
834
+ model, discriminator, optimizer, discr_optimizer, lr_scheduler, discr_lr_scheduler
835
+ )
836
+ if args.use_ema:
837
+ ema_model.to(accelerator.device)
838
+ # Train!
839
+ logger.info("***** Running training *****")
840
+ logger.info(f" Num examples = {len(train_dataset)}")
841
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
842
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
843
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
844
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
845
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
846
+ global_step = 0
847
+ first_epoch = 0
848
+ # Scheduler and math around the number of training steps.
849
+ overrode_max_train_steps = False
850
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
851
+ if args.max_train_steps is None:
852
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
853
+ overrode_max_train_steps = True
854
+ if overrode_max_train_steps:
855
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
856
+ # Afterwards we recalculate our number of training epochs
857
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
858
+
859
+ # Potentially load in the weights and states from a previous save
860
+ resume_from_checkpoint = args.resume_from_checkpoint
861
+ if resume_from_checkpoint:
862
+ if resume_from_checkpoint != "latest":
863
+ path = resume_from_checkpoint
864
+ else:
865
+ # Get the most recent checkpoint
866
+ dirs = os.listdir(args.output_dir)
867
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
868
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
869
+ path = dirs[-1] if len(dirs) > 0 else None
870
+ path = os.path.join(args.output_dir, path)
871
+
872
+ if path is None:
873
+ accelerator.print(f"Checkpoint '{resume_from_checkpoint}' does not exist. Starting a new training run.")
874
+ resume_from_checkpoint = None
875
+ else:
876
+ accelerator.print(f"Resuming from checkpoint {path}")
877
+ accelerator.load_state(path)
878
+ accelerator.wait_for_everyone()
879
+ global_step = int(os.path.basename(path).split("-")[1])
880
+ first_epoch = global_step // num_update_steps_per_epoch
881
+
882
+ batch_time_m = AverageMeter()
883
+ data_time_m = AverageMeter()
884
+ end = time.time()
885
+ progress_bar = tqdm(
886
+ range(0, args.max_train_steps),
887
+ initial=global_step,
888
+ desc="Steps",
889
+ # Only show the progress bar once on each machine.
890
+ disable=not accelerator.is_local_main_process,
891
+ )
892
+ # As stated above, we are not doing epoch based training here, but just using this for book keeping and being able to
893
+ # reuse the same training loop with other datasets/loaders.
894
+ avg_gen_loss, avg_discr_loss = None, None
895
+ for epoch in range(first_epoch, args.num_train_epochs):
896
+ model.train()
897
+ discriminator.train()
898
+ for i, batch in enumerate(train_dataloader):
899
+ pixel_values = batch["pixel_values"]
900
+ pixel_values = pixel_values.to(accelerator.device, non_blocking=True)
901
+ data_time_m.update(time.time() - end)
902
+ generator_step = ((i // args.gradient_accumulation_steps) % 2) == 0
903
+ # Train Step
904
+ # The behavior of accelerator.accumulate is to
905
+ # 1. Check if gradients are synced(reached gradient-accumulation_steps)
906
+ # 2. If so sync gradients by stopping the not syncing process
907
+ if generator_step:
908
+ optimizer.zero_grad(set_to_none=True)
909
+ else:
910
+ discr_optimizer.zero_grad(set_to_none=True)
911
+ # encode images to the latent space and get the commit loss from vq tokenization
912
+ # Return commit loss
913
+ fmap, commit_loss = model(pixel_values, return_dict=False)
914
+
915
+ if generator_step:
916
+ with accelerator.accumulate(model):
917
+ # reconstruction loss. Pixel level differences between input vs output
918
+ if args.vae_loss == "l2":
919
+ loss = F.mse_loss(pixel_values, fmap)
920
+ else:
921
+ loss = F.l1_loss(pixel_values, fmap)
922
+ # perceptual loss. The high level feature mean squared error loss
923
+ perceptual_loss = get_perceptual_loss(
924
+ pixel_values,
925
+ fmap,
926
+ timm_model,
927
+ timm_model_resolution=timm_model_resolution,
928
+ timm_model_normalization=timm_model_normalization,
929
+ )
930
+ # generator loss
931
+ gen_loss = -discriminator(fmap).mean()
932
+ last_dec_layer = accelerator.unwrap_model(model).decoder.conv_out.weight
933
+ norm_grad_wrt_perceptual_loss = grad_layer_wrt_loss(perceptual_loss, last_dec_layer).norm(p=2)
934
+ norm_grad_wrt_gen_loss = grad_layer_wrt_loss(gen_loss, last_dec_layer).norm(p=2)
935
+
936
+ adaptive_weight = norm_grad_wrt_perceptual_loss / norm_grad_wrt_gen_loss.clamp(min=1e-8)
937
+ adaptive_weight = adaptive_weight.clamp(max=1e4)
938
+ loss += commit_loss
939
+ loss += perceptual_loss
940
+ loss += adaptive_weight * gen_loss
941
+ # Gather the losses across all processes for logging (if we use distributed training).
942
+ avg_gen_loss = accelerator.gather(loss.repeat(args.train_batch_size)).float().mean()
943
+ accelerator.backward(loss)
944
+
945
+ if args.max_grad_norm is not None and accelerator.sync_gradients:
946
+ accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm)
947
+
948
+ optimizer.step()
949
+ lr_scheduler.step()
950
+ # log gradient norm before zeroing it
951
+ if (
952
+ accelerator.sync_gradients
953
+ and global_step % args.log_grad_norm_steps == 0
954
+ and accelerator.is_main_process
955
+ ):
956
+ log_grad_norm(model, accelerator, global_step)
957
+ else:
958
+ # Return discriminator loss
959
+ with accelerator.accumulate(discriminator):
960
+ fmap.detach_()
961
+ pixel_values.requires_grad_()
962
+ real = discriminator(pixel_values)
963
+ fake = discriminator(fmap)
964
+ loss = (F.relu(1 + fake) + F.relu(1 - real)).mean()
965
+ gp = gradient_penalty(pixel_values, real)
966
+ loss += gp
967
+ avg_discr_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
968
+ accelerator.backward(loss)
969
+
970
+ if args.max_grad_norm is not None and accelerator.sync_gradients:
971
+ accelerator.clip_grad_norm_(discriminator.parameters(), args.max_grad_norm)
972
+
973
+ discr_optimizer.step()
974
+ discr_lr_scheduler.step()
975
+ if (
976
+ accelerator.sync_gradients
977
+ and global_step % args.log_grad_norm_steps == 0
978
+ and accelerator.is_main_process
979
+ ):
980
+ log_grad_norm(discriminator, accelerator, global_step)
981
+ batch_time_m.update(time.time() - end)
982
+ # Checks if the accelerator has performed an optimization step behind the scenes
983
+ if accelerator.sync_gradients:
984
+ global_step += 1
985
+ progress_bar.update(1)
986
+ if args.use_ema:
987
+ ema_model.step(model.parameters())
988
+ if accelerator.sync_gradients and not generator_step and accelerator.is_main_process:
989
+ # wait for both generator and discriminator to settle
990
+ # Log metrics
991
+ if global_step % args.log_steps == 0:
992
+ samples_per_second_per_gpu = (
993
+ args.gradient_accumulation_steps * args.train_batch_size / batch_time_m.val
994
+ )
995
+ logs = {
996
+ "step_discr_loss": avg_discr_loss.item(),
997
+ "lr": lr_scheduler.get_last_lr()[0],
998
+ "samples/sec/gpu": samples_per_second_per_gpu,
999
+ "data_time": data_time_m.val,
1000
+ "batch_time": batch_time_m.val,
1001
+ }
1002
+ if avg_gen_loss is not None:
1003
+ logs["step_gen_loss"] = avg_gen_loss.item()
1004
+ accelerator.log(logs, step=global_step)
1005
+
1006
+ # resetting batch / data time meters per log window
1007
+ batch_time_m.reset()
1008
+ data_time_m.reset()
1009
+ # Save model checkpoint
1010
+ if global_step % args.checkpointing_steps == 0:
1011
+ if accelerator.is_main_process:
1012
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1013
+ if args.checkpoints_total_limit is not None:
1014
+ checkpoints = os.listdir(args.output_dir)
1015
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1016
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1017
+
1018
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1019
+ if len(checkpoints) >= args.checkpoints_total_limit:
1020
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1021
+ removing_checkpoints = checkpoints[0:num_to_remove]
1022
+
1023
+ logger.info(
1024
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1025
+ )
1026
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1027
+
1028
+ for removing_checkpoint in removing_checkpoints:
1029
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1030
+ shutil.rmtree(removing_checkpoint)
1031
+
1032
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1033
+ accelerator.save_state(save_path)
1034
+ logger.info(f"Saved state to {save_path}")
1035
+
1036
+ # Generate images
1037
+ if global_step % args.validation_steps == 0:
1038
+ if args.use_ema:
1039
+ # Store the VQGAN parameters temporarily and load the EMA parameters to perform inference.
1040
+ ema_model.store(model.parameters())
1041
+ ema_model.copy_to(model.parameters())
1042
+ log_validation(model, args, validation_transform, accelerator, global_step)
1043
+ if args.use_ema:
1044
+ # Switch back to the original VQGAN parameters.
1045
+ ema_model.restore(model.parameters())
1046
+ end = time.time()
1047
+ # Stop training if max steps is reached
1048
+ if global_step >= args.max_train_steps:
1049
+ break
1050
+ # End for
1051
+
1052
+ accelerator.wait_for_everyone()
1053
+
1054
+ # Save the final trained checkpoint
1055
+ if accelerator.is_main_process:
1056
+ model = accelerator.unwrap_model(model)
1057
+ discriminator = accelerator.unwrap_model(discriminator)
1058
+ if args.use_ema:
1059
+ ema_model.copy_to(model.parameters())
1060
+ model.save_pretrained(os.path.join(args.output_dir, "vqmodel"))
1061
+ discriminator.save_pretrained(os.path.join(args.output_dir, "discriminator"))
1062
+
1063
+ accelerator.end_training()
1064
+
1065
+
1066
+ if __name__ == "__main__":
1067
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/pyproject.toml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.ruff]
2
+ line-length = 119
3
+ extend-exclude = [
4
+ "src/diffusers/pipelines/flux2/system_messages.py",
5
+ ]
6
+
7
+ [tool.ruff.lint]
8
+ # Never enforce `E501` (line length violations).
9
+ ignore = ["C901", "E501", "E721", "E741", "F402", "F823"]
10
+ select = ["C", "E", "F", "I", "W"]
11
+
12
+ # Ignore import violations in all `__init__.py` files.
13
+ [tool.ruff.lint.per-file-ignores]
14
+ "__init__.py" = ["E402", "F401", "F403", "F811"]
15
+ "src/diffusers/utils/dummy_*.py" = ["F401"]
16
+
17
+ [tool.ruff.lint.isort]
18
+ lines-after-imports = 2
19
+ known-first-party = ["diffusers"]
20
+
21
+ [tool.ruff.format]
22
+ # Like Black, use double quotes for strings.
23
+ quote-style = "double"
24
+
25
+ # Like Black, indent with spaces, rather than tabs.
26
+ indent-style = "space"
27
+
28
+ # Like Black, respect magic trailing commas.
29
+ skip-magic-trailing-comma = false
30
+
31
+ # Like Black, automatically detect the appropriate line ending.
32
+ line-ending = "auto"
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/__init__.py ADDED
File without changes
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/change_naming_configs_and_checkpoints.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Conversion script for the LDM checkpoints."""
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+
21
+ import torch
22
+ from transformers.file_utils import has_file
23
+
24
+ from diffusers import UNet2DConditionModel, UNet2DModel
25
+
26
+
27
+ do_only_config = False
28
+ do_only_weights = True
29
+ do_only_renaming = False
30
+
31
+
32
+ if __name__ == "__main__":
33
+ parser = argparse.ArgumentParser()
34
+
35
+ parser.add_argument(
36
+ "--repo_path",
37
+ default=None,
38
+ type=str,
39
+ required=True,
40
+ help="The config json file corresponding to the architecture.",
41
+ )
42
+
43
+ parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
44
+
45
+ args = parser.parse_args()
46
+
47
+ config_parameters_to_change = {
48
+ "image_size": "sample_size",
49
+ "num_res_blocks": "layers_per_block",
50
+ "block_channels": "block_out_channels",
51
+ "down_blocks": "down_block_types",
52
+ "up_blocks": "up_block_types",
53
+ "downscale_freq_shift": "freq_shift",
54
+ "resnet_num_groups": "norm_num_groups",
55
+ "resnet_act_fn": "act_fn",
56
+ "resnet_eps": "norm_eps",
57
+ "num_head_channels": "attention_head_dim",
58
+ }
59
+
60
+ key_parameters_to_change = {
61
+ "time_steps": "time_proj",
62
+ "mid": "mid_block",
63
+ "downsample_blocks": "down_blocks",
64
+ "upsample_blocks": "up_blocks",
65
+ }
66
+
67
+ subfolder = "" if has_file(args.repo_path, "config.json") else "unet"
68
+
69
+ with open(os.path.join(args.repo_path, subfolder, "config.json"), "r", encoding="utf-8") as reader:
70
+ text = reader.read()
71
+ config = json.loads(text)
72
+
73
+ if do_only_config:
74
+ for key in config_parameters_to_change.keys():
75
+ config.pop(key, None)
76
+
77
+ if has_file(args.repo_path, "config.json"):
78
+ model = UNet2DModel(**config)
79
+ else:
80
+ class_name = UNet2DConditionModel if "ldm-text2im-large-256" in args.repo_path else UNet2DModel
81
+ model = class_name(**config)
82
+
83
+ if do_only_config:
84
+ model.save_config(os.path.join(args.repo_path, subfolder))
85
+
86
+ config = dict(model.config)
87
+
88
+ if do_only_renaming:
89
+ for key, value in config_parameters_to_change.items():
90
+ if key in config:
91
+ config[value] = config[key]
92
+ del config[key]
93
+
94
+ config["down_block_types"] = [k.replace("UNetRes", "") for k in config["down_block_types"]]
95
+ config["up_block_types"] = [k.replace("UNetRes", "") for k in config["up_block_types"]]
96
+
97
+ if do_only_weights:
98
+ state_dict = torch.load(os.path.join(args.repo_path, subfolder, "diffusion_pytorch_model.bin"))
99
+
100
+ new_state_dict = {}
101
+ for param_key, param_value in state_dict.items():
102
+ if param_key.endswith(".op.bias") or param_key.endswith(".op.weight"):
103
+ continue
104
+ has_changed = False
105
+ for key, new_key in key_parameters_to_change.items():
106
+ if not has_changed and param_key.split(".")[0] == key:
107
+ new_state_dict[".".join([new_key] + param_key.split(".")[1:])] = param_value
108
+ has_changed = True
109
+ if not has_changed:
110
+ new_state_dict[param_key] = param_value
111
+
112
+ model.load_state_dict(new_state_dict)
113
+ model.save_pretrained(os.path.join(args.repo_path, subfolder))
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/conversion_ldm_uncond.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch
4
+ import yaml
5
+
6
+ from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel
7
+
8
+
9
+ def convert_ldm_original(checkpoint_path, config_path, output_path):
10
+ config = yaml.safe_load(config_path)
11
+ state_dict = torch.load(checkpoint_path, map_location="cpu")["model"]
12
+ keys = list(state_dict.keys())
13
+
14
+ # extract state_dict for VQVAE
15
+ first_stage_dict = {}
16
+ first_stage_key = "first_stage_model."
17
+ for key in keys:
18
+ if key.startswith(first_stage_key):
19
+ first_stage_dict[key.replace(first_stage_key, "")] = state_dict[key]
20
+
21
+ # extract state_dict for UNetLDM
22
+ unet_state_dict = {}
23
+ unet_key = "model.diffusion_model."
24
+ for key in keys:
25
+ if key.startswith(unet_key):
26
+ unet_state_dict[key.replace(unet_key, "")] = state_dict[key]
27
+
28
+ vqvae_init_args = config["model"]["params"]["first_stage_config"]["params"]
29
+ unet_init_args = config["model"]["params"]["unet_config"]["params"]
30
+
31
+ vqvae = VQModel(**vqvae_init_args).eval()
32
+ vqvae.load_state_dict(first_stage_dict)
33
+
34
+ unet = UNetLDMModel(**unet_init_args).eval()
35
+ unet.load_state_dict(unet_state_dict)
36
+
37
+ noise_scheduler = DDIMScheduler(
38
+ timesteps=config["model"]["params"]["timesteps"],
39
+ beta_schedule="scaled_linear",
40
+ beta_start=config["model"]["params"]["linear_start"],
41
+ beta_end=config["model"]["params"]["linear_end"],
42
+ clip_sample=False,
43
+ )
44
+
45
+ pipeline = LDMPipeline(vqvae, unet, noise_scheduler)
46
+ pipeline.save_pretrained(output_path)
47
+
48
+
49
+ if __name__ == "__main__":
50
+ parser = argparse.ArgumentParser()
51
+ parser.add_argument("--checkpoint_path", type=str, required=True)
52
+ parser.add_argument("--config_path", type=str, required=True)
53
+ parser.add_argument("--output_path", type=str, required=True)
54
+ args = parser.parse_args()
55
+
56
+ convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_ace_step_to_diffusers.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run this script to convert ACE-Step model weights to a diffusers pipeline.
2
+ #
3
+ # Usage:
4
+ # python scripts/convert_ace_step_to_diffusers.py \
5
+ # --checkpoint_dir /path/to/ACE-Step-1.5/checkpoints \
6
+ # --dit_config acestep-v15-turbo \
7
+ # --output_dir /path/to/output/ACE-Step-v1-5-turbo \
8
+ # --dtype bf16
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import shutil
14
+
15
+ import torch
16
+ from safetensors.torch import load_file
17
+
18
+
19
+ def convert_ace_step_weights(checkpoint_dir, dit_config, output_dir, dtype_str="bf16"):
20
+ """
21
+ Convert ACE-Step checkpoint weights into a Diffusers-compatible pipeline layout.
22
+
23
+ The original ACE-Step model stores all weights in a single `model.safetensors` file
24
+ under `checkpoints/<dit_config>/`. This script splits the weights into separate
25
+ sub-model directories that can be loaded by `AceStepPipeline.from_pretrained()`.
26
+
27
+ Expected input layout:
28
+ checkpoint_dir/
29
+ <dit_config>/ # e.g., acestep-v15-turbo
30
+ config.json
31
+ model.safetensors
32
+ silence_latent.pt
33
+ vae/
34
+ config.json
35
+ diffusion_pytorch_model.safetensors
36
+ Qwen3-Embedding-0.6B/
37
+ config.json
38
+ model.safetensors
39
+ tokenizer.json
40
+ ...
41
+
42
+ Output layout:
43
+ output_dir/
44
+ model_index.json
45
+ transformer/
46
+ config.json
47
+ diffusion_pytorch_model.safetensors
48
+ condition_encoder/
49
+ config.json
50
+ diffusion_pytorch_model.safetensors
51
+ vae/
52
+ config.json
53
+ diffusion_pytorch_model.safetensors
54
+ text_encoder/
55
+ config.json
56
+ model.safetensors
57
+ ...
58
+ tokenizer/
59
+ tokenizer.json
60
+ ...
61
+ """
62
+ # Support `--checkpoint_dir <repo-id>` by snapshot-downloading it first. A
63
+ # local path that happens not to exist still raises the clearer FileNotFoundError
64
+ # below, so we only fall through to the Hub if the path is missing AND looks like
65
+ # a repo id (namespace/name).
66
+ if not os.path.exists(checkpoint_dir) and "/" in checkpoint_dir and not checkpoint_dir.startswith((".", "~", "/")):
67
+ try:
68
+ from huggingface_hub import snapshot_download
69
+
70
+ print(f"Downloading `{checkpoint_dir}` from the Hugging Face Hub ...")
71
+ checkpoint_dir = snapshot_download(repo_id=checkpoint_dir)
72
+ print(f" -> local snapshot at {checkpoint_dir}")
73
+ except ImportError as e:
74
+ raise ImportError(
75
+ "To use a Hugging Face Hub repo id for --checkpoint_dir, install `huggingface_hub`."
76
+ ) from e
77
+
78
+ # Resolve paths
79
+ dit_dir = os.path.join(checkpoint_dir, dit_config)
80
+ vae_dir = os.path.join(checkpoint_dir, "vae")
81
+ text_encoder_dir = os.path.join(checkpoint_dir, "Qwen3-Embedding-0.6B")
82
+
83
+ # The DiT weights ship either as a single `model.safetensors` (the smaller turbo
84
+ # variant) or as sharded safetensors keyed by `model.safetensors.index.json`
85
+ # (the 5B XL variant). Resolve both layouts to `dit_weight_files` and load below.
86
+ single_model_path = os.path.join(dit_dir, "model.safetensors")
87
+ sharded_index_path = os.path.join(dit_dir, "model.safetensors.index.json")
88
+ config_path = os.path.join(dit_dir, "config.json")
89
+ if os.path.exists(single_model_path):
90
+ dit_weight_files = [single_model_path]
91
+ elif os.path.exists(sharded_index_path):
92
+ with open(sharded_index_path) as f:
93
+ shard_index = json.load(f)
94
+ dit_weight_files = [os.path.join(dit_dir, s) for s in sorted(set(shard_index["weight_map"].values()))]
95
+ for p in dit_weight_files:
96
+ if not os.path.exists(p):
97
+ raise FileNotFoundError(f"sharded DiT weight missing: {p}")
98
+ else:
99
+ raise FileNotFoundError(
100
+ f"DiT weights not found at: {single_model_path} or {sharded_index_path}. "
101
+ "Expected either a single `model.safetensors` or a sharded "
102
+ "`model.safetensors.index.json` + per-shard files."
103
+ )
104
+ for path, name in [
105
+ (config_path, "config"),
106
+ (vae_dir, "VAE"),
107
+ (text_encoder_dir, "text encoder"),
108
+ ]:
109
+ if not os.path.exists(path):
110
+ raise FileNotFoundError(f"{name} not found at: {path}")
111
+
112
+ # Select dtype
113
+ dtype_map = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16}
114
+ if dtype_str not in dtype_map:
115
+ raise ValueError(f"Unsupported dtype: {dtype_str}. Choose from {list(dtype_map.keys())}")
116
+ target_dtype = dtype_map[dtype_str]
117
+
118
+ # Load original config
119
+ with open(config_path) as f:
120
+ original_config = json.load(f)
121
+
122
+ print(f"Loading DiT weights from {len(dit_weight_files)} file(s) ...")
123
+ state_dict = {}
124
+ for p in dit_weight_files:
125
+ print(f" loading {os.path.basename(p)}")
126
+ state_dict.update(load_file(p))
127
+ print(f" Total keys: {len(state_dict)}")
128
+
129
+ # =========================================================================
130
+ # 1. Split weights by prefix
131
+ # =========================================================================
132
+ transformer_sd = {}
133
+ condition_encoder_sd = {}
134
+ audio_tokenizer_sd = {}
135
+ audio_token_detokenizer_sd = {}
136
+ other_sd = {}
137
+
138
+ # Rename original ACE-Step attention keys to the diffusers `Attention` +
139
+ # `AttnProcessor` convention (`to_q`/`to_k`/`to_v`/`to_out.0`/`norm_q`/`norm_k`).
140
+ # Applies uniformly to both the DiT (self-attn and cross-attn) and the
141
+ # condition-encoder self-attention, since both use `AceStepAttention`.
142
+ _ATTN_KEY_RENAMES = [
143
+ (".q_proj.", ".to_q."),
144
+ (".k_proj.", ".to_k."),
145
+ (".v_proj.", ".to_v."),
146
+ (".o_proj.", ".to_out.0."),
147
+ (".q_norm.", ".norm_q."),
148
+ (".k_norm.", ".norm_k."),
149
+ ]
150
+
151
+ def _rename_attn_keys(key: str) -> str:
152
+ for old, new in _ATTN_KEY_RENAMES:
153
+ key = key.replace(old, new)
154
+ return key
155
+
156
+ for key, value in state_dict.items():
157
+ if key.startswith("decoder."):
158
+ # Strip "decoder." prefix for the transformer
159
+ new_key = key[len("decoder.") :]
160
+ # The original model uses nn.Sequential for proj_in/proj_out:
161
+ # proj_in = Sequential(Lambda, Conv1d, Lambda)
162
+ # proj_out = Sequential(Lambda, ConvTranspose1d, Lambda)
163
+ # Only the Conv1d/ConvTranspose1d (index 1) has parameters.
164
+ # In diffusers, we use standalone Conv1d/ConvTranspose1d named proj_in_conv/proj_out_conv.
165
+ new_key = new_key.replace("proj_in.1.", "proj_in_conv.")
166
+ new_key = new_key.replace("proj_out.1.", "proj_out_conv.")
167
+ new_key = _rename_attn_keys(new_key)
168
+ transformer_sd[new_key] = value.to(target_dtype)
169
+ elif key.startswith("encoder."):
170
+ # Strip "encoder." prefix for the condition encoder
171
+ new_key = key[len("encoder.") :]
172
+ new_key = _rename_attn_keys(new_key)
173
+ condition_encoder_sd[new_key] = value.to(target_dtype)
174
+ elif key == "null_condition_emb":
175
+ # Learned unconditional embedding (used by the base/SFT CFG path).
176
+ # Keep it co-located with the condition encoder since that is where the
177
+ # pipeline pulls unconditional sequences from.
178
+ condition_encoder_sd["null_condition_emb"] = value.to(target_dtype)
179
+ elif key.startswith("tokenizer."):
180
+ new_key = key[len("tokenizer.") :]
181
+ new_key = _rename_attn_keys(new_key)
182
+ audio_tokenizer_sd[new_key] = value.to(target_dtype)
183
+ elif key.startswith("detokenizer."):
184
+ new_key = key[len("detokenizer.") :]
185
+ new_key = _rename_attn_keys(new_key)
186
+ audio_token_detokenizer_sd[new_key] = value.to(target_dtype)
187
+ else:
188
+ other_sd[key] = value.to(target_dtype)
189
+
190
+ print(f" Transformer keys: {len(transformer_sd)}")
191
+ print(f" Condition encoder keys: {len(condition_encoder_sd)}")
192
+ print(f" Audio tokenizer keys: {len(audio_tokenizer_sd)}")
193
+ print(f" Audio token detokenizer keys: {len(audio_token_detokenizer_sd)}")
194
+ print(f" Other keys: {len(other_sd)} ({list(other_sd.keys())[:5]}...)")
195
+
196
+ # =========================================================================
197
+ # 2. Build configs for each sub-model
198
+ # =========================================================================
199
+
200
+ # On the 5B XL turbo the condition encoder is narrower than the DiT
201
+ # (`encoder_hidden_size=2048` feeding a `hidden_size=2560` DiT). Non-XL
202
+ # turbo / base checkpoints don't set this field, so fall back to
203
+ # `hidden_size` — that makes the DiT's `condition_embedder` an identity-width
204
+ # Linear as before. Similarly `encoder_intermediate_size` /
205
+ # `encoder_num_attention_heads` / `encoder_num_key_value_heads` describe the
206
+ # condition encoder on XL only.
207
+ encoder_hidden_size = original_config.get("encoder_hidden_size", original_config["hidden_size"])
208
+ encoder_intermediate_size = original_config.get("encoder_intermediate_size", original_config["intermediate_size"])
209
+ encoder_num_attention_heads = original_config.get(
210
+ "encoder_num_attention_heads", original_config["num_attention_heads"]
211
+ )
212
+ encoder_num_key_value_heads = original_config.get(
213
+ "encoder_num_key_value_heads", original_config["num_key_value_heads"]
214
+ )
215
+
216
+ # Transformer (DiT) config. `is_turbo` / `model_version` propagate the variant so
217
+ # the pipeline can pick the right CFG / shift / step-count defaults at inference.
218
+ # Note: `max_position_embeddings` is dropped (RoPE computes freqs on-the-fly per call),
219
+ # and `use_sliding_window` is implied by the mix of `layer_types`.
220
+ transformer_config = {
221
+ "_class_name": "AceStepTransformer1DModel",
222
+ "_diffusers_version": "0.33.0.dev0",
223
+ "hidden_size": original_config["hidden_size"],
224
+ "intermediate_size": original_config["intermediate_size"],
225
+ "num_hidden_layers": original_config["num_hidden_layers"],
226
+ "num_attention_heads": original_config["num_attention_heads"],
227
+ "num_key_value_heads": original_config["num_key_value_heads"],
228
+ "head_dim": original_config["head_dim"],
229
+ "in_channels": original_config["in_channels"],
230
+ "audio_acoustic_hidden_dim": original_config["audio_acoustic_hidden_dim"],
231
+ "patch_size": original_config["patch_size"],
232
+ "rope_theta": original_config["rope_theta"],
233
+ "attention_bias": original_config["attention_bias"],
234
+ "attention_dropout": original_config["attention_dropout"],
235
+ "rms_norm_eps": original_config["rms_norm_eps"],
236
+ "sliding_window": original_config["sliding_window"],
237
+ "layer_types": original_config["layer_types"],
238
+ "encoder_hidden_size": encoder_hidden_size,
239
+ "is_turbo": bool(original_config.get("is_turbo", False)),
240
+ "model_version": original_config.get("model_version"),
241
+ }
242
+
243
+ # Condition encoder config
244
+ condition_encoder_config = {
245
+ "_class_name": "AceStepConditionEncoder",
246
+ "_diffusers_version": "0.33.0.dev0",
247
+ "hidden_size": encoder_hidden_size,
248
+ "intermediate_size": encoder_intermediate_size,
249
+ "text_hidden_dim": original_config["text_hidden_dim"],
250
+ "timbre_hidden_dim": original_config["timbre_hidden_dim"],
251
+ "num_lyric_encoder_hidden_layers": original_config["num_lyric_encoder_hidden_layers"],
252
+ "num_timbre_encoder_hidden_layers": original_config["num_timbre_encoder_hidden_layers"],
253
+ "num_attention_heads": encoder_num_attention_heads,
254
+ "num_key_value_heads": encoder_num_key_value_heads,
255
+ "head_dim": original_config["head_dim"],
256
+ "rope_theta": original_config["rope_theta"],
257
+ "attention_bias": original_config["attention_bias"],
258
+ "attention_dropout": original_config["attention_dropout"],
259
+ "rms_norm_eps": original_config["rms_norm_eps"],
260
+ "sliding_window": original_config["sliding_window"],
261
+ }
262
+
263
+ audio_tokenizer_config = {
264
+ "_class_name": "AceStepAudioTokenizer",
265
+ "_diffusers_version": "0.33.0.dev0",
266
+ "hidden_size": encoder_hidden_size,
267
+ "intermediate_size": encoder_intermediate_size,
268
+ "audio_acoustic_hidden_dim": original_config["audio_acoustic_hidden_dim"],
269
+ "pool_window_size": original_config.get("pool_window_size", 5),
270
+ "fsq_dim": original_config.get("fsq_dim", encoder_hidden_size),
271
+ "fsq_input_levels": original_config.get("fsq_input_levels", [8, 8, 8, 5, 5, 5]),
272
+ "fsq_input_num_quantizers": original_config.get("fsq_input_num_quantizers", 1),
273
+ "num_attention_pooler_hidden_layers": original_config.get("num_attention_pooler_hidden_layers", 2),
274
+ "num_attention_heads": encoder_num_attention_heads,
275
+ "num_key_value_heads": encoder_num_key_value_heads,
276
+ "head_dim": original_config["head_dim"],
277
+ "rope_theta": original_config["rope_theta"],
278
+ "attention_bias": original_config["attention_bias"],
279
+ "attention_dropout": original_config["attention_dropout"],
280
+ "rms_norm_eps": original_config["rms_norm_eps"],
281
+ "sliding_window": original_config["sliding_window"],
282
+ "layer_types": original_config["layer_types"][: original_config.get("num_attention_pooler_hidden_layers", 2)],
283
+ }
284
+
285
+ audio_token_detokenizer_config = {
286
+ "_class_name": "AceStepAudioTokenDetokenizer",
287
+ "_diffusers_version": "0.33.0.dev0",
288
+ "hidden_size": encoder_hidden_size,
289
+ "intermediate_size": encoder_intermediate_size,
290
+ "audio_acoustic_hidden_dim": original_config["audio_acoustic_hidden_dim"],
291
+ "pool_window_size": original_config.get("pool_window_size", 5),
292
+ "num_attention_pooler_hidden_layers": original_config.get("num_attention_pooler_hidden_layers", 2),
293
+ "num_attention_heads": encoder_num_attention_heads,
294
+ "num_key_value_heads": encoder_num_key_value_heads,
295
+ "head_dim": original_config["head_dim"],
296
+ "rope_theta": original_config["rope_theta"],
297
+ "attention_bias": original_config["attention_bias"],
298
+ "attention_dropout": original_config["attention_dropout"],
299
+ "rms_norm_eps": original_config["rms_norm_eps"],
300
+ "sliding_window": original_config["sliding_window"],
301
+ "layer_types": original_config["layer_types"][: original_config.get("num_attention_pooler_hidden_layers", 2)],
302
+ }
303
+
304
+ # =========================================================================
305
+ # 3. Bake silence_latent into the condition_encoder state dict.
306
+ #
307
+ # The original loader in
308
+ # acestep/core/generation/handler/init_service_loader.py:214 does
309
+ # self.silence_latent = torch.load(...).transpose(1, 2)
310
+ # converting the stored [B, C=64, T=15000] tensor to [B, T, C=64] before any
311
+ # downstream slicing. Do the same transpose here and register it as the
312
+ # `silence_latent` buffer on AceStepConditionEncoder — the pipeline slices
313
+ # `silence_latent[:, :timbre_fix_frame, :]` to build the "silence" input to the
314
+ # timbre encoder when no reference audio is supplied. Passing literal zeros
315
+ # produces drone-like audio.
316
+ silence_latent_src = os.path.join(dit_dir, "silence_latent.pt")
317
+ if os.path.exists(silence_latent_src):
318
+ silence_raw = torch.load(silence_latent_src, weights_only=True, map_location="cpu")
319
+ silence_latent = silence_raw.transpose(1, 2).to(target_dtype).contiguous()
320
+ print(f" silence_latent raw shape: {tuple(silence_raw.shape)} -> baked shape: {tuple(silence_latent.shape)}")
321
+ condition_encoder_sd["silence_latent"] = silence_latent
322
+
323
+ # =========================================================================
324
+ # 4. Build the AceStepPipeline in memory and save via `save_pretrained`.
325
+ # Assembling the pipeline directly (rather than hand-writing model_index.json)
326
+ # ensures the saved repo stays in sync with the `AceStepPipeline.__init__`
327
+ # signature — e.g. a future sub-module added to the pipeline can't silently
328
+ # drift out of `model_index.json`.
329
+ # =========================================================================
330
+ from transformers import AutoModel, AutoTokenizer
331
+
332
+ from diffusers import (
333
+ AceStepPipeline,
334
+ AceStepTransformer1DModel,
335
+ AutoencoderOobleck,
336
+ FlowMatchEulerDiscreteScheduler,
337
+ )
338
+ from diffusers.pipelines.ace_step import (
339
+ AceStepAudioTokenDetokenizer,
340
+ AceStepAudioTokenizer,
341
+ AceStepConditionEncoder,
342
+ )
343
+
344
+ # Drop metadata keys — they're re-populated by `save_pretrained` at save time.
345
+ transformer_init_kwargs = {k: v for k, v in transformer_config.items() if not k.startswith("_")}
346
+ condition_encoder_init_kwargs = {k: v for k, v in condition_encoder_config.items() if not k.startswith("_")}
347
+ audio_tokenizer_init_kwargs = {k: v for k, v in audio_tokenizer_config.items() if not k.startswith("_")}
348
+ audio_token_detokenizer_init_kwargs = {
349
+ k: v for k, v in audio_token_detokenizer_config.items() if not k.startswith("_")
350
+ }
351
+
352
+ print("\nConstructing transformer ...")
353
+ transformer = AceStepTransformer1DModel(**transformer_init_kwargs).to(target_dtype)
354
+ transformer.load_state_dict(transformer_sd, strict=True)
355
+
356
+ print("Constructing condition_encoder ...")
357
+ condition_encoder = AceStepConditionEncoder(**condition_encoder_init_kwargs).to(target_dtype)
358
+ condition_encoder.load_state_dict(condition_encoder_sd, strict=True)
359
+
360
+ print("Constructing audio_tokenizer ...")
361
+ audio_tokenizer = AceStepAudioTokenizer(**audio_tokenizer_init_kwargs).to(target_dtype)
362
+ audio_tokenizer.load_state_dict(audio_tokenizer_sd, strict=True)
363
+
364
+ print("Constructing audio_token_detokenizer ...")
365
+ audio_token_detokenizer = AceStepAudioTokenDetokenizer(**audio_token_detokenizer_init_kwargs).to(target_dtype)
366
+ audio_token_detokenizer.load_state_dict(audio_token_detokenizer_sd, strict=True)
367
+
368
+ print("Loading VAE ...")
369
+ vae = AutoencoderOobleck.from_pretrained(vae_dir).to(target_dtype)
370
+
371
+ print("Loading text encoder ...")
372
+ text_encoder = AutoModel.from_pretrained(text_encoder_dir, torch_dtype=target_dtype)
373
+
374
+ print("Loading tokenizer ...")
375
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_dir)
376
+
377
+ # ACE-Step drives the DiT with t ∈ [0, 1] and computes its own shifted / turbo
378
+ # sigma schedule, which it passes to `scheduler.set_timesteps(sigmas=...)` at
379
+ # sampling time. So the scheduler needs `num_train_timesteps=1` (so
380
+ # `scheduler.timesteps == sigmas`) and `shift=1.0` (so it doesn't re-shift
381
+ # already-shifted sigmas). All other defaults are fine.
382
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1, shift=1.0)
383
+
384
+ pipe = AceStepPipeline(
385
+ vae=vae,
386
+ text_encoder=text_encoder,
387
+ tokenizer=tokenizer,
388
+ transformer=transformer,
389
+ condition_encoder=condition_encoder,
390
+ scheduler=scheduler,
391
+ audio_tokenizer=audio_tokenizer,
392
+ audio_token_detokenizer=audio_token_detokenizer,
393
+ )
394
+
395
+ print(f"\nSaving pipeline -> {output_dir}")
396
+ pipe.save_pretrained(output_dir, safe_serialization=True, max_shard_size="5GB")
397
+
398
+ # Keep the raw silence_latent.pt at the pipeline root for debugging — not
399
+ # required by `from_pretrained`, but makes it easy to re-derive the buffer
400
+ # without re-running the full conversion.
401
+ if os.path.exists(silence_latent_src):
402
+ shutil.copy2(silence_latent_src, os.path.join(output_dir, "silence_latent.pt"))
403
+ print(f" kept raw silence_latent copy at {output_dir}/silence_latent.pt")
404
+
405
+ # Report any keys that were not saved to registered pipeline modules.
406
+ if other_sd:
407
+ print(f"\nNote: {len(other_sd)} keys were dropped:")
408
+ for key in sorted(other_sd.keys())[:10]:
409
+ print(f" {key}")
410
+ if len(other_sd) > 10:
411
+ print(f" ... ({len(other_sd) - 10} more)")
412
+
413
+ print(f"\nConversion complete! Output saved to: {output_dir}")
414
+ print("\nTo load the pipeline:")
415
+ print(" from diffusers import AceStepPipeline")
416
+ print(f" pipe = AceStepPipeline.from_pretrained('{output_dir}', torch_dtype=torch.bfloat16)")
417
+ print(" pipe = pipe.to('cuda')")
418
+
419
+
420
+ if __name__ == "__main__":
421
+ parser = argparse.ArgumentParser(description="Convert ACE-Step model weights to Diffusers pipeline format")
422
+ parser.add_argument(
423
+ "--checkpoint_dir",
424
+ type=str,
425
+ required=True,
426
+ help="Path to the ACE-Step checkpoints directory (containing vae/, Qwen3-Embedding-0.6B/, and dit config dirs)",
427
+ )
428
+ parser.add_argument(
429
+ "--dit_config",
430
+ type=str,
431
+ default="acestep-v15-turbo",
432
+ help="Name of the DiT config directory (default: acestep-v15-turbo)",
433
+ )
434
+ parser.add_argument(
435
+ "--output_dir",
436
+ type=str,
437
+ required=True,
438
+ help="Path to save the converted Diffusers pipeline",
439
+ )
440
+ parser.add_argument(
441
+ "--dtype",
442
+ type=str,
443
+ default="bf16",
444
+ choices=["fp32", "fp16", "bf16"],
445
+ help="Data type for saved weights (default: bf16)",
446
+ )
447
+
448
+ args = parser.parse_args()
449
+ convert_ace_step_weights(
450
+ checkpoint_dir=args.checkpoint_dir,
451
+ dit_config=args.dit_config,
452
+ output_dir=args.output_dir,
453
+ dtype_str=args.dtype,
454
+ )
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_amused.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+ from argparse import ArgumentParser
4
+
5
+ import numpy as np
6
+ import torch
7
+ from muse import MaskGiTUViT, VQGANModel
8
+ from muse import PipelineMuse as OldPipelineMuse
9
+ from transformers import CLIPTextModelWithProjection, CLIPTokenizer
10
+
11
+ from diffusers import VQModel
12
+ from diffusers.models.attention_processor import AttnProcessor
13
+ from diffusers.models.unets.uvit_2d import UVit2DModel
14
+ from diffusers.pipelines.amused.pipeline_amused import AmusedPipeline
15
+ from diffusers.schedulers import AmusedScheduler
16
+
17
+
18
+ torch.backends.cuda.enable_flash_sdp(False)
19
+ torch.backends.cuda.enable_mem_efficient_sdp(False)
20
+ torch.backends.cuda.enable_math_sdp(True)
21
+
22
+ os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
23
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8"
24
+ torch.use_deterministic_algorithms(True)
25
+
26
+ # Enable CUDNN deterministic mode
27
+ torch.backends.cudnn.deterministic = True
28
+ torch.backends.cudnn.benchmark = False
29
+ torch.backends.cuda.matmul.allow_tf32 = False
30
+
31
+ device = "cuda"
32
+
33
+
34
+ def main():
35
+ args = ArgumentParser()
36
+ args.add_argument("--model_256", action="store_true")
37
+ args.add_argument("--write_to", type=str, required=False, default=None)
38
+ args.add_argument("--transformer_path", type=str, required=False, default=None)
39
+ args = args.parse_args()
40
+
41
+ transformer_path = args.transformer_path
42
+ subfolder = "transformer"
43
+
44
+ if transformer_path is None:
45
+ if args.model_256:
46
+ transformer_path = "openMUSE/muse-256"
47
+ else:
48
+ transformer_path = (
49
+ "../research-run-512-checkpoints/research-run-512-with-downsample-checkpoint-554000/unwrapped_model/"
50
+ )
51
+ subfolder = None
52
+
53
+ old_transformer = MaskGiTUViT.from_pretrained(transformer_path, subfolder=subfolder)
54
+
55
+ old_transformer.to(device)
56
+
57
+ old_vae = VQGANModel.from_pretrained("openMUSE/muse-512", subfolder="vae")
58
+ old_vae.to(device)
59
+
60
+ vqvae = make_vqvae(old_vae)
61
+
62
+ tokenizer = CLIPTokenizer.from_pretrained("openMUSE/muse-512", subfolder="text_encoder")
63
+
64
+ text_encoder = CLIPTextModelWithProjection.from_pretrained("openMUSE/muse-512", subfolder="text_encoder")
65
+ text_encoder.to(device)
66
+
67
+ transformer = make_transformer(old_transformer, args.model_256)
68
+
69
+ scheduler = AmusedScheduler(mask_token_id=old_transformer.config.mask_token_id)
70
+
71
+ new_pipe = AmusedPipeline(
72
+ vqvae=vqvae, tokenizer=tokenizer, text_encoder=text_encoder, transformer=transformer, scheduler=scheduler
73
+ )
74
+
75
+ old_pipe = OldPipelineMuse(
76
+ vae=old_vae, transformer=old_transformer, text_encoder=text_encoder, tokenizer=tokenizer
77
+ )
78
+ old_pipe.to(device)
79
+
80
+ if args.model_256:
81
+ transformer_seq_len = 256
82
+ orig_size = (256, 256)
83
+ else:
84
+ transformer_seq_len = 1024
85
+ orig_size = (512, 512)
86
+
87
+ old_out = old_pipe(
88
+ "dog",
89
+ generator=torch.Generator(device).manual_seed(0),
90
+ transformer_seq_len=transformer_seq_len,
91
+ orig_size=orig_size,
92
+ timesteps=12,
93
+ )[0]
94
+
95
+ new_out = new_pipe("dog", generator=torch.Generator(device).manual_seed(0)).images[0]
96
+
97
+ old_out = np.array(old_out)
98
+ new_out = np.array(new_out)
99
+
100
+ diff = np.abs(old_out.astype(np.float64) - new_out.astype(np.float64))
101
+
102
+ # assert diff diff.sum() == 0
103
+ print("skipping pipeline full equivalence check")
104
+
105
+ print(f"max diff: {diff.max()}, diff.sum() / diff.size {diff.sum() / diff.size}")
106
+
107
+ if args.model_256:
108
+ assert diff.max() <= 3
109
+ assert diff.sum() / diff.size < 0.7
110
+ else:
111
+ assert diff.max() <= 1
112
+ assert diff.sum() / diff.size < 0.4
113
+
114
+ if args.write_to is not None:
115
+ new_pipe.save_pretrained(args.write_to)
116
+
117
+
118
+ def make_transformer(old_transformer, model_256):
119
+ args = dict(old_transformer.config)
120
+ force_down_up_sample = args["force_down_up_sample"]
121
+
122
+ signature = inspect.signature(UVit2DModel.__init__)
123
+
124
+ args_ = {
125
+ "downsample": force_down_up_sample,
126
+ "upsample": force_down_up_sample,
127
+ "block_out_channels": args["block_out_channels"][0],
128
+ "sample_size": 16 if model_256 else 32,
129
+ }
130
+
131
+ for s in list(signature.parameters.keys()):
132
+ if s in ["self", "downsample", "upsample", "sample_size", "block_out_channels"]:
133
+ continue
134
+
135
+ args_[s] = args[s]
136
+
137
+ new_transformer = UVit2DModel(**args_)
138
+ new_transformer.to(device)
139
+
140
+ new_transformer.set_attn_processor(AttnProcessor())
141
+
142
+ state_dict = old_transformer.state_dict()
143
+
144
+ state_dict["cond_embed.linear_1.weight"] = state_dict.pop("cond_embed.0.weight")
145
+ state_dict["cond_embed.linear_2.weight"] = state_dict.pop("cond_embed.2.weight")
146
+
147
+ for i in range(22):
148
+ state_dict[f"transformer_layers.{i}.norm1.norm.weight"] = state_dict.pop(
149
+ f"transformer_layers.{i}.attn_layer_norm.weight"
150
+ )
151
+ state_dict[f"transformer_layers.{i}.norm1.linear.weight"] = state_dict.pop(
152
+ f"transformer_layers.{i}.self_attn_adaLN_modulation.mapper.weight"
153
+ )
154
+
155
+ state_dict[f"transformer_layers.{i}.attn1.to_q.weight"] = state_dict.pop(
156
+ f"transformer_layers.{i}.attention.query.weight"
157
+ )
158
+ state_dict[f"transformer_layers.{i}.attn1.to_k.weight"] = state_dict.pop(
159
+ f"transformer_layers.{i}.attention.key.weight"
160
+ )
161
+ state_dict[f"transformer_layers.{i}.attn1.to_v.weight"] = state_dict.pop(
162
+ f"transformer_layers.{i}.attention.value.weight"
163
+ )
164
+ state_dict[f"transformer_layers.{i}.attn1.to_out.0.weight"] = state_dict.pop(
165
+ f"transformer_layers.{i}.attention.out.weight"
166
+ )
167
+
168
+ state_dict[f"transformer_layers.{i}.norm2.norm.weight"] = state_dict.pop(
169
+ f"transformer_layers.{i}.crossattn_layer_norm.weight"
170
+ )
171
+ state_dict[f"transformer_layers.{i}.norm2.linear.weight"] = state_dict.pop(
172
+ f"transformer_layers.{i}.cross_attn_adaLN_modulation.mapper.weight"
173
+ )
174
+
175
+ state_dict[f"transformer_layers.{i}.attn2.to_q.weight"] = state_dict.pop(
176
+ f"transformer_layers.{i}.crossattention.query.weight"
177
+ )
178
+ state_dict[f"transformer_layers.{i}.attn2.to_k.weight"] = state_dict.pop(
179
+ f"transformer_layers.{i}.crossattention.key.weight"
180
+ )
181
+ state_dict[f"transformer_layers.{i}.attn2.to_v.weight"] = state_dict.pop(
182
+ f"transformer_layers.{i}.crossattention.value.weight"
183
+ )
184
+ state_dict[f"transformer_layers.{i}.attn2.to_out.0.weight"] = state_dict.pop(
185
+ f"transformer_layers.{i}.crossattention.out.weight"
186
+ )
187
+
188
+ state_dict[f"transformer_layers.{i}.norm3.norm.weight"] = state_dict.pop(
189
+ f"transformer_layers.{i}.ffn.pre_mlp_layer_norm.weight"
190
+ )
191
+ state_dict[f"transformer_layers.{i}.norm3.linear.weight"] = state_dict.pop(
192
+ f"transformer_layers.{i}.ffn.adaLN_modulation.mapper.weight"
193
+ )
194
+
195
+ wi_0_weight = state_dict.pop(f"transformer_layers.{i}.ffn.wi_0.weight")
196
+ wi_1_weight = state_dict.pop(f"transformer_layers.{i}.ffn.wi_1.weight")
197
+ proj_weight = torch.concat([wi_1_weight, wi_0_weight], dim=0)
198
+ state_dict[f"transformer_layers.{i}.ff.net.0.proj.weight"] = proj_weight
199
+
200
+ state_dict[f"transformer_layers.{i}.ff.net.2.weight"] = state_dict.pop(f"transformer_layers.{i}.ffn.wo.weight")
201
+
202
+ if force_down_up_sample:
203
+ state_dict["down_block.downsample.norm.weight"] = state_dict.pop("down_blocks.0.downsample.0.norm.weight")
204
+ state_dict["down_block.downsample.conv.weight"] = state_dict.pop("down_blocks.0.downsample.1.weight")
205
+
206
+ state_dict["up_block.upsample.norm.weight"] = state_dict.pop("up_blocks.0.upsample.0.norm.weight")
207
+ state_dict["up_block.upsample.conv.weight"] = state_dict.pop("up_blocks.0.upsample.1.weight")
208
+
209
+ state_dict["mlm_layer.layer_norm.weight"] = state_dict.pop("mlm_layer.layer_norm.norm.weight")
210
+
211
+ for i in range(3):
212
+ state_dict[f"down_block.res_blocks.{i}.norm.weight"] = state_dict.pop(
213
+ f"down_blocks.0.res_blocks.{i}.norm.norm.weight"
214
+ )
215
+ state_dict[f"down_block.res_blocks.{i}.channelwise_linear_1.weight"] = state_dict.pop(
216
+ f"down_blocks.0.res_blocks.{i}.channelwise.0.weight"
217
+ )
218
+ state_dict[f"down_block.res_blocks.{i}.channelwise_norm.gamma"] = state_dict.pop(
219
+ f"down_blocks.0.res_blocks.{i}.channelwise.2.gamma"
220
+ )
221
+ state_dict[f"down_block.res_blocks.{i}.channelwise_norm.beta"] = state_dict.pop(
222
+ f"down_blocks.0.res_blocks.{i}.channelwise.2.beta"
223
+ )
224
+ state_dict[f"down_block.res_blocks.{i}.channelwise_linear_2.weight"] = state_dict.pop(
225
+ f"down_blocks.0.res_blocks.{i}.channelwise.4.weight"
226
+ )
227
+ state_dict[f"down_block.res_blocks.{i}.cond_embeds_mapper.weight"] = state_dict.pop(
228
+ f"down_blocks.0.res_blocks.{i}.adaLN_modulation.mapper.weight"
229
+ )
230
+
231
+ state_dict[f"down_block.attention_blocks.{i}.norm1.weight"] = state_dict.pop(
232
+ f"down_blocks.0.attention_blocks.{i}.attn_layer_norm.weight"
233
+ )
234
+ state_dict[f"down_block.attention_blocks.{i}.attn1.to_q.weight"] = state_dict.pop(
235
+ f"down_blocks.0.attention_blocks.{i}.attention.query.weight"
236
+ )
237
+ state_dict[f"down_block.attention_blocks.{i}.attn1.to_k.weight"] = state_dict.pop(
238
+ f"down_blocks.0.attention_blocks.{i}.attention.key.weight"
239
+ )
240
+ state_dict[f"down_block.attention_blocks.{i}.attn1.to_v.weight"] = state_dict.pop(
241
+ f"down_blocks.0.attention_blocks.{i}.attention.value.weight"
242
+ )
243
+ state_dict[f"down_block.attention_blocks.{i}.attn1.to_out.0.weight"] = state_dict.pop(
244
+ f"down_blocks.0.attention_blocks.{i}.attention.out.weight"
245
+ )
246
+
247
+ state_dict[f"down_block.attention_blocks.{i}.norm2.weight"] = state_dict.pop(
248
+ f"down_blocks.0.attention_blocks.{i}.crossattn_layer_norm.weight"
249
+ )
250
+ state_dict[f"down_block.attention_blocks.{i}.attn2.to_q.weight"] = state_dict.pop(
251
+ f"down_blocks.0.attention_blocks.{i}.crossattention.query.weight"
252
+ )
253
+ state_dict[f"down_block.attention_blocks.{i}.attn2.to_k.weight"] = state_dict.pop(
254
+ f"down_blocks.0.attention_blocks.{i}.crossattention.key.weight"
255
+ )
256
+ state_dict[f"down_block.attention_blocks.{i}.attn2.to_v.weight"] = state_dict.pop(
257
+ f"down_blocks.0.attention_blocks.{i}.crossattention.value.weight"
258
+ )
259
+ state_dict[f"down_block.attention_blocks.{i}.attn2.to_out.0.weight"] = state_dict.pop(
260
+ f"down_blocks.0.attention_blocks.{i}.crossattention.out.weight"
261
+ )
262
+
263
+ state_dict[f"up_block.res_blocks.{i}.norm.weight"] = state_dict.pop(
264
+ f"up_blocks.0.res_blocks.{i}.norm.norm.weight"
265
+ )
266
+ state_dict[f"up_block.res_blocks.{i}.channelwise_linear_1.weight"] = state_dict.pop(
267
+ f"up_blocks.0.res_blocks.{i}.channelwise.0.weight"
268
+ )
269
+ state_dict[f"up_block.res_blocks.{i}.channelwise_norm.gamma"] = state_dict.pop(
270
+ f"up_blocks.0.res_blocks.{i}.channelwise.2.gamma"
271
+ )
272
+ state_dict[f"up_block.res_blocks.{i}.channelwise_norm.beta"] = state_dict.pop(
273
+ f"up_blocks.0.res_blocks.{i}.channelwise.2.beta"
274
+ )
275
+ state_dict[f"up_block.res_blocks.{i}.channelwise_linear_2.weight"] = state_dict.pop(
276
+ f"up_blocks.0.res_blocks.{i}.channelwise.4.weight"
277
+ )
278
+ state_dict[f"up_block.res_blocks.{i}.cond_embeds_mapper.weight"] = state_dict.pop(
279
+ f"up_blocks.0.res_blocks.{i}.adaLN_modulation.mapper.weight"
280
+ )
281
+
282
+ state_dict[f"up_block.attention_blocks.{i}.norm1.weight"] = state_dict.pop(
283
+ f"up_blocks.0.attention_blocks.{i}.attn_layer_norm.weight"
284
+ )
285
+ state_dict[f"up_block.attention_blocks.{i}.attn1.to_q.weight"] = state_dict.pop(
286
+ f"up_blocks.0.attention_blocks.{i}.attention.query.weight"
287
+ )
288
+ state_dict[f"up_block.attention_blocks.{i}.attn1.to_k.weight"] = state_dict.pop(
289
+ f"up_blocks.0.attention_blocks.{i}.attention.key.weight"
290
+ )
291
+ state_dict[f"up_block.attention_blocks.{i}.attn1.to_v.weight"] = state_dict.pop(
292
+ f"up_blocks.0.attention_blocks.{i}.attention.value.weight"
293
+ )
294
+ state_dict[f"up_block.attention_blocks.{i}.attn1.to_out.0.weight"] = state_dict.pop(
295
+ f"up_blocks.0.attention_blocks.{i}.attention.out.weight"
296
+ )
297
+
298
+ state_dict[f"up_block.attention_blocks.{i}.norm2.weight"] = state_dict.pop(
299
+ f"up_blocks.0.attention_blocks.{i}.crossattn_layer_norm.weight"
300
+ )
301
+ state_dict[f"up_block.attention_blocks.{i}.attn2.to_q.weight"] = state_dict.pop(
302
+ f"up_blocks.0.attention_blocks.{i}.crossattention.query.weight"
303
+ )
304
+ state_dict[f"up_block.attention_blocks.{i}.attn2.to_k.weight"] = state_dict.pop(
305
+ f"up_blocks.0.attention_blocks.{i}.crossattention.key.weight"
306
+ )
307
+ state_dict[f"up_block.attention_blocks.{i}.attn2.to_v.weight"] = state_dict.pop(
308
+ f"up_blocks.0.attention_blocks.{i}.crossattention.value.weight"
309
+ )
310
+ state_dict[f"up_block.attention_blocks.{i}.attn2.to_out.0.weight"] = state_dict.pop(
311
+ f"up_blocks.0.attention_blocks.{i}.crossattention.out.weight"
312
+ )
313
+
314
+ for key in list(state_dict.keys()):
315
+ if key.startswith("up_blocks.0"):
316
+ key_ = "up_block." + ".".join(key.split(".")[2:])
317
+ state_dict[key_] = state_dict.pop(key)
318
+
319
+ if key.startswith("down_blocks.0"):
320
+ key_ = "down_block." + ".".join(key.split(".")[2:])
321
+ state_dict[key_] = state_dict.pop(key)
322
+
323
+ new_transformer.load_state_dict(state_dict)
324
+
325
+ input_ids = torch.randint(0, 10, (1, 32, 32), device=old_transformer.device)
326
+ encoder_hidden_states = torch.randn((1, 77, 768), device=old_transformer.device)
327
+ cond_embeds = torch.randn((1, 768), device=old_transformer.device)
328
+ micro_conds = torch.tensor([[512, 512, 0, 0, 6]], dtype=torch.float32, device=old_transformer.device)
329
+
330
+ old_out = old_transformer(input_ids.reshape(1, -1), encoder_hidden_states, cond_embeds, micro_conds)
331
+ old_out = old_out.reshape(1, 32, 32, 8192).permute(0, 3, 1, 2)
332
+
333
+ new_out = new_transformer(input_ids, encoder_hidden_states, cond_embeds, micro_conds)
334
+
335
+ # NOTE: these differences are solely due to using the geglu block that has a single linear layer of
336
+ # double output dimension instead of two different linear layers
337
+ max_diff = (old_out - new_out).abs().max()
338
+ total_diff = (old_out - new_out).abs().sum()
339
+ print(f"Transformer max_diff: {max_diff} total_diff: {total_diff}")
340
+ assert max_diff < 0.01
341
+ assert total_diff < 1500
342
+
343
+ return new_transformer
344
+
345
+
346
+ def make_vqvae(old_vae):
347
+ new_vae = VQModel(
348
+ act_fn="silu",
349
+ block_out_channels=[128, 256, 256, 512, 768],
350
+ down_block_types=[
351
+ "DownEncoderBlock2D",
352
+ "DownEncoderBlock2D",
353
+ "DownEncoderBlock2D",
354
+ "DownEncoderBlock2D",
355
+ "DownEncoderBlock2D",
356
+ ],
357
+ in_channels=3,
358
+ latent_channels=64,
359
+ layers_per_block=2,
360
+ norm_num_groups=32,
361
+ num_vq_embeddings=8192,
362
+ out_channels=3,
363
+ sample_size=32,
364
+ up_block_types=[
365
+ "UpDecoderBlock2D",
366
+ "UpDecoderBlock2D",
367
+ "UpDecoderBlock2D",
368
+ "UpDecoderBlock2D",
369
+ "UpDecoderBlock2D",
370
+ ],
371
+ mid_block_add_attention=False,
372
+ lookup_from_codebook=True,
373
+ )
374
+ new_vae.to(device)
375
+
376
+ # fmt: off
377
+
378
+ new_state_dict = {}
379
+
380
+ old_state_dict = old_vae.state_dict()
381
+
382
+ new_state_dict["encoder.conv_in.weight"] = old_state_dict.pop("encoder.conv_in.weight")
383
+ new_state_dict["encoder.conv_in.bias"] = old_state_dict.pop("encoder.conv_in.bias")
384
+
385
+ convert_vae_block_state_dict(old_state_dict, "encoder.down.0", new_state_dict, "encoder.down_blocks.0")
386
+ convert_vae_block_state_dict(old_state_dict, "encoder.down.1", new_state_dict, "encoder.down_blocks.1")
387
+ convert_vae_block_state_dict(old_state_dict, "encoder.down.2", new_state_dict, "encoder.down_blocks.2")
388
+ convert_vae_block_state_dict(old_state_dict, "encoder.down.3", new_state_dict, "encoder.down_blocks.3")
389
+ convert_vae_block_state_dict(old_state_dict, "encoder.down.4", new_state_dict, "encoder.down_blocks.4")
390
+
391
+ new_state_dict["encoder.mid_block.resnets.0.norm1.weight"] = old_state_dict.pop("encoder.mid.block_1.norm1.weight")
392
+ new_state_dict["encoder.mid_block.resnets.0.norm1.bias"] = old_state_dict.pop("encoder.mid.block_1.norm1.bias")
393
+ new_state_dict["encoder.mid_block.resnets.0.conv1.weight"] = old_state_dict.pop("encoder.mid.block_1.conv1.weight")
394
+ new_state_dict["encoder.mid_block.resnets.0.conv1.bias"] = old_state_dict.pop("encoder.mid.block_1.conv1.bias")
395
+ new_state_dict["encoder.mid_block.resnets.0.norm2.weight"] = old_state_dict.pop("encoder.mid.block_1.norm2.weight")
396
+ new_state_dict["encoder.mid_block.resnets.0.norm2.bias"] = old_state_dict.pop("encoder.mid.block_1.norm2.bias")
397
+ new_state_dict["encoder.mid_block.resnets.0.conv2.weight"] = old_state_dict.pop("encoder.mid.block_1.conv2.weight")
398
+ new_state_dict["encoder.mid_block.resnets.0.conv2.bias"] = old_state_dict.pop("encoder.mid.block_1.conv2.bias")
399
+ new_state_dict["encoder.mid_block.resnets.1.norm1.weight"] = old_state_dict.pop("encoder.mid.block_2.norm1.weight")
400
+ new_state_dict["encoder.mid_block.resnets.1.norm1.bias"] = old_state_dict.pop("encoder.mid.block_2.norm1.bias")
401
+ new_state_dict["encoder.mid_block.resnets.1.conv1.weight"] = old_state_dict.pop("encoder.mid.block_2.conv1.weight")
402
+ new_state_dict["encoder.mid_block.resnets.1.conv1.bias"] = old_state_dict.pop("encoder.mid.block_2.conv1.bias")
403
+ new_state_dict["encoder.mid_block.resnets.1.norm2.weight"] = old_state_dict.pop("encoder.mid.block_2.norm2.weight")
404
+ new_state_dict["encoder.mid_block.resnets.1.norm2.bias"] = old_state_dict.pop("encoder.mid.block_2.norm2.bias")
405
+ new_state_dict["encoder.mid_block.resnets.1.conv2.weight"] = old_state_dict.pop("encoder.mid.block_2.conv2.weight")
406
+ new_state_dict["encoder.mid_block.resnets.1.conv2.bias"] = old_state_dict.pop("encoder.mid.block_2.conv2.bias")
407
+ new_state_dict["encoder.conv_norm_out.weight"] = old_state_dict.pop("encoder.norm_out.weight")
408
+ new_state_dict["encoder.conv_norm_out.bias"] = old_state_dict.pop("encoder.norm_out.bias")
409
+ new_state_dict["encoder.conv_out.weight"] = old_state_dict.pop("encoder.conv_out.weight")
410
+ new_state_dict["encoder.conv_out.bias"] = old_state_dict.pop("encoder.conv_out.bias")
411
+ new_state_dict["quant_conv.weight"] = old_state_dict.pop("quant_conv.weight")
412
+ new_state_dict["quant_conv.bias"] = old_state_dict.pop("quant_conv.bias")
413
+ new_state_dict["quantize.embedding.weight"] = old_state_dict.pop("quantize.embedding.weight")
414
+ new_state_dict["post_quant_conv.weight"] = old_state_dict.pop("post_quant_conv.weight")
415
+ new_state_dict["post_quant_conv.bias"] = old_state_dict.pop("post_quant_conv.bias")
416
+ new_state_dict["decoder.conv_in.weight"] = old_state_dict.pop("decoder.conv_in.weight")
417
+ new_state_dict["decoder.conv_in.bias"] = old_state_dict.pop("decoder.conv_in.bias")
418
+ new_state_dict["decoder.mid_block.resnets.0.norm1.weight"] = old_state_dict.pop("decoder.mid.block_1.norm1.weight")
419
+ new_state_dict["decoder.mid_block.resnets.0.norm1.bias"] = old_state_dict.pop("decoder.mid.block_1.norm1.bias")
420
+ new_state_dict["decoder.mid_block.resnets.0.conv1.weight"] = old_state_dict.pop("decoder.mid.block_1.conv1.weight")
421
+ new_state_dict["decoder.mid_block.resnets.0.conv1.bias"] = old_state_dict.pop("decoder.mid.block_1.conv1.bias")
422
+ new_state_dict["decoder.mid_block.resnets.0.norm2.weight"] = old_state_dict.pop("decoder.mid.block_1.norm2.weight")
423
+ new_state_dict["decoder.mid_block.resnets.0.norm2.bias"] = old_state_dict.pop("decoder.mid.block_1.norm2.bias")
424
+ new_state_dict["decoder.mid_block.resnets.0.conv2.weight"] = old_state_dict.pop("decoder.mid.block_1.conv2.weight")
425
+ new_state_dict["decoder.mid_block.resnets.0.conv2.bias"] = old_state_dict.pop("decoder.mid.block_1.conv2.bias")
426
+ new_state_dict["decoder.mid_block.resnets.1.norm1.weight"] = old_state_dict.pop("decoder.mid.block_2.norm1.weight")
427
+ new_state_dict["decoder.mid_block.resnets.1.norm1.bias"] = old_state_dict.pop("decoder.mid.block_2.norm1.bias")
428
+ new_state_dict["decoder.mid_block.resnets.1.conv1.weight"] = old_state_dict.pop("decoder.mid.block_2.conv1.weight")
429
+ new_state_dict["decoder.mid_block.resnets.1.conv1.bias"] = old_state_dict.pop("decoder.mid.block_2.conv1.bias")
430
+ new_state_dict["decoder.mid_block.resnets.1.norm2.weight"] = old_state_dict.pop("decoder.mid.block_2.norm2.weight")
431
+ new_state_dict["decoder.mid_block.resnets.1.norm2.bias"] = old_state_dict.pop("decoder.mid.block_2.norm2.bias")
432
+ new_state_dict["decoder.mid_block.resnets.1.conv2.weight"] = old_state_dict.pop("decoder.mid.block_2.conv2.weight")
433
+ new_state_dict["decoder.mid_block.resnets.1.conv2.bias"] = old_state_dict.pop("decoder.mid.block_2.conv2.bias")
434
+
435
+ convert_vae_block_state_dict(old_state_dict, "decoder.up.0", new_state_dict, "decoder.up_blocks.4")
436
+ convert_vae_block_state_dict(old_state_dict, "decoder.up.1", new_state_dict, "decoder.up_blocks.3")
437
+ convert_vae_block_state_dict(old_state_dict, "decoder.up.2", new_state_dict, "decoder.up_blocks.2")
438
+ convert_vae_block_state_dict(old_state_dict, "decoder.up.3", new_state_dict, "decoder.up_blocks.1")
439
+ convert_vae_block_state_dict(old_state_dict, "decoder.up.4", new_state_dict, "decoder.up_blocks.0")
440
+
441
+ new_state_dict["decoder.conv_norm_out.weight"] = old_state_dict.pop("decoder.norm_out.weight")
442
+ new_state_dict["decoder.conv_norm_out.bias"] = old_state_dict.pop("decoder.norm_out.bias")
443
+ new_state_dict["decoder.conv_out.weight"] = old_state_dict.pop("decoder.conv_out.weight")
444
+ new_state_dict["decoder.conv_out.bias"] = old_state_dict.pop("decoder.conv_out.bias")
445
+
446
+ # fmt: on
447
+
448
+ assert len(old_state_dict.keys()) == 0
449
+
450
+ new_vae.load_state_dict(new_state_dict)
451
+
452
+ input = torch.randn((1, 3, 512, 512), device=device)
453
+ input = input.clamp(-1, 1)
454
+
455
+ old_encoder_output = old_vae.quant_conv(old_vae.encoder(input))
456
+ new_encoder_output = new_vae.quant_conv(new_vae.encoder(input))
457
+ assert (old_encoder_output == new_encoder_output).all()
458
+
459
+ old_decoder_output = old_vae.decoder(old_vae.post_quant_conv(old_encoder_output))
460
+ new_decoder_output = new_vae.decoder(new_vae.post_quant_conv(new_encoder_output))
461
+
462
+ # assert (old_decoder_output == new_decoder_output).all()
463
+ print("kipping vae decoder equivalence check")
464
+ print(f"vae decoder diff {(old_decoder_output - new_decoder_output).float().abs().sum()}")
465
+
466
+ old_output = old_vae(input)[0]
467
+ new_output = new_vae(input)[0]
468
+
469
+ # assert (old_output == new_output).all()
470
+ print("skipping full vae equivalence check")
471
+ print(f"vae full diff {(old_output - new_output).float().abs().sum()}")
472
+
473
+ return new_vae
474
+
475
+
476
+ def convert_vae_block_state_dict(old_state_dict, prefix_from, new_state_dict, prefix_to):
477
+ # fmt: off
478
+
479
+ new_state_dict[f"{prefix_to}.resnets.0.norm1.weight"] = old_state_dict.pop(f"{prefix_from}.block.0.norm1.weight")
480
+ new_state_dict[f"{prefix_to}.resnets.0.norm1.bias"] = old_state_dict.pop(f"{prefix_from}.block.0.norm1.bias")
481
+ new_state_dict[f"{prefix_to}.resnets.0.conv1.weight"] = old_state_dict.pop(f"{prefix_from}.block.0.conv1.weight")
482
+ new_state_dict[f"{prefix_to}.resnets.0.conv1.bias"] = old_state_dict.pop(f"{prefix_from}.block.0.conv1.bias")
483
+ new_state_dict[f"{prefix_to}.resnets.0.norm2.weight"] = old_state_dict.pop(f"{prefix_from}.block.0.norm2.weight")
484
+ new_state_dict[f"{prefix_to}.resnets.0.norm2.bias"] = old_state_dict.pop(f"{prefix_from}.block.0.norm2.bias")
485
+ new_state_dict[f"{prefix_to}.resnets.0.conv2.weight"] = old_state_dict.pop(f"{prefix_from}.block.0.conv2.weight")
486
+ new_state_dict[f"{prefix_to}.resnets.0.conv2.bias"] = old_state_dict.pop(f"{prefix_from}.block.0.conv2.bias")
487
+
488
+ if f"{prefix_from}.block.0.nin_shortcut.weight" in old_state_dict:
489
+ new_state_dict[f"{prefix_to}.resnets.0.conv_shortcut.weight"] = old_state_dict.pop(f"{prefix_from}.block.0.nin_shortcut.weight")
490
+ new_state_dict[f"{prefix_to}.resnets.0.conv_shortcut.bias"] = old_state_dict.pop(f"{prefix_from}.block.0.nin_shortcut.bias")
491
+
492
+ new_state_dict[f"{prefix_to}.resnets.1.norm1.weight"] = old_state_dict.pop(f"{prefix_from}.block.1.norm1.weight")
493
+ new_state_dict[f"{prefix_to}.resnets.1.norm1.bias"] = old_state_dict.pop(f"{prefix_from}.block.1.norm1.bias")
494
+ new_state_dict[f"{prefix_to}.resnets.1.conv1.weight"] = old_state_dict.pop(f"{prefix_from}.block.1.conv1.weight")
495
+ new_state_dict[f"{prefix_to}.resnets.1.conv1.bias"] = old_state_dict.pop(f"{prefix_from}.block.1.conv1.bias")
496
+ new_state_dict[f"{prefix_to}.resnets.1.norm2.weight"] = old_state_dict.pop(f"{prefix_from}.block.1.norm2.weight")
497
+ new_state_dict[f"{prefix_to}.resnets.1.norm2.bias"] = old_state_dict.pop(f"{prefix_from}.block.1.norm2.bias")
498
+ new_state_dict[f"{prefix_to}.resnets.1.conv2.weight"] = old_state_dict.pop(f"{prefix_from}.block.1.conv2.weight")
499
+ new_state_dict[f"{prefix_to}.resnets.1.conv2.bias"] = old_state_dict.pop(f"{prefix_from}.block.1.conv2.bias")
500
+
501
+ if f"{prefix_from}.downsample.conv.weight" in old_state_dict:
502
+ new_state_dict[f"{prefix_to}.downsamplers.0.conv.weight"] = old_state_dict.pop(f"{prefix_from}.downsample.conv.weight")
503
+ new_state_dict[f"{prefix_to}.downsamplers.0.conv.bias"] = old_state_dict.pop(f"{prefix_from}.downsample.conv.bias")
504
+
505
+ if f"{prefix_from}.upsample.conv.weight" in old_state_dict:
506
+ new_state_dict[f"{prefix_to}.upsamplers.0.conv.weight"] = old_state_dict.pop(f"{prefix_from}.upsample.conv.weight")
507
+ new_state_dict[f"{prefix_to}.upsamplers.0.conv.bias"] = old_state_dict.pop(f"{prefix_from}.upsample.conv.bias")
508
+
509
+ if f"{prefix_from}.block.2.norm1.weight" in old_state_dict:
510
+ new_state_dict[f"{prefix_to}.resnets.2.norm1.weight"] = old_state_dict.pop(f"{prefix_from}.block.2.norm1.weight")
511
+ new_state_dict[f"{prefix_to}.resnets.2.norm1.bias"] = old_state_dict.pop(f"{prefix_from}.block.2.norm1.bias")
512
+ new_state_dict[f"{prefix_to}.resnets.2.conv1.weight"] = old_state_dict.pop(f"{prefix_from}.block.2.conv1.weight")
513
+ new_state_dict[f"{prefix_to}.resnets.2.conv1.bias"] = old_state_dict.pop(f"{prefix_from}.block.2.conv1.bias")
514
+ new_state_dict[f"{prefix_to}.resnets.2.norm2.weight"] = old_state_dict.pop(f"{prefix_from}.block.2.norm2.weight")
515
+ new_state_dict[f"{prefix_to}.resnets.2.norm2.bias"] = old_state_dict.pop(f"{prefix_from}.block.2.norm2.bias")
516
+ new_state_dict[f"{prefix_to}.resnets.2.conv2.weight"] = old_state_dict.pop(f"{prefix_from}.block.2.conv2.weight")
517
+ new_state_dict[f"{prefix_to}.resnets.2.conv2.bias"] = old_state_dict.pop(f"{prefix_from}.block.2.conv2.bias")
518
+
519
+ # fmt: on
520
+
521
+
522
+ if __name__ == "__main__":
523
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_anima_to_diffusers.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert Anima checkpoints to Diffusers format.
3
+
4
+ Example:
5
+ ```bash
6
+ python scripts/convert_anima_to_diffusers.py \
7
+ --transformer_ckpt_path anima_model/anima-preview3-base.safetensors \
8
+ --text_encoder_ckpt_path anima_model/qwen_3_06b_base.safetensors \
9
+ --vae_ckpt_path anima_model/qwen_image_vae.safetensors \
10
+ --qwen_tokenizer_path path/to/qwen25_tokenizer \
11
+ --t5_tokenizer_path path/to/t5_tokenizer \
12
+ --output_path anima_model/anima-preview3-diffusers \
13
+ --save_pipeline
14
+ ```
15
+ """
16
+
17
+ import argparse
18
+ import pathlib
19
+ import sys
20
+ from typing import Any
21
+
22
+ import torch
23
+ from accelerate import init_empty_weights
24
+ from convert_cosmos_to_diffusers import convert_transformer
25
+ from safetensors.torch import load_file
26
+ from transformers import AutoTokenizer, Qwen3Config, Qwen3Model, T5TokenizerFast
27
+
28
+ from diffusers import (
29
+ AnimaAutoBlocks,
30
+ AnimaTextConditioner,
31
+ AutoencoderKLQwenImage,
32
+ FlowMatchEulerDiscreteScheduler,
33
+ )
34
+
35
+
36
+ DTYPE_MAPPING = {
37
+ "fp32": torch.float32,
38
+ "fp16": torch.float16,
39
+ "bf16": torch.bfloat16,
40
+ }
41
+
42
+
43
+ def rename_residual_key(key: str) -> str:
44
+ replacements = {
45
+ ".residual.0.": ".norm1.",
46
+ ".residual.2.": ".conv1.",
47
+ ".residual.3.": ".norm2.",
48
+ ".residual.6.": ".conv2.",
49
+ ".shortcut.": ".conv_shortcut.",
50
+ }
51
+ for old, new in replacements.items():
52
+ key = key.replace(old, new)
53
+ return key
54
+
55
+
56
+ def rename_mid_key(key: str) -> str:
57
+ replacements = {
58
+ ".middle.0.": ".mid_block.resnets.0.",
59
+ ".middle.1.": ".mid_block.attentions.0.",
60
+ ".middle.2.": ".mid_block.resnets.1.",
61
+ }
62
+ for old, new in replacements.items():
63
+ key = key.replace(old, new)
64
+ return rename_residual_key(key)
65
+
66
+
67
+ def rename_decoder_upsample_key(key: str) -> str:
68
+ prefix = "decoder.upsamples."
69
+ suffix = key.removeprefix(prefix)
70
+ index_str, rest = suffix.split(".", 1)
71
+ index = int(index_str)
72
+
73
+ if index in (3, 7, 11):
74
+ block_index = (index - 3) // 4
75
+ new_key = f"decoder.up_blocks.{block_index}.upsamplers.0.{rest}"
76
+ else:
77
+ block_index = index // 4
78
+ resnet_index = index % 4
79
+ new_key = f"decoder.up_blocks.{block_index}.resnets.{resnet_index}.{rest}"
80
+
81
+ return rename_residual_key(new_key)
82
+
83
+
84
+ def convert_qwen_image_vae_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
85
+ converted_state_dict = {}
86
+ for key, value in state_dict.items():
87
+ if key.startswith("conv1."):
88
+ new_key = key.replace("conv1.", "quant_conv.", 1)
89
+ elif key.startswith("conv2."):
90
+ new_key = key.replace("conv2.", "post_quant_conv.", 1)
91
+ elif key.startswith("encoder.conv1."):
92
+ new_key = key.replace("encoder.conv1.", "encoder.conv_in.", 1)
93
+ elif key.startswith("decoder.conv1."):
94
+ new_key = key.replace("decoder.conv1.", "decoder.conv_in.", 1)
95
+ elif key.startswith("encoder.downsamples."):
96
+ new_key = rename_residual_key(key.replace("encoder.downsamples.", "encoder.down_blocks.", 1))
97
+ elif key.startswith("decoder.upsamples."):
98
+ new_key = rename_decoder_upsample_key(key)
99
+ elif key.startswith("encoder.middle.") or key.startswith("decoder.middle."):
100
+ new_key = rename_mid_key(key)
101
+ elif key.startswith("encoder.head.0."):
102
+ new_key = key.replace("encoder.head.0.", "encoder.norm_out.", 1)
103
+ elif key.startswith("encoder.head.2."):
104
+ new_key = key.replace("encoder.head.2.", "encoder.conv_out.", 1)
105
+ elif key.startswith("decoder.head.0."):
106
+ new_key = key.replace("decoder.head.0.", "decoder.norm_out.", 1)
107
+ elif key.startswith("decoder.head.2."):
108
+ new_key = key.replace("decoder.head.2.", "decoder.conv_out.", 1)
109
+ else:
110
+ new_key = rename_residual_key(key)
111
+
112
+ if new_key in converted_state_dict:
113
+ raise ValueError(f"Duplicate converted VAE key: {new_key}")
114
+ converted_state_dict[new_key] = value
115
+
116
+ return converted_state_dict
117
+
118
+
119
+ def convert_qwen_image_vae(state_dict: dict[str, torch.Tensor]) -> AutoencoderKLQwenImage:
120
+ converted_state_dict = convert_qwen_image_vae_state_dict(state_dict)
121
+ with init_empty_weights():
122
+ vae = AutoencoderKLQwenImage()
123
+
124
+ expected_keys = set(vae.state_dict().keys())
125
+ converted_keys = set(converted_state_dict.keys())
126
+ missing_keys = expected_keys - converted_keys
127
+ unexpected_keys = converted_keys - expected_keys
128
+ if missing_keys or unexpected_keys:
129
+ if missing_keys:
130
+ print(f"ERROR: missing VAE keys ({len(missing_keys)}):", file=sys.stderr)
131
+ for key in sorted(missing_keys):
132
+ print(key, file=sys.stderr)
133
+ if unexpected_keys:
134
+ print(f"ERROR: unexpected VAE keys ({len(unexpected_keys)}):", file=sys.stderr)
135
+ for key in sorted(unexpected_keys):
136
+ print(key, file=sys.stderr)
137
+ sys.exit(1)
138
+
139
+ vae.load_state_dict(converted_state_dict, strict=True, assign=True)
140
+ return vae
141
+
142
+
143
+ def infer_text_conditioner_config(state_dict: dict[str, torch.Tensor]) -> dict[str, Any]:
144
+ model_dim = state_dict["blocks.0.self_attn.q_proj.weight"].shape[0]
145
+ source_dim = state_dict["blocks.0.cross_attn.k_proj.weight"].shape[1]
146
+ target_vocab_size, target_dim = state_dict["embed.weight"].shape
147
+ attention_head_dim = state_dict["blocks.0.self_attn.q_norm.weight"].shape[0]
148
+ num_layers = 1 + max(int(key.split(".")[1]) for key in state_dict if key.startswith("blocks."))
149
+
150
+ return {
151
+ "source_dim": source_dim,
152
+ "target_dim": target_dim,
153
+ "model_dim": model_dim,
154
+ "num_layers": num_layers,
155
+ "num_attention_heads": model_dim // attention_head_dim,
156
+ "target_vocab_size": target_vocab_size,
157
+ }
158
+
159
+
160
+ def convert_text_conditioner(state_dict: dict[str, torch.Tensor]) -> AnimaTextConditioner:
161
+ config = infer_text_conditioner_config(state_dict)
162
+ with init_empty_weights():
163
+ text_conditioner = AnimaTextConditioner(**config)
164
+
165
+ expected_keys = set(text_conditioner.state_dict().keys())
166
+ converted_keys = set(state_dict.keys())
167
+ missing_keys = expected_keys - converted_keys
168
+ unexpected_keys = converted_keys - expected_keys
169
+ if missing_keys or unexpected_keys:
170
+ if missing_keys:
171
+ print(f"ERROR: missing text conditioner keys ({len(missing_keys)}):", file=sys.stderr)
172
+ for key in sorted(missing_keys):
173
+ print(key, file=sys.stderr)
174
+ if unexpected_keys:
175
+ print(f"ERROR: unexpected text conditioner keys ({len(unexpected_keys)}):", file=sys.stderr)
176
+ for key in sorted(unexpected_keys):
177
+ print(key, file=sys.stderr)
178
+ sys.exit(1)
179
+
180
+ text_conditioner.load_state_dict(state_dict, strict=True, assign=True)
181
+ return text_conditioner
182
+
183
+
184
+ def infer_qwen3_config(state_dict: dict[str, torch.Tensor]) -> Qwen3Config:
185
+ vocab_size, hidden_size = state_dict["embed_tokens.weight"].shape
186
+ intermediate_size = state_dict["layers.0.mlp.gate_proj.weight"].shape[0]
187
+ num_hidden_layers = 1 + max(int(key.split(".")[1]) for key in state_dict if key.startswith("layers."))
188
+ head_dim = state_dict["layers.0.self_attn.q_norm.weight"].shape[0]
189
+ num_attention_heads = state_dict["layers.0.self_attn.q_proj.weight"].shape[0] // head_dim
190
+ num_key_value_heads = state_dict["layers.0.self_attn.k_proj.weight"].shape[0] // head_dim
191
+
192
+ return Qwen3Config(
193
+ vocab_size=vocab_size,
194
+ hidden_size=hidden_size,
195
+ intermediate_size=intermediate_size,
196
+ num_hidden_layers=num_hidden_layers,
197
+ num_attention_heads=num_attention_heads,
198
+ num_key_value_heads=num_key_value_heads,
199
+ max_position_embeddings=32768,
200
+ rms_norm_eps=1e-6,
201
+ rope_theta=1000000.0,
202
+ head_dim=head_dim,
203
+ attention_bias=False,
204
+ tie_word_embeddings=False,
205
+ )
206
+
207
+
208
+ def convert_text_encoder(state_dict: dict[str, torch.Tensor]) -> Qwen3Model:
209
+ state_dict = {key.removeprefix("model."): value for key, value in state_dict.items()}
210
+ config = infer_qwen3_config(state_dict)
211
+ with init_empty_weights():
212
+ text_encoder = Qwen3Model(config)
213
+
214
+ expected_keys = set(text_encoder.state_dict().keys())
215
+ converted_keys = set(state_dict.keys())
216
+ missing_keys = expected_keys - converted_keys
217
+ unexpected_keys = converted_keys - expected_keys
218
+ if missing_keys or unexpected_keys:
219
+ if missing_keys:
220
+ print(f"ERROR: missing Qwen3 keys ({len(missing_keys)}):", file=sys.stderr)
221
+ for key in sorted(missing_keys):
222
+ print(key, file=sys.stderr)
223
+ if unexpected_keys:
224
+ print(f"ERROR: unexpected Qwen3 keys ({len(unexpected_keys)}):", file=sys.stderr)
225
+ for key in sorted(unexpected_keys):
226
+ print(key, file=sys.stderr)
227
+ sys.exit(1)
228
+
229
+ text_encoder.load_state_dict(state_dict, strict=True, assign=True)
230
+ return text_encoder
231
+
232
+
233
+ def split_anima_transformer_checkpoint(
234
+ state_dict: dict[str, torch.Tensor],
235
+ ) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
236
+ transformer_state_dict = {}
237
+ text_conditioner_state_dict = {}
238
+ adapter_prefix = "net.llm_adapter."
239
+
240
+ for key, value in state_dict.items():
241
+ if key.startswith(adapter_prefix):
242
+ text_conditioner_state_dict[key.removeprefix(adapter_prefix)] = value
243
+ else:
244
+ transformer_state_dict[key] = value
245
+
246
+ return transformer_state_dict, text_conditioner_state_dict
247
+
248
+
249
+ def save_pipeline(args, transformer, text_conditioner, text_encoder, vae):
250
+ tokenizer = AutoTokenizer.from_pretrained(args.qwen_tokenizer_path)
251
+ t5_tokenizer = T5TokenizerFast.from_pretrained(args.t5_tokenizer_path)
252
+ scheduler = FlowMatchEulerDiscreteScheduler(shift=3.0)
253
+
254
+ pipe = AnimaAutoBlocks().init_pipeline()
255
+ pipe.update_components(
256
+ text_encoder=text_encoder,
257
+ tokenizer=tokenizer,
258
+ t5_tokenizer=t5_tokenizer,
259
+ text_conditioner=text_conditioner,
260
+ transformer=transformer,
261
+ vae=vae,
262
+ scheduler=scheduler,
263
+ )
264
+ pipe.save_pretrained(args.output_path, safe_serialization=True, max_shard_size=args.max_shard_size)
265
+
266
+
267
+ def get_args():
268
+ parser = argparse.ArgumentParser()
269
+ parser.add_argument("--transformer_ckpt_path", type=str, required=True, help="Path to Anima DiT safetensors")
270
+ parser.add_argument("--text_encoder_ckpt_path", type=str, required=True, help="Path to Qwen3 text encoder")
271
+ parser.add_argument("--vae_ckpt_path", type=str, required=True, help="Path to Qwen-Image VAE safetensors")
272
+ parser.add_argument("--qwen_tokenizer_path", type=str, default=None)
273
+ parser.add_argument("--t5_tokenizer_path", type=str, default=None)
274
+ parser.add_argument("--output_path", type=str, required=True)
275
+ parser.add_argument("--save_pipeline", action="store_true")
276
+ parser.add_argument("--dtype", default="bf16", choices=list(DTYPE_MAPPING.keys()))
277
+ parser.add_argument("--max_shard_size", default="5GB")
278
+ return parser.parse_args()
279
+
280
+
281
+ if __name__ == "__main__":
282
+ args = get_args()
283
+ output_path = pathlib.Path(args.output_path)
284
+ dtype = DTYPE_MAPPING[args.dtype]
285
+
286
+ raw_transformer_state_dict = load_file(args.transformer_ckpt_path, device="cpu")
287
+ transformer_state_dict, text_conditioner_state_dict = split_anima_transformer_checkpoint(
288
+ raw_transformer_state_dict
289
+ )
290
+ transformer = convert_transformer(
291
+ "Cosmos-2.0-Diffusion-2B-Text2Image", state_dict=transformer_state_dict, weights_only=True
292
+ ).to(dtype=dtype)
293
+ text_conditioner = convert_text_conditioner(text_conditioner_state_dict).to(dtype=dtype)
294
+
295
+ text_encoder_state_dict = load_file(args.text_encoder_ckpt_path, device="cpu")
296
+ text_encoder = convert_text_encoder(text_encoder_state_dict).to(dtype=dtype)
297
+
298
+ vae_state_dict = load_file(args.vae_ckpt_path, device="cpu")
299
+ vae = convert_qwen_image_vae(vae_state_dict).to(dtype=dtype)
300
+
301
+ if args.save_pipeline:
302
+ if args.qwen_tokenizer_path is None or args.t5_tokenizer_path is None:
303
+ raise ValueError("`--qwen_tokenizer_path` and `--t5_tokenizer_path` are required with `--save_pipeline`.")
304
+ save_pipeline(args, transformer, text_conditioner, text_encoder, vae)
305
+ else:
306
+ output_path.mkdir(parents=True, exist_ok=True)
307
+ transformer.save_pretrained(
308
+ output_path / "transformer", safe_serialization=True, max_shard_size=args.max_shard_size
309
+ )
310
+ text_conditioner.save_pretrained(
311
+ output_path / "text_conditioner", safe_serialization=True, max_shard_size=args.max_shard_size
312
+ )
313
+ text_encoder.save_pretrained(
314
+ output_path / "text_encoder", safe_serialization=True, max_shard_size=args.max_shard_size
315
+ )
316
+ vae.save_pretrained(output_path / "vae", safe_serialization=True, max_shard_size=args.max_shard_size)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_motion_lora_to_diffusers.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import torch
5
+ from huggingface_hub import create_repo, upload_folder
6
+ from safetensors.torch import load_file, save_file
7
+
8
+
9
+ def convert_motion_module(original_state_dict):
10
+ converted_state_dict = {}
11
+ for k, v in original_state_dict.items():
12
+ if "pos_encoder" in k:
13
+ continue
14
+
15
+ else:
16
+ converted_state_dict[
17
+ k.replace(".norms.0", ".norm1")
18
+ .replace(".norms.1", ".norm2")
19
+ .replace(".ff_norm", ".norm3")
20
+ .replace(".attention_blocks.0", ".attn1")
21
+ .replace(".attention_blocks.1", ".attn2")
22
+ .replace(".temporal_transformer", "")
23
+ ] = v
24
+
25
+ return converted_state_dict
26
+
27
+
28
+ def get_args():
29
+ parser = argparse.ArgumentParser()
30
+ parser.add_argument("--ckpt_path", type=str, required=True, help="Path to checkpoint")
31
+ parser.add_argument("--output_path", type=str, required=True, help="Path to output directory")
32
+ parser.add_argument(
33
+ "--push_to_hub",
34
+ action="store_true",
35
+ default=False,
36
+ help="Whether to push the converted model to the HF or not",
37
+ )
38
+
39
+ return parser.parse_args()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ args = get_args()
44
+
45
+ if args.ckpt_path.endswith(".safetensors"):
46
+ state_dict = load_file(args.ckpt_path)
47
+ else:
48
+ state_dict = torch.load(args.ckpt_path, map_location="cpu")
49
+
50
+ if "state_dict" in state_dict.keys():
51
+ state_dict = state_dict["state_dict"]
52
+
53
+ conv_state_dict = convert_motion_module(state_dict)
54
+
55
+ # convert to new format
56
+ output_dict = {}
57
+ for module_name, params in conv_state_dict.items():
58
+ if type(params) is not torch.Tensor:
59
+ continue
60
+ output_dict.update({f"unet.{module_name}": params})
61
+
62
+ os.makedirs(args.output_path, exist_ok=True)
63
+
64
+ filepath = os.path.join(args.output_path, "diffusion_pytorch_model.safetensors")
65
+ save_file(output_dict, filepath)
66
+
67
+ if args.push_to_hub:
68
+ repo_id = create_repo(args.output_path, exist_ok=True).repo_id
69
+ upload_folder(repo_id=repo_id, folder_path=args.output_path, repo_type="model")
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_motion_module_to_diffusers.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch
4
+ from safetensors.torch import load_file
5
+
6
+ from diffusers import MotionAdapter
7
+
8
+
9
+ def convert_motion_module(original_state_dict):
10
+ converted_state_dict = {}
11
+ for k, v in original_state_dict.items():
12
+ if "pos_encoder" in k:
13
+ continue
14
+
15
+ else:
16
+ converted_state_dict[
17
+ k.replace(".norms.0", ".norm1")
18
+ .replace(".norms.1", ".norm2")
19
+ .replace(".ff_norm", ".norm3")
20
+ .replace(".attention_blocks.0", ".attn1")
21
+ .replace(".attention_blocks.1", ".attn2")
22
+ .replace(".temporal_transformer", "")
23
+ ] = v
24
+
25
+ return converted_state_dict
26
+
27
+
28
+ def get_args():
29
+ parser = argparse.ArgumentParser()
30
+ parser.add_argument("--ckpt_path", type=str, required=True)
31
+ parser.add_argument("--output_path", type=str, required=True)
32
+ parser.add_argument("--use_motion_mid_block", action="store_true")
33
+ parser.add_argument("--motion_max_seq_length", type=int, default=32)
34
+ parser.add_argument("--block_out_channels", nargs="+", default=[320, 640, 1280, 1280], type=int)
35
+ parser.add_argument("--save_fp16", action="store_true")
36
+
37
+ return parser.parse_args()
38
+
39
+
40
+ if __name__ == "__main__":
41
+ args = get_args()
42
+
43
+ if args.ckpt_path.endswith(".safetensors"):
44
+ state_dict = load_file(args.ckpt_path)
45
+ else:
46
+ state_dict = torch.load(args.ckpt_path, map_location="cpu")
47
+
48
+ if "state_dict" in state_dict.keys():
49
+ state_dict = state_dict["state_dict"]
50
+
51
+ conv_state_dict = convert_motion_module(state_dict)
52
+ adapter = MotionAdapter(
53
+ block_out_channels=args.block_out_channels,
54
+ use_motion_mid_block=args.use_motion_mid_block,
55
+ motion_max_seq_length=args.motion_max_seq_length,
56
+ )
57
+ # skip loading position embeddings
58
+ adapter.load_state_dict(conv_state_dict, strict=False)
59
+ adapter.save_pretrained(args.output_path)
60
+
61
+ if args.save_fp16:
62
+ adapter.to(dtype=torch.float16).save_pretrained(args.output_path, variant="fp16")
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_animatediff_sparsectrl_to_diffusers.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from typing import Dict
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from diffusers import SparseControlNetModel
8
+
9
+
10
+ KEYS_RENAME_MAPPING = {
11
+ ".attention_blocks.0": ".attn1",
12
+ ".attention_blocks.1": ".attn2",
13
+ ".attn1.pos_encoder": ".pos_embed",
14
+ ".ff_norm": ".norm3",
15
+ ".norms.0": ".norm1",
16
+ ".norms.1": ".norm2",
17
+ ".temporal_transformer": "",
18
+ }
19
+
20
+
21
+ def convert(original_state_dict: Dict[str, nn.Module]) -> dict[str, nn.Module]:
22
+ converted_state_dict = {}
23
+
24
+ for key in list(original_state_dict.keys()):
25
+ renamed_key = key
26
+ for new_name, old_name in KEYS_RENAME_MAPPING.items():
27
+ renamed_key = renamed_key.replace(new_name, old_name)
28
+ converted_state_dict[renamed_key] = original_state_dict.pop(key)
29
+
30
+ return converted_state_dict
31
+
32
+
33
+ def get_args():
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument("--ckpt_path", type=str, required=True, help="Path to checkpoint")
36
+ parser.add_argument("--output_path", type=str, required=True, help="Path to output directory")
37
+ parser.add_argument(
38
+ "--max_motion_seq_length",
39
+ type=int,
40
+ default=32,
41
+ help="Max motion sequence length supported by the motion adapter",
42
+ )
43
+ parser.add_argument(
44
+ "--conditioning_channels", type=int, default=4, help="Number of channels in conditioning input to controlnet"
45
+ )
46
+ parser.add_argument(
47
+ "--use_simplified_condition_embedding",
48
+ action="store_true",
49
+ default=False,
50
+ help="Whether or not to use simplified condition embedding. When `conditioning_channels==4` i.e. latent inputs, set this to `True`. When `conditioning_channels==3` i.e. image inputs, set this to `False`",
51
+ )
52
+ parser.add_argument(
53
+ "--save_fp16",
54
+ action="store_true",
55
+ default=False,
56
+ help="Whether or not to save model in fp16 precision along with fp32",
57
+ )
58
+ parser.add_argument(
59
+ "--push_to_hub", action="store_true", default=False, help="Whether or not to push saved model to the HF hub"
60
+ )
61
+ return parser.parse_args()
62
+
63
+
64
+ if __name__ == "__main__":
65
+ args = get_args()
66
+
67
+ state_dict = torch.load(args.ckpt_path, map_location="cpu")
68
+ if "state_dict" in state_dict.keys():
69
+ state_dict: dict = state_dict["state_dict"]
70
+
71
+ controlnet = SparseControlNetModel(
72
+ conditioning_channels=args.conditioning_channels,
73
+ motion_max_seq_length=args.max_motion_seq_length,
74
+ use_simplified_condition_embedding=args.use_simplified_condition_embedding,
75
+ )
76
+
77
+ state_dict = convert(state_dict)
78
+ controlnet.load_state_dict(state_dict, strict=True)
79
+
80
+ controlnet.save_pretrained(args.output_path, push_to_hub=args.push_to_hub)
81
+ if args.save_fp16:
82
+ controlnet = controlnet.to(dtype=torch.float16)
83
+ controlnet.save_pretrained(args.output_path, variant="fp16", push_to_hub=args.push_to_hub)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_anyflow_to_diffusers.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The AnyFlow Team, NVIDIA Corp., and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Convert AnyFlow training checkpoints to the diffusers ``save_pretrained`` layout.
16
+
17
+ The AnyFlow training pipeline emits ``.pt`` files containing an ``ema`` key whose value is a flat state
18
+ dict for the transformer. This script:
19
+
20
+ 1. Loads the matching base Wan2.1 pipeline from the Hub (provides VAE, tokenizer, and text encoder).
21
+ 2. Constructs an ``AnyFlowTransformer3DModel`` with the right config flags for the chosen variant.
22
+ 3. Loads the ``ema`` weights into the transformer.
23
+ 4. Wraps everything in an ``AnyFlowPipeline`` (bidirectional) or ``AnyFlowFARPipeline`` (FAR causal).
24
+ 5. Calls ``pipeline.save_pretrained(output_dir)``.
25
+
26
+ Example:
27
+
28
+ ```bash
29
+ python scripts/convert_anyflow_to_diffusers.py \\
30
+ --variant AnyFlow-FAR-Wan2.1-1.3B-Diffusers \\
31
+ --ckpt /path/to/anyflow-checkpoint.pt \\
32
+ --output-dir /path/to/output/AnyFlow-FAR-Wan2.1-1.3B-Diffusers
33
+ ```
34
+ """
35
+
36
+ import argparse
37
+ import logging
38
+ import os
39
+
40
+ import torch
41
+
42
+ from diffusers import (
43
+ AnyFlowFARPipeline,
44
+ AnyFlowFARTransformer3DModel,
45
+ AnyFlowPipeline,
46
+ AnyFlowTransformer3DModel,
47
+ FlowMapEulerDiscreteScheduler,
48
+ )
49
+
50
+
51
+ logger = logging.getLogger(__name__)
52
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
53
+
54
+
55
+ # Per-variant configuration. ``base_model`` is fetched from the Hub to source the matching VAE / text encoder.
56
+ VARIANTS = {
57
+ "AnyFlow-FAR-Wan2.1-1.3B-Diffusers": {
58
+ "base_model": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
59
+ "transformer_cls": AnyFlowFARTransformer3DModel,
60
+ "transformer_kwargs": {
61
+ "full_chunk_limit": 3,
62
+ "compressed_patch_size": [1, 4, 4],
63
+ "chunk_partition": [1, 3, 3, 3, 3, 3, 3, 2],
64
+ },
65
+ "pipeline_cls": AnyFlowFARPipeline,
66
+ },
67
+ "AnyFlow-FAR-Wan2.1-14B-Diffusers": {
68
+ "base_model": "Wan-AI/Wan2.1-T2V-14B-Diffusers",
69
+ "transformer_cls": AnyFlowFARTransformer3DModel,
70
+ "transformer_kwargs": {
71
+ "full_chunk_limit": 3,
72
+ "compressed_patch_size": [1, 4, 4],
73
+ "chunk_partition": [1, 3, 3, 3, 3, 3, 3, 2],
74
+ },
75
+ "pipeline_cls": AnyFlowFARPipeline,
76
+ },
77
+ "AnyFlow-Wan2.1-T2V-1.3B-Diffusers": {
78
+ "base_model": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
79
+ "transformer_cls": AnyFlowTransformer3DModel,
80
+ "transformer_kwargs": {},
81
+ "pipeline_cls": AnyFlowPipeline,
82
+ },
83
+ "AnyFlow-Wan2.1-T2V-14B-Diffusers": {
84
+ "base_model": "Wan-AI/Wan2.1-T2V-14B-Diffusers",
85
+ "transformer_cls": AnyFlowTransformer3DModel,
86
+ "transformer_kwargs": {},
87
+ "pipeline_cls": AnyFlowPipeline,
88
+ },
89
+ }
90
+
91
+
92
+ def build_pipeline(variant: str, ckpt_path: str):
93
+ if variant not in VARIANTS:
94
+ raise ValueError(f"Unknown variant {variant!r}. Choices: {list(VARIANTS)}.")
95
+ spec = VARIANTS[variant]
96
+
97
+ transformer = spec["transformer_cls"].from_pretrained(
98
+ spec["base_model"],
99
+ subfolder="transformer",
100
+ gate_value=0.25,
101
+ deltatime_type="r",
102
+ **spec["transformer_kwargs"],
103
+ )
104
+ # NVlabs/AnyFlow training checkpoints are wrapped Python objects (the `ema` key carries metadata
105
+ # alongside tensors), so the unpickle is required. Only run this script on checkpoints you trust.
106
+ state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=False)["ema"]
107
+ missing, unexpected = transformer.load_state_dict(state_dict, strict=False)
108
+ if unexpected:
109
+ logger.warning(
110
+ "Unexpected keys in state dict (ignored): %s%s",
111
+ unexpected[:5],
112
+ "..." if len(unexpected) > 5 else "",
113
+ )
114
+ if missing:
115
+ logger.warning(
116
+ "Missing keys not loaded from state dict: %s%s",
117
+ missing[:5],
118
+ "..." if len(missing) > 5 else "",
119
+ )
120
+
121
+ scheduler = FlowMapEulerDiscreteScheduler(num_train_timesteps=1000, shift=5.0)
122
+
123
+ pipeline = spec["pipeline_cls"].from_pretrained(
124
+ spec["base_model"],
125
+ transformer=transformer,
126
+ scheduler=scheduler,
127
+ )
128
+ return pipeline
129
+
130
+
131
+ def main():
132
+ parser = argparse.ArgumentParser(
133
+ description="Convert an AnyFlow training checkpoint into a diffusers pipeline directory."
134
+ )
135
+ parser.add_argument(
136
+ "--variant",
137
+ required=True,
138
+ choices=list(VARIANTS),
139
+ help="Which AnyFlow variant the checkpoint corresponds to.",
140
+ )
141
+ parser.add_argument(
142
+ "--ckpt",
143
+ required=True,
144
+ help="Path to the AnyFlow training checkpoint (a .pt file containing an 'ema' key).",
145
+ )
146
+ parser.add_argument(
147
+ "--output-dir",
148
+ required=True,
149
+ help="Destination directory for pipeline.save_pretrained.",
150
+ )
151
+ args = parser.parse_args()
152
+
153
+ os.makedirs(args.output_dir, exist_ok=True)
154
+ pipeline = build_pipeline(args.variant, args.ckpt)
155
+ pipeline.save_pretrained(args.output_dir)
156
+ logger.info("Saved %s pipeline to %s", args.variant, args.output_dir)
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_asymmetric_vqgan_to_diffusers.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Any, Dict, Literal
5
+
6
+ import torch
7
+
8
+ from diffusers import AsymmetricAutoencoderKL
9
+
10
+
11
+ ASYMMETRIC_AUTOENCODER_KL_x_1_5_CONFIG = {
12
+ "in_channels": 3,
13
+ "out_channels": 3,
14
+ "down_block_types": [
15
+ "DownEncoderBlock2D",
16
+ "DownEncoderBlock2D",
17
+ "DownEncoderBlock2D",
18
+ "DownEncoderBlock2D",
19
+ ],
20
+ "down_block_out_channels": [128, 256, 512, 512],
21
+ "layers_per_down_block": 2,
22
+ "up_block_types": [
23
+ "UpDecoderBlock2D",
24
+ "UpDecoderBlock2D",
25
+ "UpDecoderBlock2D",
26
+ "UpDecoderBlock2D",
27
+ ],
28
+ "up_block_out_channels": [192, 384, 768, 768],
29
+ "layers_per_up_block": 3,
30
+ "act_fn": "silu",
31
+ "latent_channels": 4,
32
+ "norm_num_groups": 32,
33
+ "sample_size": 256,
34
+ "scaling_factor": 0.18215,
35
+ }
36
+
37
+ ASYMMETRIC_AUTOENCODER_KL_x_2_CONFIG = {
38
+ "in_channels": 3,
39
+ "out_channels": 3,
40
+ "down_block_types": [
41
+ "DownEncoderBlock2D",
42
+ "DownEncoderBlock2D",
43
+ "DownEncoderBlock2D",
44
+ "DownEncoderBlock2D",
45
+ ],
46
+ "down_block_out_channels": [128, 256, 512, 512],
47
+ "layers_per_down_block": 2,
48
+ "up_block_types": [
49
+ "UpDecoderBlock2D",
50
+ "UpDecoderBlock2D",
51
+ "UpDecoderBlock2D",
52
+ "UpDecoderBlock2D",
53
+ ],
54
+ "up_block_out_channels": [256, 512, 1024, 1024],
55
+ "layers_per_up_block": 5,
56
+ "act_fn": "silu",
57
+ "latent_channels": 4,
58
+ "norm_num_groups": 32,
59
+ "sample_size": 256,
60
+ "scaling_factor": 0.18215,
61
+ }
62
+
63
+
64
+ def convert_asymmetric_autoencoder_kl_state_dict(original_state_dict: Dict[str, Any]) -> dict[str, Any]:
65
+ converted_state_dict = {}
66
+ for k, v in original_state_dict.items():
67
+ if k.startswith("encoder."):
68
+ converted_state_dict[
69
+ k.replace("encoder.down.", "encoder.down_blocks.")
70
+ .replace("encoder.mid.", "encoder.mid_block.")
71
+ .replace("encoder.norm_out.", "encoder.conv_norm_out.")
72
+ .replace(".downsample.", ".downsamplers.0.")
73
+ .replace(".nin_shortcut.", ".conv_shortcut.")
74
+ .replace(".block.", ".resnets.")
75
+ .replace(".block_1.", ".resnets.0.")
76
+ .replace(".block_2.", ".resnets.1.")
77
+ .replace(".attn_1.k.", ".attentions.0.to_k.")
78
+ .replace(".attn_1.q.", ".attentions.0.to_q.")
79
+ .replace(".attn_1.v.", ".attentions.0.to_v.")
80
+ .replace(".attn_1.proj_out.", ".attentions.0.to_out.0.")
81
+ .replace(".attn_1.norm.", ".attentions.0.group_norm.")
82
+ ] = v
83
+ elif k.startswith("decoder.") and "up_layers" not in k:
84
+ converted_state_dict[
85
+ k.replace("decoder.encoder.", "decoder.condition_encoder.")
86
+ .replace(".norm_out.", ".conv_norm_out.")
87
+ .replace(".up.0.", ".up_blocks.3.")
88
+ .replace(".up.1.", ".up_blocks.2.")
89
+ .replace(".up.2.", ".up_blocks.1.")
90
+ .replace(".up.3.", ".up_blocks.0.")
91
+ .replace(".block.", ".resnets.")
92
+ .replace("mid", "mid_block")
93
+ .replace(".0.upsample.", ".0.upsamplers.0.")
94
+ .replace(".1.upsample.", ".1.upsamplers.0.")
95
+ .replace(".2.upsample.", ".2.upsamplers.0.")
96
+ .replace(".nin_shortcut.", ".conv_shortcut.")
97
+ .replace(".block_1.", ".resnets.0.")
98
+ .replace(".block_2.", ".resnets.1.")
99
+ .replace(".attn_1.k.", ".attentions.0.to_k.")
100
+ .replace(".attn_1.q.", ".attentions.0.to_q.")
101
+ .replace(".attn_1.v.", ".attentions.0.to_v.")
102
+ .replace(".attn_1.proj_out.", ".attentions.0.to_out.0.")
103
+ .replace(".attn_1.norm.", ".attentions.0.group_norm.")
104
+ ] = v
105
+ elif k.startswith("quant_conv."):
106
+ converted_state_dict[k] = v
107
+ elif k.startswith("post_quant_conv."):
108
+ converted_state_dict[k] = v
109
+ else:
110
+ print(f" skipping key `{k}`")
111
+ # fix weights shape
112
+ for k, v in converted_state_dict.items():
113
+ if (
114
+ (k.startswith("encoder.mid_block.attentions.0") or k.startswith("decoder.mid_block.attentions.0"))
115
+ and k.endswith("weight")
116
+ and ("to_q" in k or "to_k" in k or "to_v" in k or "to_out" in k)
117
+ ):
118
+ converted_state_dict[k] = converted_state_dict[k][:, :, 0, 0]
119
+
120
+ return converted_state_dict
121
+
122
+
123
+ def get_asymmetric_autoencoder_kl_from_original_checkpoint(
124
+ scale: Literal["1.5", "2"], original_checkpoint_path: str, map_location: torch.device
125
+ ) -> AsymmetricAutoencoderKL:
126
+ print("Loading original state_dict")
127
+ original_state_dict = torch.load(original_checkpoint_path, map_location=map_location)
128
+ original_state_dict = original_state_dict["state_dict"]
129
+ print("Converting state_dict")
130
+ converted_state_dict = convert_asymmetric_autoencoder_kl_state_dict(original_state_dict)
131
+ kwargs = ASYMMETRIC_AUTOENCODER_KL_x_1_5_CONFIG if scale == "1.5" else ASYMMETRIC_AUTOENCODER_KL_x_2_CONFIG
132
+ print("Initializing AsymmetricAutoencoderKL model")
133
+ asymmetric_autoencoder_kl = AsymmetricAutoencoderKL(**kwargs)
134
+ print("Loading weight from converted state_dict")
135
+ asymmetric_autoencoder_kl.load_state_dict(converted_state_dict)
136
+ asymmetric_autoencoder_kl.eval()
137
+ print("AsymmetricAutoencoderKL successfully initialized")
138
+ return asymmetric_autoencoder_kl
139
+
140
+
141
+ if __name__ == "__main__":
142
+ start = time.time()
143
+ parser = argparse.ArgumentParser()
144
+ parser.add_argument(
145
+ "--scale",
146
+ default=None,
147
+ type=str,
148
+ required=True,
149
+ help="Asymmetric VQGAN scale: `1.5` or `2`",
150
+ )
151
+ parser.add_argument(
152
+ "--original_checkpoint_path",
153
+ default=None,
154
+ type=str,
155
+ required=True,
156
+ help="Path to the original Asymmetric VQGAN checkpoint",
157
+ )
158
+ parser.add_argument(
159
+ "--output_path",
160
+ default=None,
161
+ type=str,
162
+ required=True,
163
+ help="Path to save pretrained AsymmetricAutoencoderKL model",
164
+ )
165
+ parser.add_argument(
166
+ "--map_location",
167
+ default="cpu",
168
+ type=str,
169
+ required=False,
170
+ help="The device passed to `map_location` when loading the checkpoint",
171
+ )
172
+ args = parser.parse_args()
173
+
174
+ assert args.scale in ["1.5", "2"], f"{args.scale} should be `1.5` of `2`"
175
+ assert Path(args.original_checkpoint_path).is_file()
176
+
177
+ asymmetric_autoencoder_kl = get_asymmetric_autoencoder_kl_from_original_checkpoint(
178
+ scale=args.scale,
179
+ original_checkpoint_path=args.original_checkpoint_path,
180
+ map_location=torch.device(args.map_location),
181
+ )
182
+ print("Saving pretrained AsymmetricAutoencoderKL")
183
+ asymmetric_autoencoder_kl.save_pretrained(args.output_path)
184
+ print(f"Done in {time.time() - start:.2f} seconds")
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_aura_flow_to_diffusers.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import torch
4
+ from huggingface_hub import hf_hub_download
5
+
6
+ from diffusers.models.transformers.auraflow_transformer_2d import AuraFlowTransformer2DModel
7
+
8
+
9
+ def load_original_state_dict(args):
10
+ model_pt = hf_hub_download(repo_id=args.original_state_dict_repo_id, filename="aura_diffusion_pytorch_model.bin")
11
+ state_dict = torch.load(model_pt, map_location="cpu")
12
+ return state_dict
13
+
14
+
15
+ def calculate_layers(state_dict_keys, key_prefix):
16
+ dit_layers = set()
17
+ for k in state_dict_keys:
18
+ if key_prefix in k:
19
+ dit_layers.add(int(k.split(".")[2]))
20
+ print(f"{key_prefix}: {len(dit_layers)}")
21
+ return len(dit_layers)
22
+
23
+
24
+ # similar to SD3 but only for the last norm layer
25
+ def swap_scale_shift(weight, dim):
26
+ shift, scale = weight.chunk(2, dim=0)
27
+ new_weight = torch.cat([scale, shift], dim=0)
28
+ return new_weight
29
+
30
+
31
+ def convert_transformer(state_dict):
32
+ converted_state_dict = {}
33
+ state_dict_keys = list(state_dict.keys())
34
+
35
+ converted_state_dict["register_tokens"] = state_dict.pop("model.register_tokens")
36
+ converted_state_dict["pos_embed.pos_embed"] = state_dict.pop("model.positional_encoding")
37
+ converted_state_dict["pos_embed.proj.weight"] = state_dict.pop("model.init_x_linear.weight")
38
+ converted_state_dict["pos_embed.proj.bias"] = state_dict.pop("model.init_x_linear.bias")
39
+
40
+ converted_state_dict["time_step_proj.linear_1.weight"] = state_dict.pop("model.t_embedder.mlp.0.weight")
41
+ converted_state_dict["time_step_proj.linear_1.bias"] = state_dict.pop("model.t_embedder.mlp.0.bias")
42
+ converted_state_dict["time_step_proj.linear_2.weight"] = state_dict.pop("model.t_embedder.mlp.2.weight")
43
+ converted_state_dict["time_step_proj.linear_2.bias"] = state_dict.pop("model.t_embedder.mlp.2.bias")
44
+
45
+ converted_state_dict["context_embedder.weight"] = state_dict.pop("model.cond_seq_linear.weight")
46
+
47
+ mmdit_layers = calculate_layers(state_dict_keys, key_prefix="double_layers")
48
+ single_dit_layers = calculate_layers(state_dict_keys, key_prefix="single_layers")
49
+
50
+ # MMDiT blocks 🎸.
51
+ for i in range(mmdit_layers):
52
+ # feed-forward
53
+ path_mapping = {"mlpX": "ff", "mlpC": "ff_context"}
54
+ weight_mapping = {"c_fc1": "linear_1", "c_fc2": "linear_2", "c_proj": "out_projection"}
55
+ for orig_k, diffuser_k in path_mapping.items():
56
+ for k, v in weight_mapping.items():
57
+ converted_state_dict[f"joint_transformer_blocks.{i}.{diffuser_k}.{v}.weight"] = state_dict.pop(
58
+ f"model.double_layers.{i}.{orig_k}.{k}.weight"
59
+ )
60
+
61
+ # norms
62
+ path_mapping = {"modX": "norm1", "modC": "norm1_context"}
63
+ for orig_k, diffuser_k in path_mapping.items():
64
+ converted_state_dict[f"joint_transformer_blocks.{i}.{diffuser_k}.linear.weight"] = state_dict.pop(
65
+ f"model.double_layers.{i}.{orig_k}.1.weight"
66
+ )
67
+
68
+ # attns
69
+ x_attn_mapping = {"w2q": "to_q", "w2k": "to_k", "w2v": "to_v", "w2o": "to_out.0"}
70
+ context_attn_mapping = {"w1q": "add_q_proj", "w1k": "add_k_proj", "w1v": "add_v_proj", "w1o": "to_add_out"}
71
+ for attn_mapping in [x_attn_mapping, context_attn_mapping]:
72
+ for k, v in attn_mapping.items():
73
+ converted_state_dict[f"joint_transformer_blocks.{i}.attn.{v}.weight"] = state_dict.pop(
74
+ f"model.double_layers.{i}.attn.{k}.weight"
75
+ )
76
+
77
+ # Single-DiT blocks.
78
+ for i in range(single_dit_layers):
79
+ # feed-forward
80
+ mapping = {"c_fc1": "linear_1", "c_fc2": "linear_2", "c_proj": "out_projection"}
81
+ for k, v in mapping.items():
82
+ converted_state_dict[f"single_transformer_blocks.{i}.ff.{v}.weight"] = state_dict.pop(
83
+ f"model.single_layers.{i}.mlp.{k}.weight"
84
+ )
85
+
86
+ # norms
87
+ converted_state_dict[f"single_transformer_blocks.{i}.norm1.linear.weight"] = state_dict.pop(
88
+ f"model.single_layers.{i}.modCX.1.weight"
89
+ )
90
+
91
+ # attns
92
+ x_attn_mapping = {"w1q": "to_q", "w1k": "to_k", "w1v": "to_v", "w1o": "to_out.0"}
93
+ for k, v in x_attn_mapping.items():
94
+ converted_state_dict[f"single_transformer_blocks.{i}.attn.{v}.weight"] = state_dict.pop(
95
+ f"model.single_layers.{i}.attn.{k}.weight"
96
+ )
97
+
98
+ # Final blocks.
99
+ converted_state_dict["proj_out.weight"] = state_dict.pop("model.final_linear.weight")
100
+ converted_state_dict["norm_out.linear.weight"] = swap_scale_shift(state_dict.pop("model.modF.1.weight"), dim=None)
101
+
102
+ return converted_state_dict
103
+
104
+
105
+ @torch.no_grad()
106
+ def populate_state_dict(args):
107
+ original_state_dict = load_original_state_dict(args)
108
+ state_dict_keys = list(original_state_dict.keys())
109
+ mmdit_layers = calculate_layers(state_dict_keys, key_prefix="double_layers")
110
+ single_dit_layers = calculate_layers(state_dict_keys, key_prefix="single_layers")
111
+
112
+ converted_state_dict = convert_transformer(original_state_dict)
113
+ model_diffusers = AuraFlowTransformer2DModel(
114
+ num_mmdit_layers=mmdit_layers, num_single_dit_layers=single_dit_layers
115
+ )
116
+ model_diffusers.load_state_dict(converted_state_dict, strict=True)
117
+
118
+ return model_diffusers
119
+
120
+
121
+ if __name__ == "__main__":
122
+ parser = argparse.ArgumentParser()
123
+ parser.add_argument("--original_state_dict_repo_id", default="AuraDiffusion/auradiffusion-v0.1a0", type=str)
124
+ parser.add_argument("--dump_path", default="aura-flow", type=str)
125
+ parser.add_argument("--hub_id", default=None, type=str)
126
+ args = parser.parse_args()
127
+
128
+ model_diffusers = populate_state_dict(args)
129
+ model_diffusers.save_pretrained(args.dump_path)
130
+ if args.hub_id is not None:
131
+ model_diffusers.push_to_hub(args.hub_id)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_blipdiffusion_to_diffusers.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script requires you to build `LAVIS` from source, since the pip version doesn't have BLIP Diffusion. Follow instructions here: https://github.com/salesforce/LAVIS/tree/main.
3
+ """
4
+
5
+ import argparse
6
+ import os
7
+ import tempfile
8
+
9
+ import torch
10
+ from lavis.models import load_model_and_preprocess
11
+ from transformers import CLIPTokenizer
12
+ from transformers.models.blip_2.configuration_blip_2 import Blip2Config
13
+
14
+ from diffusers import (
15
+ AutoencoderKL,
16
+ PNDMScheduler,
17
+ UNet2DConditionModel,
18
+ )
19
+ from diffusers.pipelines import BlipDiffusionPipeline
20
+ from diffusers.pipelines.blip_diffusion.blip_image_processing import BlipImageProcessor
21
+ from diffusers.pipelines.blip_diffusion.modeling_blip2 import Blip2QFormerModel
22
+ from diffusers.pipelines.blip_diffusion.modeling_ctx_clip import ContextCLIPTextModel
23
+
24
+
25
+ BLIP2_CONFIG = {
26
+ "vision_config": {
27
+ "hidden_size": 1024,
28
+ "num_hidden_layers": 23,
29
+ "num_attention_heads": 16,
30
+ "image_size": 224,
31
+ "patch_size": 14,
32
+ "intermediate_size": 4096,
33
+ "hidden_act": "quick_gelu",
34
+ },
35
+ "qformer_config": {
36
+ "cross_attention_frequency": 1,
37
+ "encoder_hidden_size": 1024,
38
+ "vocab_size": 30523,
39
+ },
40
+ "num_query_tokens": 16,
41
+ }
42
+ blip2config = Blip2Config(**BLIP2_CONFIG)
43
+
44
+
45
+ def qformer_model_from_original_config():
46
+ qformer = Blip2QFormerModel(blip2config)
47
+ return qformer
48
+
49
+
50
+ def embeddings_from_original_checkpoint(model, diffuser_embeddings_prefix, original_embeddings_prefix):
51
+ embeddings = {}
52
+ embeddings.update(
53
+ {
54
+ f"{diffuser_embeddings_prefix}.word_embeddings.weight": model[
55
+ f"{original_embeddings_prefix}.word_embeddings.weight"
56
+ ]
57
+ }
58
+ )
59
+ embeddings.update(
60
+ {
61
+ f"{diffuser_embeddings_prefix}.position_embeddings.weight": model[
62
+ f"{original_embeddings_prefix}.position_embeddings.weight"
63
+ ]
64
+ }
65
+ )
66
+ embeddings.update(
67
+ {f"{diffuser_embeddings_prefix}.LayerNorm.weight": model[f"{original_embeddings_prefix}.LayerNorm.weight"]}
68
+ )
69
+ embeddings.update(
70
+ {f"{diffuser_embeddings_prefix}.LayerNorm.bias": model[f"{original_embeddings_prefix}.LayerNorm.bias"]}
71
+ )
72
+ return embeddings
73
+
74
+
75
+ def proj_layer_from_original_checkpoint(model, diffuser_proj_prefix, original_proj_prefix):
76
+ proj_layer = {}
77
+ proj_layer.update({f"{diffuser_proj_prefix}.dense1.weight": model[f"{original_proj_prefix}.dense1.weight"]})
78
+ proj_layer.update({f"{diffuser_proj_prefix}.dense1.bias": model[f"{original_proj_prefix}.dense1.bias"]})
79
+ proj_layer.update({f"{diffuser_proj_prefix}.dense2.weight": model[f"{original_proj_prefix}.dense2.weight"]})
80
+ proj_layer.update({f"{diffuser_proj_prefix}.dense2.bias": model[f"{original_proj_prefix}.dense2.bias"]})
81
+ proj_layer.update({f"{diffuser_proj_prefix}.LayerNorm.weight": model[f"{original_proj_prefix}.LayerNorm.weight"]})
82
+ proj_layer.update({f"{diffuser_proj_prefix}.LayerNorm.bias": model[f"{original_proj_prefix}.LayerNorm.bias"]})
83
+ return proj_layer
84
+
85
+
86
+ def attention_from_original_checkpoint(model, diffuser_attention_prefix, original_attention_prefix):
87
+ attention = {}
88
+ attention.update(
89
+ {
90
+ f"{diffuser_attention_prefix}.attention.query.weight": model[
91
+ f"{original_attention_prefix}.self.query.weight"
92
+ ]
93
+ }
94
+ )
95
+ attention.update(
96
+ {f"{diffuser_attention_prefix}.attention.query.bias": model[f"{original_attention_prefix}.self.query.bias"]}
97
+ )
98
+ attention.update(
99
+ {f"{diffuser_attention_prefix}.attention.key.weight": model[f"{original_attention_prefix}.self.key.weight"]}
100
+ )
101
+ attention.update(
102
+ {f"{diffuser_attention_prefix}.attention.key.bias": model[f"{original_attention_prefix}.self.key.bias"]}
103
+ )
104
+ attention.update(
105
+ {
106
+ f"{diffuser_attention_prefix}.attention.value.weight": model[
107
+ f"{original_attention_prefix}.self.value.weight"
108
+ ]
109
+ }
110
+ )
111
+ attention.update(
112
+ {f"{diffuser_attention_prefix}.attention.value.bias": model[f"{original_attention_prefix}.self.value.bias"]}
113
+ )
114
+ attention.update(
115
+ {f"{diffuser_attention_prefix}.output.dense.weight": model[f"{original_attention_prefix}.output.dense.weight"]}
116
+ )
117
+ attention.update(
118
+ {f"{diffuser_attention_prefix}.output.dense.bias": model[f"{original_attention_prefix}.output.dense.bias"]}
119
+ )
120
+ attention.update(
121
+ {
122
+ f"{diffuser_attention_prefix}.output.LayerNorm.weight": model[
123
+ f"{original_attention_prefix}.output.LayerNorm.weight"
124
+ ]
125
+ }
126
+ )
127
+ attention.update(
128
+ {
129
+ f"{diffuser_attention_prefix}.output.LayerNorm.bias": model[
130
+ f"{original_attention_prefix}.output.LayerNorm.bias"
131
+ ]
132
+ }
133
+ )
134
+ return attention
135
+
136
+
137
+ def output_layers_from_original_checkpoint(model, diffuser_output_prefix, original_output_prefix):
138
+ output_layers = {}
139
+ output_layers.update({f"{diffuser_output_prefix}.dense.weight": model[f"{original_output_prefix}.dense.weight"]})
140
+ output_layers.update({f"{diffuser_output_prefix}.dense.bias": model[f"{original_output_prefix}.dense.bias"]})
141
+ output_layers.update(
142
+ {f"{diffuser_output_prefix}.LayerNorm.weight": model[f"{original_output_prefix}.LayerNorm.weight"]}
143
+ )
144
+ output_layers.update(
145
+ {f"{diffuser_output_prefix}.LayerNorm.bias": model[f"{original_output_prefix}.LayerNorm.bias"]}
146
+ )
147
+ return output_layers
148
+
149
+
150
+ def encoder_from_original_checkpoint(model, diffuser_encoder_prefix, original_encoder_prefix):
151
+ encoder = {}
152
+ for i in range(blip2config.qformer_config.num_hidden_layers):
153
+ encoder.update(
154
+ attention_from_original_checkpoint(
155
+ model, f"{diffuser_encoder_prefix}.{i}.attention", f"{original_encoder_prefix}.{i}.attention"
156
+ )
157
+ )
158
+ encoder.update(
159
+ attention_from_original_checkpoint(
160
+ model, f"{diffuser_encoder_prefix}.{i}.crossattention", f"{original_encoder_prefix}.{i}.crossattention"
161
+ )
162
+ )
163
+
164
+ encoder.update(
165
+ {
166
+ f"{diffuser_encoder_prefix}.{i}.intermediate.dense.weight": model[
167
+ f"{original_encoder_prefix}.{i}.intermediate.dense.weight"
168
+ ]
169
+ }
170
+ )
171
+ encoder.update(
172
+ {
173
+ f"{diffuser_encoder_prefix}.{i}.intermediate.dense.bias": model[
174
+ f"{original_encoder_prefix}.{i}.intermediate.dense.bias"
175
+ ]
176
+ }
177
+ )
178
+ encoder.update(
179
+ {
180
+ f"{diffuser_encoder_prefix}.{i}.intermediate_query.dense.weight": model[
181
+ f"{original_encoder_prefix}.{i}.intermediate_query.dense.weight"
182
+ ]
183
+ }
184
+ )
185
+ encoder.update(
186
+ {
187
+ f"{diffuser_encoder_prefix}.{i}.intermediate_query.dense.bias": model[
188
+ f"{original_encoder_prefix}.{i}.intermediate_query.dense.bias"
189
+ ]
190
+ }
191
+ )
192
+
193
+ encoder.update(
194
+ output_layers_from_original_checkpoint(
195
+ model, f"{diffuser_encoder_prefix}.{i}.output", f"{original_encoder_prefix}.{i}.output"
196
+ )
197
+ )
198
+ encoder.update(
199
+ output_layers_from_original_checkpoint(
200
+ model, f"{diffuser_encoder_prefix}.{i}.output_query", f"{original_encoder_prefix}.{i}.output_query"
201
+ )
202
+ )
203
+ return encoder
204
+
205
+
206
+ def visual_encoder_layer_from_original_checkpoint(model, diffuser_prefix, original_prefix):
207
+ visual_encoder_layer = {}
208
+
209
+ visual_encoder_layer.update({f"{diffuser_prefix}.layer_norm1.weight": model[f"{original_prefix}.ln_1.weight"]})
210
+ visual_encoder_layer.update({f"{diffuser_prefix}.layer_norm1.bias": model[f"{original_prefix}.ln_1.bias"]})
211
+ visual_encoder_layer.update({f"{diffuser_prefix}.layer_norm2.weight": model[f"{original_prefix}.ln_2.weight"]})
212
+ visual_encoder_layer.update({f"{diffuser_prefix}.layer_norm2.bias": model[f"{original_prefix}.ln_2.bias"]})
213
+ visual_encoder_layer.update(
214
+ {f"{diffuser_prefix}.self_attn.qkv.weight": model[f"{original_prefix}.attn.in_proj_weight"]}
215
+ )
216
+ visual_encoder_layer.update(
217
+ {f"{diffuser_prefix}.self_attn.qkv.bias": model[f"{original_prefix}.attn.in_proj_bias"]}
218
+ )
219
+ visual_encoder_layer.update(
220
+ {f"{diffuser_prefix}.self_attn.projection.weight": model[f"{original_prefix}.attn.out_proj.weight"]}
221
+ )
222
+ visual_encoder_layer.update(
223
+ {f"{diffuser_prefix}.self_attn.projection.bias": model[f"{original_prefix}.attn.out_proj.bias"]}
224
+ )
225
+ visual_encoder_layer.update({f"{diffuser_prefix}.mlp.fc1.weight": model[f"{original_prefix}.mlp.c_fc.weight"]})
226
+ visual_encoder_layer.update({f"{diffuser_prefix}.mlp.fc1.bias": model[f"{original_prefix}.mlp.c_fc.bias"]})
227
+ visual_encoder_layer.update({f"{diffuser_prefix}.mlp.fc2.weight": model[f"{original_prefix}.mlp.c_proj.weight"]})
228
+ visual_encoder_layer.update({f"{diffuser_prefix}.mlp.fc2.bias": model[f"{original_prefix}.mlp.c_proj.bias"]})
229
+
230
+ return visual_encoder_layer
231
+
232
+
233
+ def visual_encoder_from_original_checkpoint(model, diffuser_prefix, original_prefix):
234
+ visual_encoder = {}
235
+
236
+ visual_encoder.update(
237
+ {
238
+ f"{diffuser_prefix}.embeddings.class_embedding": model[f"{original_prefix}.class_embedding"]
239
+ .unsqueeze(0)
240
+ .unsqueeze(0)
241
+ }
242
+ )
243
+ visual_encoder.update(
244
+ {
245
+ f"{diffuser_prefix}.embeddings.position_embedding": model[
246
+ f"{original_prefix}.positional_embedding"
247
+ ].unsqueeze(0)
248
+ }
249
+ )
250
+ visual_encoder.update(
251
+ {f"{diffuser_prefix}.embeddings.patch_embedding.weight": model[f"{original_prefix}.conv1.weight"]}
252
+ )
253
+ visual_encoder.update({f"{diffuser_prefix}.pre_layernorm.weight": model[f"{original_prefix}.ln_pre.weight"]})
254
+ visual_encoder.update({f"{diffuser_prefix}.pre_layernorm.bias": model[f"{original_prefix}.ln_pre.bias"]})
255
+
256
+ for i in range(blip2config.vision_config.num_hidden_layers):
257
+ visual_encoder.update(
258
+ visual_encoder_layer_from_original_checkpoint(
259
+ model, f"{diffuser_prefix}.encoder.layers.{i}", f"{original_prefix}.transformer.resblocks.{i}"
260
+ )
261
+ )
262
+
263
+ visual_encoder.update({f"{diffuser_prefix}.post_layernorm.weight": model["blip.ln_vision.weight"]})
264
+ visual_encoder.update({f"{diffuser_prefix}.post_layernorm.bias": model["blip.ln_vision.bias"]})
265
+
266
+ return visual_encoder
267
+
268
+
269
+ def qformer_original_checkpoint_to_diffusers_checkpoint(model):
270
+ qformer_checkpoint = {}
271
+ qformer_checkpoint.update(embeddings_from_original_checkpoint(model, "embeddings", "blip.Qformer.bert.embeddings"))
272
+ qformer_checkpoint.update({"query_tokens": model["blip.query_tokens"]})
273
+ qformer_checkpoint.update(proj_layer_from_original_checkpoint(model, "proj_layer", "proj_layer"))
274
+ qformer_checkpoint.update(
275
+ encoder_from_original_checkpoint(model, "encoder.layer", "blip.Qformer.bert.encoder.layer")
276
+ )
277
+ qformer_checkpoint.update(visual_encoder_from_original_checkpoint(model, "visual_encoder", "blip.visual_encoder"))
278
+ return qformer_checkpoint
279
+
280
+
281
+ def get_qformer(model):
282
+ print("loading qformer")
283
+
284
+ qformer = qformer_model_from_original_config()
285
+ qformer_diffusers_checkpoint = qformer_original_checkpoint_to_diffusers_checkpoint(model)
286
+
287
+ load_checkpoint_to_model(qformer_diffusers_checkpoint, qformer)
288
+
289
+ print("done loading qformer")
290
+ return qformer
291
+
292
+
293
+ def load_checkpoint_to_model(checkpoint, model):
294
+ with tempfile.NamedTemporaryFile(delete=False) as file:
295
+ torch.save(checkpoint, file.name)
296
+ del checkpoint
297
+ model.load_state_dict(torch.load(file.name), strict=False)
298
+
299
+ os.remove(file.name)
300
+
301
+
302
+ def save_blip_diffusion_model(model, args):
303
+ qformer = get_qformer(model)
304
+ qformer.eval()
305
+
306
+ text_encoder = ContextCLIPTextModel.from_pretrained(
307
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="text_encoder"
308
+ )
309
+ vae = AutoencoderKL.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="vae")
310
+ unet = UNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="unet")
311
+ vae.eval()
312
+ text_encoder.eval()
313
+ scheduler = PNDMScheduler(
314
+ beta_start=0.00085,
315
+ beta_end=0.012,
316
+ beta_schedule="scaled_linear",
317
+ set_alpha_to_one=False,
318
+ skip_prk_steps=True,
319
+ )
320
+ tokenizer = CLIPTokenizer.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="tokenizer")
321
+ image_processor = BlipImageProcessor()
322
+ blip_diffusion = BlipDiffusionPipeline(
323
+ tokenizer=tokenizer,
324
+ text_encoder=text_encoder,
325
+ vae=vae,
326
+ unet=unet,
327
+ scheduler=scheduler,
328
+ qformer=qformer,
329
+ image_processor=image_processor,
330
+ )
331
+ blip_diffusion.save_pretrained(args.checkpoint_path)
332
+
333
+
334
+ def main(args):
335
+ model, _, _ = load_model_and_preprocess("blip_diffusion", "base", device="cpu", is_eval=True)
336
+ save_blip_diffusion_model(model.state_dict(), args)
337
+
338
+
339
+ if __name__ == "__main__":
340
+ parser = argparse.ArgumentParser()
341
+ parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.")
342
+ args = parser.parse_args()
343
+
344
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogvideox_to_diffusers.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from typing import Any, Dict
3
+
4
+ import torch
5
+ from transformers import T5EncoderModel, T5Tokenizer
6
+
7
+ from diffusers import (
8
+ AutoencoderKLCogVideoX,
9
+ CogVideoXDDIMScheduler,
10
+ CogVideoXImageToVideoPipeline,
11
+ CogVideoXPipeline,
12
+ CogVideoXTransformer3DModel,
13
+ )
14
+
15
+
16
+ def reassign_query_key_value_inplace(key: str, state_dict: Dict[str, Any]):
17
+ to_q_key = key.replace("query_key_value", "to_q")
18
+ to_k_key = key.replace("query_key_value", "to_k")
19
+ to_v_key = key.replace("query_key_value", "to_v")
20
+ to_q, to_k, to_v = torch.chunk(state_dict[key], chunks=3, dim=0)
21
+ state_dict[to_q_key] = to_q
22
+ state_dict[to_k_key] = to_k
23
+ state_dict[to_v_key] = to_v
24
+ state_dict.pop(key)
25
+
26
+
27
+ def reassign_query_key_layernorm_inplace(key: str, state_dict: Dict[str, Any]):
28
+ layer_id, weight_or_bias = key.split(".")[-2:]
29
+
30
+ if "query" in key:
31
+ new_key = f"transformer_blocks.{layer_id}.attn1.norm_q.{weight_or_bias}"
32
+ elif "key" in key:
33
+ new_key = f"transformer_blocks.{layer_id}.attn1.norm_k.{weight_or_bias}"
34
+
35
+ state_dict[new_key] = state_dict.pop(key)
36
+
37
+
38
+ def reassign_adaln_norm_inplace(key: str, state_dict: Dict[str, Any]):
39
+ layer_id, _, weight_or_bias = key.split(".")[-3:]
40
+
41
+ weights_or_biases = state_dict[key].chunk(12, dim=0)
42
+ norm1_weights_or_biases = torch.cat(weights_or_biases[0:3] + weights_or_biases[6:9])
43
+ norm2_weights_or_biases = torch.cat(weights_or_biases[3:6] + weights_or_biases[9:12])
44
+
45
+ norm1_key = f"transformer_blocks.{layer_id}.norm1.linear.{weight_or_bias}"
46
+ state_dict[norm1_key] = norm1_weights_or_biases
47
+
48
+ norm2_key = f"transformer_blocks.{layer_id}.norm2.linear.{weight_or_bias}"
49
+ state_dict[norm2_key] = norm2_weights_or_biases
50
+
51
+ state_dict.pop(key)
52
+
53
+
54
+ def remove_keys_inplace(key: str, state_dict: Dict[str, Any]):
55
+ state_dict.pop(key)
56
+
57
+
58
+ def replace_up_keys_inplace(key: str, state_dict: Dict[str, Any]):
59
+ key_split = key.split(".")
60
+ layer_index = int(key_split[2])
61
+ replace_layer_index = 4 - 1 - layer_index
62
+
63
+ key_split[1] = "up_blocks"
64
+ key_split[2] = str(replace_layer_index)
65
+ new_key = ".".join(key_split)
66
+
67
+ state_dict[new_key] = state_dict.pop(key)
68
+
69
+
70
+ TRANSFORMER_KEYS_RENAME_DICT = {
71
+ "transformer.final_layernorm": "norm_final",
72
+ "transformer": "transformer_blocks",
73
+ "attention": "attn1",
74
+ "mlp": "ff.net",
75
+ "dense_h_to_4h": "0.proj",
76
+ "dense_4h_to_h": "2",
77
+ ".layers": "",
78
+ "dense": "to_out.0",
79
+ "input_layernorm": "norm1.norm",
80
+ "post_attn1_layernorm": "norm2.norm",
81
+ "time_embed.0": "time_embedding.linear_1",
82
+ "time_embed.2": "time_embedding.linear_2",
83
+ "ofs_embed.0": "ofs_embedding.linear_1",
84
+ "ofs_embed.2": "ofs_embedding.linear_2",
85
+ "mixins.patch_embed": "patch_embed",
86
+ "mixins.final_layer.norm_final": "norm_out.norm",
87
+ "mixins.final_layer.linear": "proj_out",
88
+ "mixins.final_layer.adaLN_modulation.1": "norm_out.linear",
89
+ "mixins.pos_embed.pos_embedding": "patch_embed.pos_embedding", # Specific to CogVideoX-5b-I2V
90
+ }
91
+
92
+ TRANSFORMER_SPECIAL_KEYS_REMAP = {
93
+ "query_key_value": reassign_query_key_value_inplace,
94
+ "query_layernorm_list": reassign_query_key_layernorm_inplace,
95
+ "key_layernorm_list": reassign_query_key_layernorm_inplace,
96
+ "adaln_layer.adaLN_modulations": reassign_adaln_norm_inplace,
97
+ "embed_tokens": remove_keys_inplace,
98
+ "freqs_sin": remove_keys_inplace,
99
+ "freqs_cos": remove_keys_inplace,
100
+ "position_embedding": remove_keys_inplace,
101
+ }
102
+
103
+ VAE_KEYS_RENAME_DICT = {
104
+ "block.": "resnets.",
105
+ "down.": "down_blocks.",
106
+ "downsample": "downsamplers.0",
107
+ "upsample": "upsamplers.0",
108
+ "nin_shortcut": "conv_shortcut",
109
+ "encoder.mid.block_1": "encoder.mid_block.resnets.0",
110
+ "encoder.mid.block_2": "encoder.mid_block.resnets.1",
111
+ "decoder.mid.block_1": "decoder.mid_block.resnets.0",
112
+ "decoder.mid.block_2": "decoder.mid_block.resnets.1",
113
+ }
114
+
115
+ VAE_SPECIAL_KEYS_REMAP = {
116
+ "loss": remove_keys_inplace,
117
+ "up.": replace_up_keys_inplace,
118
+ }
119
+
120
+ TOKENIZER_MAX_LENGTH = 226
121
+
122
+
123
+ def get_state_dict(saved_dict: Dict[str, Any]) -> dict[str, Any]:
124
+ state_dict = saved_dict
125
+ if "model" in saved_dict.keys():
126
+ state_dict = state_dict["model"]
127
+ if "module" in saved_dict.keys():
128
+ state_dict = state_dict["module"]
129
+ if "state_dict" in saved_dict.keys():
130
+ state_dict = state_dict["state_dict"]
131
+ return state_dict
132
+
133
+
134
+ def update_state_dict_inplace(state_dict: Dict[str, Any], old_key: str, new_key: str) -> dict[str, Any]:
135
+ state_dict[new_key] = state_dict.pop(old_key)
136
+
137
+
138
+ def convert_transformer(
139
+ ckpt_path: str,
140
+ num_layers: int,
141
+ num_attention_heads: int,
142
+ use_rotary_positional_embeddings: bool,
143
+ i2v: bool,
144
+ dtype: torch.dtype,
145
+ init_kwargs: Dict[str, Any],
146
+ ):
147
+ PREFIX_KEY = "model.diffusion_model."
148
+
149
+ original_state_dict = get_state_dict(torch.load(ckpt_path, map_location="cpu", mmap=True))
150
+ transformer = CogVideoXTransformer3DModel(
151
+ in_channels=32 if i2v else 16,
152
+ num_layers=num_layers,
153
+ num_attention_heads=num_attention_heads,
154
+ use_rotary_positional_embeddings=use_rotary_positional_embeddings,
155
+ ofs_embed_dim=512 if (i2v and init_kwargs["patch_size_t"] is not None) else None, # CogVideoX1.5-5B-I2V
156
+ use_learned_positional_embeddings=i2v and init_kwargs["patch_size_t"] is None, # CogVideoX-5B-I2V
157
+ **init_kwargs,
158
+ ).to(dtype=dtype)
159
+
160
+ for key in list(original_state_dict.keys()):
161
+ new_key = key[len(PREFIX_KEY) :]
162
+ for replace_key, rename_key in TRANSFORMER_KEYS_RENAME_DICT.items():
163
+ new_key = new_key.replace(replace_key, rename_key)
164
+ update_state_dict_inplace(original_state_dict, key, new_key)
165
+
166
+ for key in list(original_state_dict.keys()):
167
+ for special_key, handler_fn_inplace in TRANSFORMER_SPECIAL_KEYS_REMAP.items():
168
+ if special_key not in key:
169
+ continue
170
+ handler_fn_inplace(key, original_state_dict)
171
+
172
+ transformer.load_state_dict(original_state_dict, strict=True)
173
+ return transformer
174
+
175
+
176
+ def convert_vae(ckpt_path: str, scaling_factor: float, version: str, dtype: torch.dtype):
177
+ init_kwargs = {"scaling_factor": scaling_factor}
178
+ if version == "1.5":
179
+ init_kwargs.update({"invert_scale_latents": True})
180
+
181
+ original_state_dict = get_state_dict(torch.load(ckpt_path, map_location="cpu", mmap=True))
182
+ vae = AutoencoderKLCogVideoX(**init_kwargs).to(dtype=dtype)
183
+
184
+ for key in list(original_state_dict.keys()):
185
+ new_key = key[:]
186
+ for replace_key, rename_key in VAE_KEYS_RENAME_DICT.items():
187
+ new_key = new_key.replace(replace_key, rename_key)
188
+ update_state_dict_inplace(original_state_dict, key, new_key)
189
+
190
+ for key in list(original_state_dict.keys()):
191
+ for special_key, handler_fn_inplace in VAE_SPECIAL_KEYS_REMAP.items():
192
+ if special_key not in key:
193
+ continue
194
+ handler_fn_inplace(key, original_state_dict)
195
+
196
+ vae.load_state_dict(original_state_dict, strict=True)
197
+ return vae
198
+
199
+
200
+ def get_transformer_init_kwargs(version: str):
201
+ if version == "1.0":
202
+ vae_scale_factor_spatial = 8
203
+ init_kwargs = {
204
+ "patch_size": 2,
205
+ "patch_size_t": None,
206
+ "patch_bias": True,
207
+ "sample_height": 480 // vae_scale_factor_spatial,
208
+ "sample_width": 720 // vae_scale_factor_spatial,
209
+ "sample_frames": 49,
210
+ }
211
+
212
+ elif version == "1.5":
213
+ vae_scale_factor_spatial = 8
214
+ init_kwargs = {
215
+ "patch_size": 2,
216
+ "patch_size_t": 2,
217
+ "patch_bias": False,
218
+ "sample_height": 300,
219
+ "sample_width": 300,
220
+ "sample_frames": 81,
221
+ }
222
+ else:
223
+ raise ValueError("Unsupported version of CogVideoX.")
224
+
225
+ return init_kwargs
226
+
227
+
228
+ def get_args():
229
+ parser = argparse.ArgumentParser()
230
+ parser.add_argument(
231
+ "--transformer_ckpt_path", type=str, default=None, help="Path to original transformer checkpoint"
232
+ )
233
+ parser.add_argument("--vae_ckpt_path", type=str, default=None, help="Path to original vae checkpoint")
234
+ parser.add_argument("--output_path", type=str, required=True, help="Path where converted model should be saved")
235
+ parser.add_argument("--fp16", action="store_true", default=False, help="Whether to save the model weights in fp16")
236
+ parser.add_argument("--bf16", action="store_true", default=False, help="Whether to save the model weights in bf16")
237
+ parser.add_argument(
238
+ "--push_to_hub", action="store_true", default=False, help="Whether to push to HF Hub after saving"
239
+ )
240
+ parser.add_argument(
241
+ "--text_encoder_cache_dir", type=str, default=None, help="Path to text encoder cache directory"
242
+ )
243
+ parser.add_argument(
244
+ "--typecast_text_encoder",
245
+ action="store_true",
246
+ default=False,
247
+ help="Whether or not to apply fp16/bf16 precision to text_encoder",
248
+ )
249
+ # For CogVideoX-2B, num_layers is 30. For 5B, it is 42
250
+ parser.add_argument("--num_layers", type=int, default=30, help="Number of transformer blocks")
251
+ # For CogVideoX-2B, num_attention_heads is 30. For 5B, it is 48
252
+ parser.add_argument("--num_attention_heads", type=int, default=30, help="Number of attention heads")
253
+ # For CogVideoX-2B, use_rotary_positional_embeddings is False. For 5B, it is True
254
+ parser.add_argument(
255
+ "--use_rotary_positional_embeddings", action="store_true", default=False, help="Whether to use RoPE or not"
256
+ )
257
+ # For CogVideoX-2B, scaling_factor is 1.15258426. For 5B, it is 0.7
258
+ parser.add_argument("--scaling_factor", type=float, default=1.15258426, help="Scaling factor in the VAE")
259
+ # For CogVideoX-2B, snr_shift_scale is 3.0. For 5B, it is 1.0
260
+ parser.add_argument("--snr_shift_scale", type=float, default=3.0, help="Scaling factor in the VAE")
261
+ parser.add_argument(
262
+ "--i2v",
263
+ action="store_true",
264
+ default=False,
265
+ help="Whether the model to be converted is the Image-to-Video version of CogVideoX.",
266
+ )
267
+ parser.add_argument(
268
+ "--version",
269
+ choices=["1.0", "1.5"],
270
+ default="1.0",
271
+ help="Which version of CogVideoX to use for initializing default modeling parameters.",
272
+ )
273
+ return parser.parse_args()
274
+
275
+
276
+ if __name__ == "__main__":
277
+ args = get_args()
278
+
279
+ transformer = None
280
+ vae = None
281
+
282
+ if args.fp16 and args.bf16:
283
+ raise ValueError("You cannot pass both --fp16 and --bf16 at the same time.")
284
+
285
+ dtype = torch.float16 if args.fp16 else torch.bfloat16 if args.bf16 else torch.float32
286
+
287
+ if args.transformer_ckpt_path is not None:
288
+ init_kwargs = get_transformer_init_kwargs(args.version)
289
+ transformer = convert_transformer(
290
+ args.transformer_ckpt_path,
291
+ args.num_layers,
292
+ args.num_attention_heads,
293
+ args.use_rotary_positional_embeddings,
294
+ args.i2v,
295
+ dtype,
296
+ init_kwargs,
297
+ )
298
+ if args.vae_ckpt_path is not None:
299
+ # Keep VAE in float32 for better quality
300
+ vae = convert_vae(args.vae_ckpt_path, args.scaling_factor, args.version, torch.float32)
301
+
302
+ text_encoder_id = "google/t5-v1_1-xxl"
303
+ tokenizer = T5Tokenizer.from_pretrained(text_encoder_id, model_max_length=TOKENIZER_MAX_LENGTH)
304
+ text_encoder = T5EncoderModel.from_pretrained(text_encoder_id, cache_dir=args.text_encoder_cache_dir)
305
+
306
+ if args.typecast_text_encoder:
307
+ text_encoder = text_encoder.to(dtype=dtype)
308
+
309
+ # Apparently, the conversion does not work anymore without this :shrug:
310
+ for param in text_encoder.parameters():
311
+ param.data = param.data.contiguous()
312
+
313
+ scheduler = CogVideoXDDIMScheduler.from_config(
314
+ {
315
+ "snr_shift_scale": args.snr_shift_scale,
316
+ "beta_end": 0.012,
317
+ "beta_schedule": "scaled_linear",
318
+ "beta_start": 0.00085,
319
+ "clip_sample": False,
320
+ "num_train_timesteps": 1000,
321
+ "prediction_type": "v_prediction",
322
+ "rescale_betas_zero_snr": True,
323
+ "set_alpha_to_one": True,
324
+ "timestep_spacing": "trailing",
325
+ }
326
+ )
327
+ if args.i2v:
328
+ pipeline_cls = CogVideoXImageToVideoPipeline
329
+ else:
330
+ pipeline_cls = CogVideoXPipeline
331
+
332
+ pipe = pipeline_cls(
333
+ tokenizer=tokenizer,
334
+ text_encoder=text_encoder,
335
+ vae=vae,
336
+ transformer=transformer,
337
+ scheduler=scheduler,
338
+ )
339
+
340
+ # We don't use variant here because the model must be run in fp16 (2B) or bf16 (5B). It would be weird
341
+ # for users to specify variant when the default is not fp32 and they want to run with the correct default (which
342
+ # is either fp16/bf16 here).
343
+
344
+ # This is necessary This is necessary for users with insufficient memory,
345
+ # such as those using Colab and notebooks, as it can save some memory used for model loading.
346
+ pipe.save_pretrained(args.output_path, safe_serialization=True, max_shard_size="5GB", push_to_hub=args.push_to_hub)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview3_to_diffusers.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert a CogView3 checkpoint to the Diffusers format.
3
+
4
+ This script converts a CogView3 checkpoint to the Diffusers format, which can then be used
5
+ with the Diffusers library.
6
+
7
+ Example usage:
8
+ python scripts/convert_cogview3_to_diffusers.py \
9
+ --transformer_checkpoint_path 'your path/cogview3plus_3b/1/mp_rank_00_model_states.pt' \
10
+ --vae_checkpoint_path 'your path/3plus_ae/imagekl_ch16.pt' \
11
+ --output_path "/raid/yiyi/cogview3_diffusers" \
12
+ --dtype "bf16"
13
+
14
+ Arguments:
15
+ --transformer_checkpoint_path: Path to Transformer state dict.
16
+ --vae_checkpoint_path: Path to VAE state dict.
17
+ --output_path: The path to save the converted model.
18
+ --push_to_hub: Whether to push the converted checkpoint to the HF Hub or not. Defaults to `False`.
19
+ --text_encoder_cache_dir: Cache directory where text encoder is located. Defaults to None, which means HF_HOME will be used
20
+ --dtype: The dtype to save the model in (default: "bf16", options: "fp16", "bf16", "fp32"). If None, the dtype of the state dict is considered.
21
+
22
+ Default is "bf16" because CogView3 uses bfloat16 for Training.
23
+
24
+ Note: You must provide either --original_state_dict_repo_id or --checkpoint_path.
25
+ """
26
+
27
+ import argparse
28
+ from contextlib import nullcontext
29
+
30
+ import torch
31
+ from accelerate import init_empty_weights
32
+ from transformers import T5EncoderModel, T5Tokenizer
33
+
34
+ from diffusers import AutoencoderKL, CogVideoXDDIMScheduler, CogView3PlusPipeline, CogView3PlusTransformer2DModel
35
+ from diffusers.loaders.single_file_utils import convert_ldm_vae_checkpoint
36
+ from diffusers.utils.import_utils import is_accelerate_available
37
+
38
+
39
+ CTX = init_empty_weights if is_accelerate_available() else nullcontext
40
+
41
+ TOKENIZER_MAX_LENGTH = 224
42
+
43
+ parser = argparse.ArgumentParser()
44
+ parser.add_argument("--transformer_checkpoint_path", default=None, type=str)
45
+ parser.add_argument("--vae_checkpoint_path", default=None, type=str)
46
+ parser.add_argument("--output_path", required=True, type=str)
47
+ parser.add_argument("--push_to_hub", action="store_true", default=False, help="Whether to push to HF Hub after saving")
48
+ parser.add_argument("--text_encoder_cache_dir", type=str, default=None, help="Path to text encoder cache directory")
49
+ parser.add_argument("--dtype", type=str, default="bf16")
50
+
51
+ args = parser.parse_args()
52
+
53
+
54
+ # this is specific to `AdaLayerNormContinuous`:
55
+ # diffusers implementation split the linear projection into the scale, shift while CogView3 split it tino shift, scale
56
+ def swap_scale_shift(weight, dim):
57
+ shift, scale = weight.chunk(2, dim=0)
58
+ new_weight = torch.cat([scale, shift], dim=0)
59
+ return new_weight
60
+
61
+
62
+ def convert_cogview3_transformer_checkpoint_to_diffusers(ckpt_path):
63
+ original_state_dict = torch.load(ckpt_path, map_location="cpu")
64
+ original_state_dict = original_state_dict["module"]
65
+ original_state_dict = {k.replace("model.diffusion_model.", ""): v for k, v in original_state_dict.items()}
66
+
67
+ new_state_dict = {}
68
+
69
+ # Convert patch_embed
70
+ new_state_dict["patch_embed.proj.weight"] = original_state_dict.pop("mixins.patch_embed.proj.weight")
71
+ new_state_dict["patch_embed.proj.bias"] = original_state_dict.pop("mixins.patch_embed.proj.bias")
72
+ new_state_dict["patch_embed.text_proj.weight"] = original_state_dict.pop("mixins.patch_embed.text_proj.weight")
73
+ new_state_dict["patch_embed.text_proj.bias"] = original_state_dict.pop("mixins.patch_embed.text_proj.bias")
74
+
75
+ # Convert time_condition_embed
76
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.weight"] = original_state_dict.pop(
77
+ "time_embed.0.weight"
78
+ )
79
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.bias"] = original_state_dict.pop(
80
+ "time_embed.0.bias"
81
+ )
82
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.weight"] = original_state_dict.pop(
83
+ "time_embed.2.weight"
84
+ )
85
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.bias"] = original_state_dict.pop(
86
+ "time_embed.2.bias"
87
+ )
88
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.weight"] = original_state_dict.pop(
89
+ "label_emb.0.0.weight"
90
+ )
91
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.bias"] = original_state_dict.pop(
92
+ "label_emb.0.0.bias"
93
+ )
94
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.weight"] = original_state_dict.pop(
95
+ "label_emb.0.2.weight"
96
+ )
97
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.bias"] = original_state_dict.pop(
98
+ "label_emb.0.2.bias"
99
+ )
100
+
101
+ # Convert transformer blocks
102
+ for i in range(30):
103
+ block_prefix = f"transformer_blocks.{i}."
104
+ old_prefix = f"transformer.layers.{i}."
105
+ adaln_prefix = f"mixins.adaln.adaln_modules.{i}."
106
+
107
+ new_state_dict[block_prefix + "norm1.linear.weight"] = original_state_dict.pop(adaln_prefix + "1.weight")
108
+ new_state_dict[block_prefix + "norm1.linear.bias"] = original_state_dict.pop(adaln_prefix + "1.bias")
109
+
110
+ qkv_weight = original_state_dict.pop(old_prefix + "attention.query_key_value.weight")
111
+ qkv_bias = original_state_dict.pop(old_prefix + "attention.query_key_value.bias")
112
+ q, k, v = qkv_weight.chunk(3, dim=0)
113
+ q_bias, k_bias, v_bias = qkv_bias.chunk(3, dim=0)
114
+
115
+ new_state_dict[block_prefix + "attn1.to_q.weight"] = q
116
+ new_state_dict[block_prefix + "attn1.to_q.bias"] = q_bias
117
+ new_state_dict[block_prefix + "attn1.to_k.weight"] = k
118
+ new_state_dict[block_prefix + "attn1.to_k.bias"] = k_bias
119
+ new_state_dict[block_prefix + "attn1.to_v.weight"] = v
120
+ new_state_dict[block_prefix + "attn1.to_v.bias"] = v_bias
121
+
122
+ new_state_dict[block_prefix + "attn1.to_out.0.weight"] = original_state_dict.pop(
123
+ old_prefix + "attention.dense.weight"
124
+ )
125
+ new_state_dict[block_prefix + "attn1.to_out.0.bias"] = original_state_dict.pop(
126
+ old_prefix + "attention.dense.bias"
127
+ )
128
+
129
+ new_state_dict[block_prefix + "ff.net.0.proj.weight"] = original_state_dict.pop(
130
+ old_prefix + "mlp.dense_h_to_4h.weight"
131
+ )
132
+ new_state_dict[block_prefix + "ff.net.0.proj.bias"] = original_state_dict.pop(
133
+ old_prefix + "mlp.dense_h_to_4h.bias"
134
+ )
135
+ new_state_dict[block_prefix + "ff.net.2.weight"] = original_state_dict.pop(
136
+ old_prefix + "mlp.dense_4h_to_h.weight"
137
+ )
138
+ new_state_dict[block_prefix + "ff.net.2.bias"] = original_state_dict.pop(old_prefix + "mlp.dense_4h_to_h.bias")
139
+
140
+ # Convert final norm and projection
141
+ new_state_dict["norm_out.linear.weight"] = swap_scale_shift(
142
+ original_state_dict.pop("mixins.final_layer.adaln.1.weight"), dim=0
143
+ )
144
+ new_state_dict["norm_out.linear.bias"] = swap_scale_shift(
145
+ original_state_dict.pop("mixins.final_layer.adaln.1.bias"), dim=0
146
+ )
147
+ new_state_dict["proj_out.weight"] = original_state_dict.pop("mixins.final_layer.linear.weight")
148
+ new_state_dict["proj_out.bias"] = original_state_dict.pop("mixins.final_layer.linear.bias")
149
+
150
+ return new_state_dict
151
+
152
+
153
+ def convert_cogview3_vae_checkpoint_to_diffusers(ckpt_path, vae_config):
154
+ original_state_dict = torch.load(ckpt_path, map_location="cpu")["state_dict"]
155
+ return convert_ldm_vae_checkpoint(original_state_dict, vae_config)
156
+
157
+
158
+ def main(args):
159
+ if args.dtype == "fp16":
160
+ dtype = torch.float16
161
+ elif args.dtype == "bf16":
162
+ dtype = torch.bfloat16
163
+ elif args.dtype == "fp32":
164
+ dtype = torch.float32
165
+ else:
166
+ raise ValueError(f"Unsupported dtype: {args.dtype}")
167
+
168
+ transformer = None
169
+ vae = None
170
+
171
+ if args.transformer_checkpoint_path is not None:
172
+ converted_transformer_state_dict = convert_cogview3_transformer_checkpoint_to_diffusers(
173
+ args.transformer_checkpoint_path
174
+ )
175
+ transformer = CogView3PlusTransformer2DModel()
176
+ transformer.load_state_dict(converted_transformer_state_dict, strict=True)
177
+ if dtype is not None:
178
+ # Original checkpoint data type will be preserved
179
+ transformer = transformer.to(dtype=dtype)
180
+
181
+ if args.vae_checkpoint_path is not None:
182
+ vae_config = {
183
+ "in_channels": 3,
184
+ "out_channels": 3,
185
+ "down_block_types": ("DownEncoderBlock2D",) * 4,
186
+ "up_block_types": ("UpDecoderBlock2D",) * 4,
187
+ "block_out_channels": (128, 512, 1024, 1024),
188
+ "layers_per_block": 3,
189
+ "act_fn": "silu",
190
+ "latent_channels": 16,
191
+ "norm_num_groups": 32,
192
+ "sample_size": 1024,
193
+ "scaling_factor": 1.0,
194
+ "force_upcast": True,
195
+ "use_quant_conv": False,
196
+ "use_post_quant_conv": False,
197
+ "mid_block_add_attention": False,
198
+ }
199
+ converted_vae_state_dict = convert_cogview3_vae_checkpoint_to_diffusers(args.vae_checkpoint_path, vae_config)
200
+ vae = AutoencoderKL(**vae_config)
201
+ vae.load_state_dict(converted_vae_state_dict, strict=True)
202
+ if dtype is not None:
203
+ vae = vae.to(dtype=dtype)
204
+
205
+ text_encoder_id = "google/t5-v1_1-xxl"
206
+ tokenizer = T5Tokenizer.from_pretrained(text_encoder_id, model_max_length=TOKENIZER_MAX_LENGTH)
207
+ text_encoder = T5EncoderModel.from_pretrained(text_encoder_id, cache_dir=args.text_encoder_cache_dir)
208
+
209
+ # Apparently, the conversion does not work anymore without this :shrug:
210
+ for param in text_encoder.parameters():
211
+ param.data = param.data.contiguous()
212
+
213
+ scheduler = CogVideoXDDIMScheduler.from_config(
214
+ {
215
+ "snr_shift_scale": 4.0,
216
+ "beta_end": 0.012,
217
+ "beta_schedule": "scaled_linear",
218
+ "beta_start": 0.00085,
219
+ "clip_sample": False,
220
+ "num_train_timesteps": 1000,
221
+ "prediction_type": "v_prediction",
222
+ "rescale_betas_zero_snr": True,
223
+ "set_alpha_to_one": True,
224
+ "timestep_spacing": "trailing",
225
+ }
226
+ )
227
+
228
+ pipe = CogView3PlusPipeline(
229
+ tokenizer=tokenizer,
230
+ text_encoder=text_encoder,
231
+ vae=vae,
232
+ transformer=transformer,
233
+ scheduler=scheduler,
234
+ )
235
+
236
+ # This is necessary for users with insufficient memory, such as those using Colab and notebooks, as it can
237
+ # save some memory used for model loading.
238
+ pipe.save_pretrained(args.output_path, safe_serialization=True, max_shard_size="5GB", push_to_hub=args.push_to_hub)
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview4_to_diffusers.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert a CogView4 checkpoint from SAT(https://github.com/THUDM/SwissArmyTransformer) to the Diffusers format.
3
+ (deprecated Since 2025-02-07 and will remove it in later CogView4 version)
4
+
5
+ This script converts a CogView4 checkpoint to the Diffusers format, which can then be used
6
+ with the Diffusers library.
7
+
8
+ Example usage:
9
+ python scripts/convert_cogview4_to_diffusers.py \
10
+ --transformer_checkpoint_path 'your path/cogview4_6b/1/mp_rank_00_model_states.pt' \
11
+ --vae_checkpoint_path 'your path/cogview4_6b/imagekl_ch16.pt' \
12
+ --output_path "THUDM/CogView4-6B" \
13
+ --dtype "bf16"
14
+
15
+ Arguments:
16
+ --transformer_checkpoint_path: Path to Transformer state dict.
17
+ --vae_checkpoint_path: Path to VAE state dict.
18
+ --output_path: The path to save the converted model.
19
+ --push_to_hub: Whether to push the converted checkpoint to the HF Hub or not. Defaults to `False`.
20
+ --text_encoder_cache_dir: Cache directory where text encoder is located. Defaults to None, which means HF_HOME will be used
21
+ --dtype: The dtype to save the model in (default: "bf16", options: "fp16", "bf16", "fp32"). If None, the dtype of the state dict is considered.
22
+
23
+ Default is "bf16" because CogView4 uses bfloat16 for Training.
24
+
25
+ Note: You must provide either --original_state_dict_repo_id or --checkpoint_path.
26
+ """
27
+
28
+ import argparse
29
+ from contextlib import nullcontext
30
+
31
+ import torch
32
+ from accelerate import init_empty_weights
33
+ from transformers import GlmForCausalLM, PreTrainedTokenizerFast
34
+
35
+ from diffusers import AutoencoderKL, CogView4Pipeline, CogView4Transformer2DModel, FlowMatchEulerDiscreteScheduler
36
+ from diffusers.loaders.single_file_utils import convert_ldm_vae_checkpoint
37
+ from diffusers.utils.import_utils import is_accelerate_available
38
+
39
+
40
+ CTX = init_empty_weights if is_accelerate_available() else nullcontext
41
+
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument("--transformer_checkpoint_path", default=None, type=str)
44
+ parser.add_argument("--vae_checkpoint_path", default=None, type=str)
45
+ parser.add_argument("--output_path", required=True, type=str)
46
+ parser.add_argument("--push_to_hub", action="store_true", default=False, help="Whether to push to HF Hub after saving")
47
+ parser.add_argument("--text_encoder_cache_dir", type=str, default=None, help="Path to text encoder cache directory")
48
+ parser.add_argument("--dtype", type=str, default="bf16")
49
+
50
+ args = parser.parse_args()
51
+
52
+
53
+ # this is specific to `AdaLayerNormContinuous`:
54
+ # diffusers implementation split the linear projection into the scale, shift while CogView4 split it tino shift, scale
55
+ def swap_scale_shift(weight, dim):
56
+ """
57
+ Swap the scale and shift components in the weight tensor.
58
+
59
+ Args:
60
+ weight (torch.Tensor): The original weight tensor.
61
+ dim (int): The dimension along which to split.
62
+
63
+ Returns:
64
+ torch.Tensor: The modified weight tensor with scale and shift swapped.
65
+ """
66
+ shift, scale = weight.chunk(2, dim=dim)
67
+ new_weight = torch.cat([scale, shift], dim=dim)
68
+ return new_weight
69
+
70
+
71
+ def convert_cogview4_transformer_checkpoint_to_diffusers(ckpt_path):
72
+ original_state_dict = torch.load(ckpt_path, map_location="cpu")
73
+ original_state_dict = original_state_dict["module"]
74
+ original_state_dict = {k.replace("model.diffusion_model.", ""): v for k, v in original_state_dict.items()}
75
+
76
+ new_state_dict = {}
77
+
78
+ # Convert patch_embed
79
+ new_state_dict["patch_embed.proj.weight"] = original_state_dict.pop("mixins.patch_embed.proj.weight")
80
+ new_state_dict["patch_embed.proj.bias"] = original_state_dict.pop("mixins.patch_embed.proj.bias")
81
+ new_state_dict["patch_embed.text_proj.weight"] = original_state_dict.pop("mixins.patch_embed.text_proj.weight")
82
+ new_state_dict["patch_embed.text_proj.bias"] = original_state_dict.pop("mixins.patch_embed.text_proj.bias")
83
+
84
+ # Convert time_condition_embed
85
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.weight"] = original_state_dict.pop(
86
+ "time_embed.0.weight"
87
+ )
88
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.bias"] = original_state_dict.pop(
89
+ "time_embed.0.bias"
90
+ )
91
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.weight"] = original_state_dict.pop(
92
+ "time_embed.2.weight"
93
+ )
94
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.bias"] = original_state_dict.pop(
95
+ "time_embed.2.bias"
96
+ )
97
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.weight"] = original_state_dict.pop(
98
+ "label_emb.0.0.weight"
99
+ )
100
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.bias"] = original_state_dict.pop(
101
+ "label_emb.0.0.bias"
102
+ )
103
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.weight"] = original_state_dict.pop(
104
+ "label_emb.0.2.weight"
105
+ )
106
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.bias"] = original_state_dict.pop(
107
+ "label_emb.0.2.bias"
108
+ )
109
+
110
+ # Convert transformer blocks, for cogview4 is 28 blocks
111
+ for i in range(28):
112
+ block_prefix = f"transformer_blocks.{i}."
113
+ old_prefix = f"transformer.layers.{i}."
114
+ adaln_prefix = f"mixins.adaln.adaln_modules.{i}."
115
+ new_state_dict[block_prefix + "norm1.linear.weight"] = original_state_dict.pop(adaln_prefix + "1.weight")
116
+ new_state_dict[block_prefix + "norm1.linear.bias"] = original_state_dict.pop(adaln_prefix + "1.bias")
117
+
118
+ qkv_weight = original_state_dict.pop(old_prefix + "attention.query_key_value.weight")
119
+ qkv_bias = original_state_dict.pop(old_prefix + "attention.query_key_value.bias")
120
+ q, k, v = qkv_weight.chunk(3, dim=0)
121
+ q_bias, k_bias, v_bias = qkv_bias.chunk(3, dim=0)
122
+
123
+ new_state_dict[block_prefix + "attn1.to_q.weight"] = q
124
+ new_state_dict[block_prefix + "attn1.to_q.bias"] = q_bias
125
+ new_state_dict[block_prefix + "attn1.to_k.weight"] = k
126
+ new_state_dict[block_prefix + "attn1.to_k.bias"] = k_bias
127
+ new_state_dict[block_prefix + "attn1.to_v.weight"] = v
128
+ new_state_dict[block_prefix + "attn1.to_v.bias"] = v_bias
129
+
130
+ new_state_dict[block_prefix + "attn1.to_out.0.weight"] = original_state_dict.pop(
131
+ old_prefix + "attention.dense.weight"
132
+ )
133
+ new_state_dict[block_prefix + "attn1.to_out.0.bias"] = original_state_dict.pop(
134
+ old_prefix + "attention.dense.bias"
135
+ )
136
+
137
+ new_state_dict[block_prefix + "ff.net.0.proj.weight"] = original_state_dict.pop(
138
+ old_prefix + "mlp.dense_h_to_4h.weight"
139
+ )
140
+ new_state_dict[block_prefix + "ff.net.0.proj.bias"] = original_state_dict.pop(
141
+ old_prefix + "mlp.dense_h_to_4h.bias"
142
+ )
143
+ new_state_dict[block_prefix + "ff.net.2.weight"] = original_state_dict.pop(
144
+ old_prefix + "mlp.dense_4h_to_h.weight"
145
+ )
146
+ new_state_dict[block_prefix + "ff.net.2.bias"] = original_state_dict.pop(old_prefix + "mlp.dense_4h_to_h.bias")
147
+
148
+ # Convert final norm and projection
149
+ new_state_dict["norm_out.linear.weight"] = swap_scale_shift(
150
+ original_state_dict.pop("mixins.final_layer.adaln.1.weight"), dim=0
151
+ )
152
+ new_state_dict["norm_out.linear.bias"] = swap_scale_shift(
153
+ original_state_dict.pop("mixins.final_layer.adaln.1.bias"), dim=0
154
+ )
155
+ new_state_dict["proj_out.weight"] = original_state_dict.pop("mixins.final_layer.linear.weight")
156
+ new_state_dict["proj_out.bias"] = original_state_dict.pop("mixins.final_layer.linear.bias")
157
+
158
+ return new_state_dict
159
+
160
+
161
+ def convert_cogview4_vae_checkpoint_to_diffusers(ckpt_path, vae_config):
162
+ original_state_dict = torch.load(ckpt_path, map_location="cpu")["state_dict"]
163
+ return convert_ldm_vae_checkpoint(original_state_dict, vae_config)
164
+
165
+
166
+ def main(args):
167
+ if args.dtype == "fp16":
168
+ dtype = torch.float16
169
+ elif args.dtype == "bf16":
170
+ dtype = torch.bfloat16
171
+ elif args.dtype == "fp32":
172
+ dtype = torch.float32
173
+ else:
174
+ raise ValueError(f"Unsupported dtype: {args.dtype}")
175
+
176
+ transformer = None
177
+ vae = None
178
+
179
+ if args.transformer_checkpoint_path is not None:
180
+ converted_transformer_state_dict = convert_cogview4_transformer_checkpoint_to_diffusers(
181
+ args.transformer_checkpoint_path
182
+ )
183
+ transformer = CogView4Transformer2DModel(
184
+ patch_size=2,
185
+ in_channels=16,
186
+ num_layers=28,
187
+ attention_head_dim=128,
188
+ num_attention_heads=32,
189
+ out_channels=16,
190
+ text_embed_dim=4096,
191
+ time_embed_dim=512,
192
+ condition_dim=256,
193
+ pos_embed_max_size=128,
194
+ )
195
+ transformer.load_state_dict(converted_transformer_state_dict, strict=True)
196
+ if dtype is not None:
197
+ # Original checkpoint data type will be preserved
198
+ transformer = transformer.to(dtype=dtype)
199
+
200
+ if args.vae_checkpoint_path is not None:
201
+ vae_config = {
202
+ "in_channels": 3,
203
+ "out_channels": 3,
204
+ "down_block_types": ("DownEncoderBlock2D",) * 4,
205
+ "up_block_types": ("UpDecoderBlock2D",) * 4,
206
+ "block_out_channels": (128, 512, 1024, 1024),
207
+ "layers_per_block": 3,
208
+ "act_fn": "silu",
209
+ "latent_channels": 16,
210
+ "norm_num_groups": 32,
211
+ "sample_size": 1024,
212
+ "scaling_factor": 1.0,
213
+ "shift_factor": 0.0,
214
+ "force_upcast": True,
215
+ "use_quant_conv": False,
216
+ "use_post_quant_conv": False,
217
+ "mid_block_add_attention": False,
218
+ }
219
+ converted_vae_state_dict = convert_cogview4_vae_checkpoint_to_diffusers(args.vae_checkpoint_path, vae_config)
220
+ vae = AutoencoderKL(**vae_config)
221
+ vae.load_state_dict(converted_vae_state_dict, strict=True)
222
+ if dtype is not None:
223
+ vae = vae.to(dtype=dtype)
224
+
225
+ text_encoder_id = "THUDM/glm-4-9b-hf"
226
+ tokenizer = PreTrainedTokenizerFast.from_pretrained(text_encoder_id)
227
+ text_encoder = GlmForCausalLM.from_pretrained(
228
+ text_encoder_id,
229
+ cache_dir=args.text_encoder_cache_dir,
230
+ torch_dtype=torch.bfloat16 if args.dtype == "bf16" else torch.float32,
231
+ )
232
+
233
+ for param in text_encoder.parameters():
234
+ param.data = param.data.contiguous()
235
+
236
+ scheduler = FlowMatchEulerDiscreteScheduler(
237
+ base_shift=0.25, max_shift=0.75, base_image_seq_len=256, use_dynamic_shifting=True, time_shift_type="linear"
238
+ )
239
+
240
+ pipe = CogView4Pipeline(
241
+ tokenizer=tokenizer,
242
+ text_encoder=text_encoder,
243
+ vae=vae,
244
+ transformer=transformer,
245
+ scheduler=scheduler,
246
+ )
247
+
248
+ # This is necessary for users with insufficient memory, such as those using Colab and notebooks, as it can
249
+ # save some memory used for model loading.
250
+ pipe.save_pretrained(args.output_path, safe_serialization=True, max_shard_size="5GB", push_to_hub=args.push_to_hub)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_cogview4_to_diffusers_megatron.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convert a CogView4 checkpoint from Megatron to the Diffusers format.
3
+
4
+ Example usage:
5
+ python scripts/convert_cogview4_to_diffusers.py \
6
+ --transformer_checkpoint_path 'your path/cogview4_6b/mp_rank_00/model_optim_rng.pt' \
7
+ --vae_checkpoint_path 'your path/cogview4_6b/imagekl_ch16.pt' \
8
+ --output_path "THUDM/CogView4-6B" \
9
+ --dtype "bf16"
10
+
11
+ Arguments:
12
+ --transformer_checkpoint_path: Path to Transformer state dict.
13
+ --vae_checkpoint_path: Path to VAE state dict.
14
+ --output_path: The path to save the converted model.
15
+ --push_to_hub: Whether to push the converted checkpoint to the HF Hub or not. Defaults to `False`.
16
+ --text_encoder_cache_dir: Cache directory where text encoder is located. Defaults to None, which means HF_HOME will be used.
17
+ --dtype: The dtype to save the model in (default: "bf16", options: "fp16", "bf16", "fp32"). If None, the dtype of the state dict is considered.
18
+
19
+ Default is "bf16" because CogView4 uses bfloat16 for training.
20
+
21
+ Note: You must provide either --transformer_checkpoint_path or --vae_checkpoint_path.
22
+ """
23
+
24
+ import argparse
25
+
26
+ import torch
27
+ from tqdm import tqdm
28
+ from transformers import GlmModel, PreTrainedTokenizerFast
29
+
30
+ from diffusers import (
31
+ AutoencoderKL,
32
+ CogView4ControlPipeline,
33
+ CogView4Pipeline,
34
+ CogView4Transformer2DModel,
35
+ FlowMatchEulerDiscreteScheduler,
36
+ )
37
+ from diffusers.loaders.single_file_utils import convert_ldm_vae_checkpoint
38
+
39
+
40
+ parser = argparse.ArgumentParser()
41
+ parser.add_argument(
42
+ "--transformer_checkpoint_path",
43
+ default=None,
44
+ type=str,
45
+ help="Path to Megatron (not SAT) Transformer checkpoint, e.g., 'model_optim_rng.pt'.",
46
+ )
47
+ parser.add_argument(
48
+ "--vae_checkpoint_path",
49
+ default=None,
50
+ type=str,
51
+ help="(Optional) Path to VAE checkpoint, e.g., 'imagekl_ch16.pt'.",
52
+ )
53
+ parser.add_argument(
54
+ "--output_path",
55
+ required=True,
56
+ type=str,
57
+ help="Directory to save the final Diffusers format pipeline.",
58
+ )
59
+ parser.add_argument(
60
+ "--push_to_hub",
61
+ action="store_true",
62
+ default=False,
63
+ help="Whether to push the converted model to the HuggingFace Hub.",
64
+ )
65
+ parser.add_argument(
66
+ "--text_encoder_cache_dir",
67
+ type=str,
68
+ default=None,
69
+ help="Specify the cache directory for the text encoder.",
70
+ )
71
+ parser.add_argument(
72
+ "--dtype",
73
+ type=str,
74
+ default="bf16",
75
+ choices=["fp16", "bf16", "fp32"],
76
+ help="Data type to save the model in.",
77
+ )
78
+
79
+ parser.add_argument(
80
+ "--num_layers",
81
+ type=int,
82
+ default=28,
83
+ help="Number of Transformer layers (e.g., 28, 48...).",
84
+ )
85
+ parser.add_argument(
86
+ "--num_heads",
87
+ type=int,
88
+ default=32,
89
+ help="Number of attention heads.",
90
+ )
91
+ parser.add_argument(
92
+ "--hidden_size",
93
+ type=int,
94
+ default=4096,
95
+ help="Transformer hidden dimension size.",
96
+ )
97
+ parser.add_argument(
98
+ "--attention_head_dim",
99
+ type=int,
100
+ default=128,
101
+ help="Dimension of each attention head.",
102
+ )
103
+ parser.add_argument(
104
+ "--time_embed_dim",
105
+ type=int,
106
+ default=512,
107
+ help="Dimension of time embeddings.",
108
+ )
109
+ parser.add_argument(
110
+ "--condition_dim",
111
+ type=int,
112
+ default=256,
113
+ help="Dimension of condition embeddings.",
114
+ )
115
+ parser.add_argument(
116
+ "--pos_embed_max_size",
117
+ type=int,
118
+ default=128,
119
+ help="Maximum size for positional embeddings.",
120
+ )
121
+ parser.add_argument(
122
+ "--control",
123
+ action="store_true",
124
+ default=False,
125
+ help="Whether to use control model.",
126
+ )
127
+
128
+ args = parser.parse_args()
129
+
130
+
131
+ def swap_scale_shift(weight, dim):
132
+ """
133
+ Swap the scale and shift components in the weight tensor.
134
+
135
+ Args:
136
+ weight (torch.Tensor): The original weight tensor.
137
+ dim (int): The dimension along which to split.
138
+
139
+ Returns:
140
+ torch.Tensor: The modified weight tensor with scale and shift swapped.
141
+ """
142
+ shift, scale = weight.chunk(2, dim=dim)
143
+ new_weight = torch.cat([scale, shift], dim=dim)
144
+ return new_weight
145
+
146
+
147
+ def convert_megatron_transformer_checkpoint_to_diffusers(
148
+ ckpt_path: str,
149
+ num_layers: int,
150
+ num_heads: int,
151
+ hidden_size: int,
152
+ ):
153
+ """
154
+ Convert a Megatron Transformer checkpoint to Diffusers format.
155
+
156
+ Args:
157
+ ckpt_path (str): Path to the Megatron Transformer checkpoint.
158
+ num_layers (int): Number of Transformer layers.
159
+ num_heads (int): Number of attention heads.
160
+ hidden_size (int): Hidden size of the Transformer.
161
+
162
+ Returns:
163
+ dict: The converted state dictionary compatible with Diffusers.
164
+ """
165
+ ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
166
+ mega = ckpt["model"]
167
+
168
+ new_state_dict = {}
169
+
170
+ # Patch Embedding
171
+ new_state_dict["patch_embed.proj.weight"] = mega["encoder_expand_linear.weight"].reshape(
172
+ hidden_size, 128 if args.control else 64
173
+ )
174
+ new_state_dict["patch_embed.proj.bias"] = mega["encoder_expand_linear.bias"]
175
+ new_state_dict["patch_embed.text_proj.weight"] = mega["text_projector.weight"]
176
+ new_state_dict["patch_embed.text_proj.bias"] = mega["text_projector.bias"]
177
+
178
+ # Time Condition Embedding
179
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.weight"] = mega[
180
+ "time_embedding.time_embed.0.weight"
181
+ ]
182
+ new_state_dict["time_condition_embed.timestep_embedder.linear_1.bias"] = mega["time_embedding.time_embed.0.bias"]
183
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.weight"] = mega[
184
+ "time_embedding.time_embed.2.weight"
185
+ ]
186
+ new_state_dict["time_condition_embed.timestep_embedder.linear_2.bias"] = mega["time_embedding.time_embed.2.bias"]
187
+
188
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.weight"] = mega[
189
+ "label_embedding.label_embed.0.weight"
190
+ ]
191
+ new_state_dict["time_condition_embed.condition_embedder.linear_1.bias"] = mega[
192
+ "label_embedding.label_embed.0.bias"
193
+ ]
194
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.weight"] = mega[
195
+ "label_embedding.label_embed.2.weight"
196
+ ]
197
+ new_state_dict["time_condition_embed.condition_embedder.linear_2.bias"] = mega[
198
+ "label_embedding.label_embed.2.bias"
199
+ ]
200
+
201
+ # Convert each Transformer layer
202
+ for i in tqdm(range(num_layers), desc="Converting layers (Megatron->Diffusers)"):
203
+ block_prefix = f"transformer_blocks.{i}."
204
+
205
+ # AdaLayerNorm
206
+ new_state_dict[block_prefix + "norm1.linear.weight"] = mega[f"decoder.layers.{i}.adaln.weight"]
207
+ new_state_dict[block_prefix + "norm1.linear.bias"] = mega[f"decoder.layers.{i}.adaln.bias"]
208
+ qkv_weight = mega[f"decoder.layers.{i}.self_attention.linear_qkv.weight"]
209
+ qkv_bias = mega[f"decoder.layers.{i}.self_attention.linear_qkv.bias"]
210
+
211
+ # Reshape to match SAT logic
212
+ qkv_weight = qkv_weight.view(num_heads, 3, hidden_size // num_heads, hidden_size)
213
+ qkv_weight = qkv_weight.permute(1, 0, 2, 3).reshape(3 * hidden_size, hidden_size)
214
+
215
+ qkv_bias = qkv_bias.view(num_heads, 3, hidden_size // num_heads)
216
+ qkv_bias = qkv_bias.permute(1, 0, 2).reshape(3 * hidden_size)
217
+
218
+ # Assign to Diffusers keys
219
+ q, k, v = torch.chunk(qkv_weight, 3, dim=0)
220
+ qb, kb, vb = torch.chunk(qkv_bias, 3, dim=0)
221
+
222
+ new_state_dict[block_prefix + "attn1.to_q.weight"] = q
223
+ new_state_dict[block_prefix + "attn1.to_q.bias"] = qb
224
+ new_state_dict[block_prefix + "attn1.to_k.weight"] = k
225
+ new_state_dict[block_prefix + "attn1.to_k.bias"] = kb
226
+ new_state_dict[block_prefix + "attn1.to_v.weight"] = v
227
+ new_state_dict[block_prefix + "attn1.to_v.bias"] = vb
228
+
229
+ # Attention Output
230
+ new_state_dict[block_prefix + "attn1.to_out.0.weight"] = mega[
231
+ f"decoder.layers.{i}.self_attention.linear_proj.weight"
232
+ ]
233
+ new_state_dict[block_prefix + "attn1.to_out.0.bias"] = mega[
234
+ f"decoder.layers.{i}.self_attention.linear_proj.bias"
235
+ ]
236
+
237
+ # MLP
238
+ new_state_dict[block_prefix + "ff.net.0.proj.weight"] = mega[f"decoder.layers.{i}.mlp.linear_fc1.weight"]
239
+ new_state_dict[block_prefix + "ff.net.0.proj.bias"] = mega[f"decoder.layers.{i}.mlp.linear_fc1.bias"]
240
+ new_state_dict[block_prefix + "ff.net.2.weight"] = mega[f"decoder.layers.{i}.mlp.linear_fc2.weight"]
241
+ new_state_dict[block_prefix + "ff.net.2.bias"] = mega[f"decoder.layers.{i}.mlp.linear_fc2.bias"]
242
+
243
+ # Final Layers
244
+ new_state_dict["norm_out.linear.weight"] = swap_scale_shift(mega["adaln_final.weight"], dim=0)
245
+ new_state_dict["norm_out.linear.bias"] = swap_scale_shift(mega["adaln_final.bias"], dim=0)
246
+ new_state_dict["proj_out.weight"] = mega["output_projector.weight"]
247
+ new_state_dict["proj_out.bias"] = mega["output_projector.bias"]
248
+
249
+ return new_state_dict
250
+
251
+
252
+ def convert_cogview4_vae_checkpoint_to_diffusers(ckpt_path, vae_config):
253
+ """
254
+ Convert a CogView4 VAE checkpoint to Diffusers format.
255
+
256
+ Args:
257
+ ckpt_path (str): Path to the VAE checkpoint.
258
+ vae_config (dict): Configuration dictionary for the VAE.
259
+
260
+ Returns:
261
+ dict: The converted VAE state dictionary compatible with Diffusers.
262
+ """
263
+ original_state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=False)["state_dict"]
264
+ return convert_ldm_vae_checkpoint(original_state_dict, vae_config)
265
+
266
+
267
+ def main(args):
268
+ """
269
+ Main function to convert CogView4 checkpoints to Diffusers format.
270
+
271
+ Args:
272
+ args (argparse.Namespace): Parsed command-line arguments.
273
+ """
274
+ # Determine the desired data type
275
+ if args.dtype == "fp16":
276
+ dtype = torch.float16
277
+ elif args.dtype == "bf16":
278
+ dtype = torch.bfloat16
279
+ elif args.dtype == "fp32":
280
+ dtype = torch.float32
281
+ else:
282
+ raise ValueError(f"Unsupported dtype: {args.dtype}")
283
+
284
+ transformer = None
285
+ vae = None
286
+
287
+ # Convert Transformer checkpoint if provided
288
+ if args.transformer_checkpoint_path is not None:
289
+ converted_transformer_state_dict = convert_megatron_transformer_checkpoint_to_diffusers(
290
+ ckpt_path=args.transformer_checkpoint_path,
291
+ num_layers=args.num_layers,
292
+ num_heads=args.num_heads,
293
+ hidden_size=args.hidden_size,
294
+ )
295
+ transformer = CogView4Transformer2DModel(
296
+ patch_size=2,
297
+ in_channels=32 if args.control else 16,
298
+ num_layers=args.num_layers,
299
+ attention_head_dim=args.attention_head_dim,
300
+ num_attention_heads=args.num_heads,
301
+ out_channels=16,
302
+ text_embed_dim=args.hidden_size,
303
+ time_embed_dim=args.time_embed_dim,
304
+ condition_dim=args.condition_dim,
305
+ pos_embed_max_size=args.pos_embed_max_size,
306
+ )
307
+
308
+ transformer.load_state_dict(converted_transformer_state_dict, strict=True)
309
+
310
+ # Convert to the specified dtype
311
+ if dtype is not None:
312
+ transformer = transformer.to(dtype=dtype)
313
+
314
+ # Convert VAE checkpoint if provided
315
+ if args.vae_checkpoint_path is not None:
316
+ vae_config = {
317
+ "in_channels": 3,
318
+ "out_channels": 3,
319
+ "down_block_types": ("DownEncoderBlock2D",) * 4,
320
+ "up_block_types": ("UpDecoderBlock2D",) * 4,
321
+ "block_out_channels": (128, 512, 1024, 1024),
322
+ "layers_per_block": 3,
323
+ "act_fn": "silu",
324
+ "latent_channels": 16,
325
+ "norm_num_groups": 32,
326
+ "sample_size": 1024,
327
+ "scaling_factor": 1.0,
328
+ "shift_factor": 0.0,
329
+ "force_upcast": True,
330
+ "use_quant_conv": False,
331
+ "use_post_quant_conv": False,
332
+ "mid_block_add_attention": False,
333
+ }
334
+ converted_vae_state_dict = convert_cogview4_vae_checkpoint_to_diffusers(args.vae_checkpoint_path, vae_config)
335
+ vae = AutoencoderKL(**vae_config)
336
+ vae.load_state_dict(converted_vae_state_dict, strict=True)
337
+ if dtype is not None:
338
+ vae = vae.to(dtype=dtype)
339
+
340
+ # Load the text encoder and tokenizer
341
+ text_encoder_id = "THUDM/glm-4-9b-hf"
342
+ tokenizer = PreTrainedTokenizerFast.from_pretrained(text_encoder_id)
343
+ text_encoder = GlmModel.from_pretrained(
344
+ text_encoder_id,
345
+ cache_dir=args.text_encoder_cache_dir,
346
+ torch_dtype=torch.bfloat16 if args.dtype == "bf16" else torch.float32,
347
+ )
348
+ for param in text_encoder.parameters():
349
+ param.data = param.data.contiguous()
350
+
351
+ # Initialize the scheduler
352
+ scheduler = FlowMatchEulerDiscreteScheduler(
353
+ base_shift=0.25, max_shift=0.75, base_image_seq_len=256, use_dynamic_shifting=True, time_shift_type="linear"
354
+ )
355
+
356
+ # Create the pipeline
357
+ if args.control:
358
+ pipe = CogView4ControlPipeline(
359
+ tokenizer=tokenizer,
360
+ text_encoder=text_encoder,
361
+ vae=vae,
362
+ transformer=transformer,
363
+ scheduler=scheduler,
364
+ )
365
+ else:
366
+ pipe = CogView4Pipeline(
367
+ tokenizer=tokenizer,
368
+ text_encoder=text_encoder,
369
+ vae=vae,
370
+ transformer=transformer,
371
+ scheduler=scheduler,
372
+ )
373
+
374
+ # Save the converted pipeline
375
+ pipe.save_pretrained(
376
+ args.output_path,
377
+ safe_serialization=True,
378
+ max_shard_size="5GB",
379
+ push_to_hub=args.push_to_hub,
380
+ )
381
+
382
+
383
+ if __name__ == "__main__":
384
+ main(args)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_consistency_decoder.py ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import urllib
4
+ import warnings
5
+ from argparse import ArgumentParser
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from huggingface_hub.utils import insecure_hashlib
11
+ from safetensors.torch import load_file as stl
12
+ from tqdm import tqdm
13
+
14
+ from diffusers import AutoencoderKL, ConsistencyDecoderVAE, DiffusionPipeline, StableDiffusionPipeline, UNet2DModel
15
+ from diffusers.models.autoencoders.vae import Encoder
16
+ from diffusers.models.embeddings import TimestepEmbedding
17
+ from diffusers.models.unets.unet_2d_blocks import ResnetDownsampleBlock2D, ResnetUpsampleBlock2D, UNetMidBlock2D
18
+
19
+
20
+ args = ArgumentParser()
21
+ args.add_argument("--save_pretrained", required=False, default=None, type=str)
22
+ args.add_argument("--test_image", required=True, type=str)
23
+ args = args.parse_args()
24
+
25
+
26
+ def _extract_into_tensor(arr, timesteps, broadcast_shape):
27
+ # from: https://github.com/openai/guided-diffusion/blob/22e0df8183507e13a7813f8d38d51b072ca1e67c/guided_diffusion/gaussian_diffusion.py#L895
28
+ # """
29
+ res = arr[timesteps].float()
30
+ dims_to_append = len(broadcast_shape) - len(res.shape)
31
+ return res[(...,) + (None,) * dims_to_append]
32
+
33
+
34
+ def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
35
+ # from: https://github.com/openai/guided-diffusion/blob/22e0df8183507e13a7813f8d38d51b072ca1e67c/guided_diffusion/gaussian_diffusion.py#L45
36
+ betas = []
37
+ for i in range(num_diffusion_timesteps):
38
+ t1 = i / num_diffusion_timesteps
39
+ t2 = (i + 1) / num_diffusion_timesteps
40
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
41
+ return torch.tensor(betas)
42
+
43
+
44
+ def _download(url: str, root: str):
45
+ os.makedirs(root, exist_ok=True)
46
+ filename = os.path.basename(url)
47
+
48
+ expected_sha256 = url.split("/")[-2]
49
+ download_target = os.path.join(root, filename)
50
+
51
+ if os.path.exists(download_target) and not os.path.isfile(download_target):
52
+ raise RuntimeError(f"{download_target} exists and is not a regular file")
53
+
54
+ if os.path.isfile(download_target):
55
+ if insecure_hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
56
+ return download_target
57
+ else:
58
+ warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
59
+
60
+ with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
61
+ with tqdm(
62
+ total=int(source.info().get("Content-Length")),
63
+ ncols=80,
64
+ unit="iB",
65
+ unit_scale=True,
66
+ unit_divisor=1024,
67
+ ) as loop:
68
+ while True:
69
+ buffer = source.read(8192)
70
+ if not buffer:
71
+ break
72
+
73
+ output.write(buffer)
74
+ loop.update(len(buffer))
75
+
76
+ if insecure_hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
77
+ raise RuntimeError("Model has been downloaded but the SHA256 checksum does not match")
78
+
79
+ return download_target
80
+
81
+
82
+ class ConsistencyDecoder:
83
+ def __init__(self, device="cuda:0", download_root=os.path.expanduser("~/.cache/clip")):
84
+ self.n_distilled_steps = 64
85
+ download_target = _download(
86
+ "https://openaipublic.azureedge.net/diff-vae/c9cebd3132dd9c42936d803e33424145a748843c8f716c0814838bdc8a2fe7cb/decoder.pt",
87
+ download_root,
88
+ )
89
+ self.ckpt = torch.jit.load(download_target).to(device)
90
+ self.device = device
91
+ sigma_data = 0.5
92
+ betas = betas_for_alpha_bar(1024, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2).to(device)
93
+ alphas = 1.0 - betas
94
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
95
+ self.sqrt_alphas_cumprod = torch.sqrt(alphas_cumprod)
96
+ self.sqrt_one_minus_alphas_cumprod = torch.sqrt(1.0 - alphas_cumprod)
97
+ sqrt_recip_alphas_cumprod = torch.sqrt(1.0 / alphas_cumprod)
98
+ sigmas = torch.sqrt(1.0 / alphas_cumprod - 1)
99
+ self.c_skip = sqrt_recip_alphas_cumprod * sigma_data**2 / (sigmas**2 + sigma_data**2)
100
+ self.c_out = sigmas * sigma_data / (sigmas**2 + sigma_data**2) ** 0.5
101
+ self.c_in = sqrt_recip_alphas_cumprod / (sigmas**2 + sigma_data**2) ** 0.5
102
+
103
+ @staticmethod
104
+ def round_timesteps(timesteps, total_timesteps, n_distilled_steps, truncate_start=True):
105
+ with torch.no_grad():
106
+ space = torch.div(total_timesteps, n_distilled_steps, rounding_mode="floor")
107
+ rounded_timesteps = (torch.div(timesteps, space, rounding_mode="floor") + 1) * space
108
+ if truncate_start:
109
+ rounded_timesteps[rounded_timesteps == total_timesteps] -= space
110
+ else:
111
+ rounded_timesteps[rounded_timesteps == total_timesteps] -= space
112
+ rounded_timesteps[rounded_timesteps == 0] += space
113
+ return rounded_timesteps
114
+
115
+ @staticmethod
116
+ def ldm_transform_latent(z, extra_scale_factor=1):
117
+ channel_means = [0.38862467, 0.02253063, 0.07381133, -0.0171294]
118
+ channel_stds = [0.9654121, 1.0440036, 0.76147926, 0.77022034]
119
+
120
+ if len(z.shape) != 4:
121
+ raise ValueError()
122
+
123
+ z = z * 0.18215
124
+ channels = [z[:, i] for i in range(z.shape[1])]
125
+
126
+ channels = [extra_scale_factor * (c - channel_means[i]) / channel_stds[i] for i, c in enumerate(channels)]
127
+ return torch.stack(channels, dim=1)
128
+
129
+ @torch.no_grad()
130
+ def __call__(
131
+ self,
132
+ features: torch.Tensor,
133
+ schedule=[1.0, 0.5],
134
+ generator=None,
135
+ ):
136
+ features = self.ldm_transform_latent(features)
137
+ ts = self.round_timesteps(
138
+ torch.arange(0, 1024),
139
+ 1024,
140
+ self.n_distilled_steps,
141
+ truncate_start=False,
142
+ )
143
+ shape = (
144
+ features.size(0),
145
+ 3,
146
+ 8 * features.size(2),
147
+ 8 * features.size(3),
148
+ )
149
+ x_start = torch.zeros(shape, device=features.device, dtype=features.dtype)
150
+ schedule_timesteps = [int((1024 - 1) * s) for s in schedule]
151
+ for i in schedule_timesteps:
152
+ t = ts[i].item()
153
+ t_ = torch.tensor([t] * features.shape[0]).to(self.device)
154
+ # noise = torch.randn_like(x_start)
155
+ noise = torch.randn(x_start.shape, dtype=x_start.dtype, generator=generator).to(device=x_start.device)
156
+ x_start = (
157
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t_, x_start.shape) * x_start
158
+ + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t_, x_start.shape) * noise
159
+ )
160
+ c_in = _extract_into_tensor(self.c_in, t_, x_start.shape)
161
+
162
+ import torch.nn.functional as F
163
+
164
+ from diffusers import UNet2DModel
165
+
166
+ if isinstance(self.ckpt, UNet2DModel):
167
+ input = torch.concat([c_in * x_start, F.upsample_nearest(features, scale_factor=8)], dim=1)
168
+ model_output = self.ckpt(input, t_).sample
169
+ else:
170
+ model_output = self.ckpt(c_in * x_start, t_, features=features)
171
+
172
+ B, C = x_start.shape[:2]
173
+ model_output, _ = torch.split(model_output, C, dim=1)
174
+ pred_xstart = (
175
+ _extract_into_tensor(self.c_out, t_, x_start.shape) * model_output
176
+ + _extract_into_tensor(self.c_skip, t_, x_start.shape) * x_start
177
+ ).clamp(-1, 1)
178
+ x_start = pred_xstart
179
+ return x_start
180
+
181
+
182
+ def save_image(image, name):
183
+ import numpy as np
184
+ from PIL import Image
185
+
186
+ image = image[0].cpu().numpy()
187
+ image = (image + 1.0) * 127.5
188
+ image = image.clip(0, 255).astype(np.uint8)
189
+ image = Image.fromarray(image.transpose(1, 2, 0))
190
+ image.save(name)
191
+
192
+
193
+ def load_image(uri, size=None, center_crop=False):
194
+ import numpy as np
195
+ from PIL import Image
196
+
197
+ image = Image.open(uri)
198
+ if center_crop:
199
+ image = image.crop(
200
+ (
201
+ (image.width - min(image.width, image.height)) // 2,
202
+ (image.height - min(image.width, image.height)) // 2,
203
+ (image.width + min(image.width, image.height)) // 2,
204
+ (image.height + min(image.width, image.height)) // 2,
205
+ )
206
+ )
207
+ if size is not None:
208
+ image = image.resize(size)
209
+ image = torch.tensor(np.array(image).transpose(2, 0, 1)).unsqueeze(0).float()
210
+ image = image / 127.5 - 1.0
211
+ return image
212
+
213
+
214
+ class TimestepEmbedding_(nn.Module):
215
+ def __init__(self, n_time=1024, n_emb=320, n_out=1280) -> None:
216
+ super().__init__()
217
+ self.emb = nn.Embedding(n_time, n_emb)
218
+ self.f_1 = nn.Linear(n_emb, n_out)
219
+ self.f_2 = nn.Linear(n_out, n_out)
220
+
221
+ def forward(self, x) -> torch.Tensor:
222
+ x = self.emb(x)
223
+ x = self.f_1(x)
224
+ x = F.silu(x)
225
+ return self.f_2(x)
226
+
227
+
228
+ class ImageEmbedding(nn.Module):
229
+ def __init__(self, in_channels=7, out_channels=320) -> None:
230
+ super().__init__()
231
+ self.f = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
232
+
233
+ def forward(self, x) -> torch.Tensor:
234
+ return self.f(x)
235
+
236
+
237
+ class ImageUnembedding(nn.Module):
238
+ def __init__(self, in_channels=320, out_channels=6) -> None:
239
+ super().__init__()
240
+ self.gn = nn.GroupNorm(32, in_channels)
241
+ self.f = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
242
+
243
+ def forward(self, x) -> torch.Tensor:
244
+ return self.f(F.silu(self.gn(x)))
245
+
246
+
247
+ class ConvResblock(nn.Module):
248
+ def __init__(self, in_features=320, out_features=320) -> None:
249
+ super().__init__()
250
+ self.f_t = nn.Linear(1280, out_features * 2)
251
+
252
+ self.gn_1 = nn.GroupNorm(32, in_features)
253
+ self.f_1 = nn.Conv2d(in_features, out_features, kernel_size=3, padding=1)
254
+
255
+ self.gn_2 = nn.GroupNorm(32, out_features)
256
+ self.f_2 = nn.Conv2d(out_features, out_features, kernel_size=3, padding=1)
257
+
258
+ skip_conv = in_features != out_features
259
+ self.f_s = nn.Conv2d(in_features, out_features, kernel_size=1, padding=0) if skip_conv else nn.Identity()
260
+
261
+ def forward(self, x, t):
262
+ x_skip = x
263
+ t = self.f_t(F.silu(t))
264
+ t = t.chunk(2, dim=1)
265
+ t_1 = t[0].unsqueeze(dim=2).unsqueeze(dim=3) + 1
266
+ t_2 = t[1].unsqueeze(dim=2).unsqueeze(dim=3)
267
+
268
+ gn_1 = F.silu(self.gn_1(x))
269
+ f_1 = self.f_1(gn_1)
270
+
271
+ gn_2 = self.gn_2(f_1)
272
+
273
+ return self.f_s(x_skip) + self.f_2(F.silu(gn_2 * t_1 + t_2))
274
+
275
+
276
+ # Also ConvResblock
277
+ class Downsample(nn.Module):
278
+ def __init__(self, in_channels=320) -> None:
279
+ super().__init__()
280
+ self.f_t = nn.Linear(1280, in_channels * 2)
281
+
282
+ self.gn_1 = nn.GroupNorm(32, in_channels)
283
+ self.f_1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
284
+ self.gn_2 = nn.GroupNorm(32, in_channels)
285
+
286
+ self.f_2 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
287
+
288
+ def forward(self, x, t) -> torch.Tensor:
289
+ x_skip = x
290
+
291
+ t = self.f_t(F.silu(t))
292
+ t_1, t_2 = t.chunk(2, dim=1)
293
+ t_1 = t_1.unsqueeze(2).unsqueeze(3) + 1
294
+ t_2 = t_2.unsqueeze(2).unsqueeze(3)
295
+
296
+ gn_1 = F.silu(self.gn_1(x))
297
+ avg_pool2d = F.avg_pool2d(gn_1, kernel_size=(2, 2), stride=None)
298
+
299
+ f_1 = self.f_1(avg_pool2d)
300
+ gn_2 = self.gn_2(f_1)
301
+
302
+ f_2 = self.f_2(F.silu(t_2 + (t_1 * gn_2)))
303
+
304
+ return f_2 + F.avg_pool2d(x_skip, kernel_size=(2, 2), stride=None)
305
+
306
+
307
+ # Also ConvResblock
308
+ class Upsample(nn.Module):
309
+ def __init__(self, in_channels=1024) -> None:
310
+ super().__init__()
311
+ self.f_t = nn.Linear(1280, in_channels * 2)
312
+
313
+ self.gn_1 = nn.GroupNorm(32, in_channels)
314
+ self.f_1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
315
+ self.gn_2 = nn.GroupNorm(32, in_channels)
316
+
317
+ self.f_2 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
318
+
319
+ def forward(self, x, t) -> torch.Tensor:
320
+ x_skip = x
321
+
322
+ t = self.f_t(F.silu(t))
323
+ t_1, t_2 = t.chunk(2, dim=1)
324
+ t_1 = t_1.unsqueeze(2).unsqueeze(3) + 1
325
+ t_2 = t_2.unsqueeze(2).unsqueeze(3)
326
+
327
+ gn_1 = F.silu(self.gn_1(x))
328
+ upsample = F.upsample_nearest(gn_1, scale_factor=2)
329
+ f_1 = self.f_1(upsample)
330
+ gn_2 = self.gn_2(f_1)
331
+
332
+ f_2 = self.f_2(F.silu(t_2 + (t_1 * gn_2)))
333
+
334
+ return f_2 + F.upsample_nearest(x_skip, scale_factor=2)
335
+
336
+
337
+ class ConvUNetVAE(nn.Module):
338
+ def __init__(self) -> None:
339
+ super().__init__()
340
+ self.embed_image = ImageEmbedding()
341
+ self.embed_time = TimestepEmbedding_()
342
+
343
+ down_0 = nn.ModuleList(
344
+ [
345
+ ConvResblock(320, 320),
346
+ ConvResblock(320, 320),
347
+ ConvResblock(320, 320),
348
+ Downsample(320),
349
+ ]
350
+ )
351
+ down_1 = nn.ModuleList(
352
+ [
353
+ ConvResblock(320, 640),
354
+ ConvResblock(640, 640),
355
+ ConvResblock(640, 640),
356
+ Downsample(640),
357
+ ]
358
+ )
359
+ down_2 = nn.ModuleList(
360
+ [
361
+ ConvResblock(640, 1024),
362
+ ConvResblock(1024, 1024),
363
+ ConvResblock(1024, 1024),
364
+ Downsample(1024),
365
+ ]
366
+ )
367
+ down_3 = nn.ModuleList(
368
+ [
369
+ ConvResblock(1024, 1024),
370
+ ConvResblock(1024, 1024),
371
+ ConvResblock(1024, 1024),
372
+ ]
373
+ )
374
+ self.down = nn.ModuleList(
375
+ [
376
+ down_0,
377
+ down_1,
378
+ down_2,
379
+ down_3,
380
+ ]
381
+ )
382
+
383
+ self.mid = nn.ModuleList(
384
+ [
385
+ ConvResblock(1024, 1024),
386
+ ConvResblock(1024, 1024),
387
+ ]
388
+ )
389
+
390
+ up_3 = nn.ModuleList(
391
+ [
392
+ ConvResblock(1024 * 2, 1024),
393
+ ConvResblock(1024 * 2, 1024),
394
+ ConvResblock(1024 * 2, 1024),
395
+ ConvResblock(1024 * 2, 1024),
396
+ Upsample(1024),
397
+ ]
398
+ )
399
+ up_2 = nn.ModuleList(
400
+ [
401
+ ConvResblock(1024 * 2, 1024),
402
+ ConvResblock(1024 * 2, 1024),
403
+ ConvResblock(1024 * 2, 1024),
404
+ ConvResblock(1024 + 640, 1024),
405
+ Upsample(1024),
406
+ ]
407
+ )
408
+ up_1 = nn.ModuleList(
409
+ [
410
+ ConvResblock(1024 + 640, 640),
411
+ ConvResblock(640 * 2, 640),
412
+ ConvResblock(640 * 2, 640),
413
+ ConvResblock(320 + 640, 640),
414
+ Upsample(640),
415
+ ]
416
+ )
417
+ up_0 = nn.ModuleList(
418
+ [
419
+ ConvResblock(320 + 640, 320),
420
+ ConvResblock(320 * 2, 320),
421
+ ConvResblock(320 * 2, 320),
422
+ ConvResblock(320 * 2, 320),
423
+ ]
424
+ )
425
+ self.up = nn.ModuleList(
426
+ [
427
+ up_0,
428
+ up_1,
429
+ up_2,
430
+ up_3,
431
+ ]
432
+ )
433
+
434
+ self.output = ImageUnembedding()
435
+
436
+ def forward(self, x, t, features) -> torch.Tensor:
437
+ converted = hasattr(self, "converted") and self.converted
438
+
439
+ x = torch.cat([x, F.upsample_nearest(features, scale_factor=8)], dim=1)
440
+
441
+ if converted:
442
+ t = self.time_embedding(self.time_proj(t))
443
+ else:
444
+ t = self.embed_time(t)
445
+
446
+ x = self.embed_image(x)
447
+
448
+ skips = [x]
449
+ for i, down in enumerate(self.down):
450
+ if converted and i in [0, 1, 2, 3]:
451
+ x, skips_ = down(x, t)
452
+ for skip in skips_:
453
+ skips.append(skip)
454
+ else:
455
+ for block in down:
456
+ x = block(x, t)
457
+ skips.append(x)
458
+ print(x.float().abs().sum())
459
+
460
+ if converted:
461
+ x = self.mid(x, t)
462
+ else:
463
+ for i in range(2):
464
+ x = self.mid[i](x, t)
465
+ print(x.float().abs().sum())
466
+
467
+ for i, up in enumerate(self.up[::-1]):
468
+ if converted and i in [0, 1, 2, 3]:
469
+ skip_4 = skips.pop()
470
+ skip_3 = skips.pop()
471
+ skip_2 = skips.pop()
472
+ skip_1 = skips.pop()
473
+ skips_ = (skip_1, skip_2, skip_3, skip_4)
474
+ x = up(x, skips_, t)
475
+ else:
476
+ for block in up:
477
+ if isinstance(block, ConvResblock):
478
+ x = torch.concat([x, skips.pop()], dim=1)
479
+ x = block(x, t)
480
+
481
+ return self.output(x)
482
+
483
+
484
+ def rename_state_dict_key(k):
485
+ k = k.replace("blocks.", "")
486
+ for i in range(5):
487
+ k = k.replace(f"down_{i}_", f"down.{i}.")
488
+ k = k.replace(f"conv_{i}.", f"{i}.")
489
+ k = k.replace(f"up_{i}_", f"up.{i}.")
490
+ k = k.replace(f"mid_{i}", f"mid.{i}")
491
+ k = k.replace("upsamp.", "4.")
492
+ k = k.replace("downsamp.", "3.")
493
+ k = k.replace("f_t.w", "f_t.weight").replace("f_t.b", "f_t.bias")
494
+ k = k.replace("f_1.w", "f_1.weight").replace("f_1.b", "f_1.bias")
495
+ k = k.replace("f_2.w", "f_2.weight").replace("f_2.b", "f_2.bias")
496
+ k = k.replace("f_s.w", "f_s.weight").replace("f_s.b", "f_s.bias")
497
+ k = k.replace("f.w", "f.weight").replace("f.b", "f.bias")
498
+ k = k.replace("gn_1.g", "gn_1.weight").replace("gn_1.b", "gn_1.bias")
499
+ k = k.replace("gn_2.g", "gn_2.weight").replace("gn_2.b", "gn_2.bias")
500
+ k = k.replace("gn.g", "gn.weight").replace("gn.b", "gn.bias")
501
+ return k
502
+
503
+
504
+ def rename_state_dict(sd, embedding):
505
+ sd = {rename_state_dict_key(k): v for k, v in sd.items()}
506
+ sd["embed_time.emb.weight"] = embedding["weight"]
507
+ return sd
508
+
509
+
510
+ # encode with stable diffusion vae
511
+ pipe = StableDiffusionPipeline.from_pretrained(
512
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
513
+ )
514
+ pipe.vae.cuda()
515
+
516
+ # construct original decoder with jitted model
517
+ decoder_consistency = ConsistencyDecoder(device="cuda:0")
518
+
519
+ # construct UNet code, overwrite the decoder with conv_unet_vae
520
+ model = ConvUNetVAE()
521
+ model.load_state_dict(
522
+ rename_state_dict(
523
+ stl("consistency_decoder.safetensors"),
524
+ stl("embedding.safetensors"),
525
+ )
526
+ )
527
+ model = model.cuda()
528
+
529
+ decoder_consistency.ckpt = model
530
+
531
+ image = load_image(args.test_image, size=(256, 256), center_crop=True)
532
+ latent = pipe.vae.encode(image.half().cuda()).latent_dist.sample()
533
+
534
+ # decode with gan
535
+ sample_gan = pipe.vae.decode(latent).sample.detach()
536
+ save_image(sample_gan, "gan.png")
537
+
538
+ # decode with conv_unet_vae
539
+ sample_consistency_orig = decoder_consistency(latent, generator=torch.Generator("cpu").manual_seed(0))
540
+ save_image(sample_consistency_orig, "con_orig.png")
541
+
542
+
543
+ ########### conversion
544
+
545
+ print("CONVERSION")
546
+
547
+ print("DOWN BLOCK ONE")
548
+
549
+ block_one_sd_orig = model.down[0].state_dict()
550
+ block_one_sd_new = {}
551
+
552
+ for i in range(3):
553
+ block_one_sd_new[f"resnets.{i}.norm1.weight"] = block_one_sd_orig.pop(f"{i}.gn_1.weight")
554
+ block_one_sd_new[f"resnets.{i}.norm1.bias"] = block_one_sd_orig.pop(f"{i}.gn_1.bias")
555
+ block_one_sd_new[f"resnets.{i}.conv1.weight"] = block_one_sd_orig.pop(f"{i}.f_1.weight")
556
+ block_one_sd_new[f"resnets.{i}.conv1.bias"] = block_one_sd_orig.pop(f"{i}.f_1.bias")
557
+ block_one_sd_new[f"resnets.{i}.time_emb_proj.weight"] = block_one_sd_orig.pop(f"{i}.f_t.weight")
558
+ block_one_sd_new[f"resnets.{i}.time_emb_proj.bias"] = block_one_sd_orig.pop(f"{i}.f_t.bias")
559
+ block_one_sd_new[f"resnets.{i}.norm2.weight"] = block_one_sd_orig.pop(f"{i}.gn_2.weight")
560
+ block_one_sd_new[f"resnets.{i}.norm2.bias"] = block_one_sd_orig.pop(f"{i}.gn_2.bias")
561
+ block_one_sd_new[f"resnets.{i}.conv2.weight"] = block_one_sd_orig.pop(f"{i}.f_2.weight")
562
+ block_one_sd_new[f"resnets.{i}.conv2.bias"] = block_one_sd_orig.pop(f"{i}.f_2.bias")
563
+
564
+ block_one_sd_new["downsamplers.0.norm1.weight"] = block_one_sd_orig.pop("3.gn_1.weight")
565
+ block_one_sd_new["downsamplers.0.norm1.bias"] = block_one_sd_orig.pop("3.gn_1.bias")
566
+ block_one_sd_new["downsamplers.0.conv1.weight"] = block_one_sd_orig.pop("3.f_1.weight")
567
+ block_one_sd_new["downsamplers.0.conv1.bias"] = block_one_sd_orig.pop("3.f_1.bias")
568
+ block_one_sd_new["downsamplers.0.time_emb_proj.weight"] = block_one_sd_orig.pop("3.f_t.weight")
569
+ block_one_sd_new["downsamplers.0.time_emb_proj.bias"] = block_one_sd_orig.pop("3.f_t.bias")
570
+ block_one_sd_new["downsamplers.0.norm2.weight"] = block_one_sd_orig.pop("3.gn_2.weight")
571
+ block_one_sd_new["downsamplers.0.norm2.bias"] = block_one_sd_orig.pop("3.gn_2.bias")
572
+ block_one_sd_new["downsamplers.0.conv2.weight"] = block_one_sd_orig.pop("3.f_2.weight")
573
+ block_one_sd_new["downsamplers.0.conv2.bias"] = block_one_sd_orig.pop("3.f_2.bias")
574
+
575
+ assert len(block_one_sd_orig) == 0
576
+
577
+ block_one = ResnetDownsampleBlock2D(
578
+ in_channels=320,
579
+ out_channels=320,
580
+ temb_channels=1280,
581
+ num_layers=3,
582
+ add_downsample=True,
583
+ resnet_time_scale_shift="scale_shift",
584
+ resnet_eps=1e-5,
585
+ )
586
+
587
+ block_one.load_state_dict(block_one_sd_new)
588
+
589
+ print("DOWN BLOCK TWO")
590
+
591
+ block_two_sd_orig = model.down[1].state_dict()
592
+ block_two_sd_new = {}
593
+
594
+ for i in range(3):
595
+ block_two_sd_new[f"resnets.{i}.norm1.weight"] = block_two_sd_orig.pop(f"{i}.gn_1.weight")
596
+ block_two_sd_new[f"resnets.{i}.norm1.bias"] = block_two_sd_orig.pop(f"{i}.gn_1.bias")
597
+ block_two_sd_new[f"resnets.{i}.conv1.weight"] = block_two_sd_orig.pop(f"{i}.f_1.weight")
598
+ block_two_sd_new[f"resnets.{i}.conv1.bias"] = block_two_sd_orig.pop(f"{i}.f_1.bias")
599
+ block_two_sd_new[f"resnets.{i}.time_emb_proj.weight"] = block_two_sd_orig.pop(f"{i}.f_t.weight")
600
+ block_two_sd_new[f"resnets.{i}.time_emb_proj.bias"] = block_two_sd_orig.pop(f"{i}.f_t.bias")
601
+ block_two_sd_new[f"resnets.{i}.norm2.weight"] = block_two_sd_orig.pop(f"{i}.gn_2.weight")
602
+ block_two_sd_new[f"resnets.{i}.norm2.bias"] = block_two_sd_orig.pop(f"{i}.gn_2.bias")
603
+ block_two_sd_new[f"resnets.{i}.conv2.weight"] = block_two_sd_orig.pop(f"{i}.f_2.weight")
604
+ block_two_sd_new[f"resnets.{i}.conv2.bias"] = block_two_sd_orig.pop(f"{i}.f_2.bias")
605
+
606
+ if i == 0:
607
+ block_two_sd_new[f"resnets.{i}.conv_shortcut.weight"] = block_two_sd_orig.pop(f"{i}.f_s.weight")
608
+ block_two_sd_new[f"resnets.{i}.conv_shortcut.bias"] = block_two_sd_orig.pop(f"{i}.f_s.bias")
609
+
610
+ block_two_sd_new["downsamplers.0.norm1.weight"] = block_two_sd_orig.pop("3.gn_1.weight")
611
+ block_two_sd_new["downsamplers.0.norm1.bias"] = block_two_sd_orig.pop("3.gn_1.bias")
612
+ block_two_sd_new["downsamplers.0.conv1.weight"] = block_two_sd_orig.pop("3.f_1.weight")
613
+ block_two_sd_new["downsamplers.0.conv1.bias"] = block_two_sd_orig.pop("3.f_1.bias")
614
+ block_two_sd_new["downsamplers.0.time_emb_proj.weight"] = block_two_sd_orig.pop("3.f_t.weight")
615
+ block_two_sd_new["downsamplers.0.time_emb_proj.bias"] = block_two_sd_orig.pop("3.f_t.bias")
616
+ block_two_sd_new["downsamplers.0.norm2.weight"] = block_two_sd_orig.pop("3.gn_2.weight")
617
+ block_two_sd_new["downsamplers.0.norm2.bias"] = block_two_sd_orig.pop("3.gn_2.bias")
618
+ block_two_sd_new["downsamplers.0.conv2.weight"] = block_two_sd_orig.pop("3.f_2.weight")
619
+ block_two_sd_new["downsamplers.0.conv2.bias"] = block_two_sd_orig.pop("3.f_2.bias")
620
+
621
+ assert len(block_two_sd_orig) == 0
622
+
623
+ block_two = ResnetDownsampleBlock2D(
624
+ in_channels=320,
625
+ out_channels=640,
626
+ temb_channels=1280,
627
+ num_layers=3,
628
+ add_downsample=True,
629
+ resnet_time_scale_shift="scale_shift",
630
+ resnet_eps=1e-5,
631
+ )
632
+
633
+ block_two.load_state_dict(block_two_sd_new)
634
+
635
+ print("DOWN BLOCK THREE")
636
+
637
+ block_three_sd_orig = model.down[2].state_dict()
638
+ block_three_sd_new = {}
639
+
640
+ for i in range(3):
641
+ block_three_sd_new[f"resnets.{i}.norm1.weight"] = block_three_sd_orig.pop(f"{i}.gn_1.weight")
642
+ block_three_sd_new[f"resnets.{i}.norm1.bias"] = block_three_sd_orig.pop(f"{i}.gn_1.bias")
643
+ block_three_sd_new[f"resnets.{i}.conv1.weight"] = block_three_sd_orig.pop(f"{i}.f_1.weight")
644
+ block_three_sd_new[f"resnets.{i}.conv1.bias"] = block_three_sd_orig.pop(f"{i}.f_1.bias")
645
+ block_three_sd_new[f"resnets.{i}.time_emb_proj.weight"] = block_three_sd_orig.pop(f"{i}.f_t.weight")
646
+ block_three_sd_new[f"resnets.{i}.time_emb_proj.bias"] = block_three_sd_orig.pop(f"{i}.f_t.bias")
647
+ block_three_sd_new[f"resnets.{i}.norm2.weight"] = block_three_sd_orig.pop(f"{i}.gn_2.weight")
648
+ block_three_sd_new[f"resnets.{i}.norm2.bias"] = block_three_sd_orig.pop(f"{i}.gn_2.bias")
649
+ block_three_sd_new[f"resnets.{i}.conv2.weight"] = block_three_sd_orig.pop(f"{i}.f_2.weight")
650
+ block_three_sd_new[f"resnets.{i}.conv2.bias"] = block_three_sd_orig.pop(f"{i}.f_2.bias")
651
+
652
+ if i == 0:
653
+ block_three_sd_new[f"resnets.{i}.conv_shortcut.weight"] = block_three_sd_orig.pop(f"{i}.f_s.weight")
654
+ block_three_sd_new[f"resnets.{i}.conv_shortcut.bias"] = block_three_sd_orig.pop(f"{i}.f_s.bias")
655
+
656
+ block_three_sd_new["downsamplers.0.norm1.weight"] = block_three_sd_orig.pop("3.gn_1.weight")
657
+ block_three_sd_new["downsamplers.0.norm1.bias"] = block_three_sd_orig.pop("3.gn_1.bias")
658
+ block_three_sd_new["downsamplers.0.conv1.weight"] = block_three_sd_orig.pop("3.f_1.weight")
659
+ block_three_sd_new["downsamplers.0.conv1.bias"] = block_three_sd_orig.pop("3.f_1.bias")
660
+ block_three_sd_new["downsamplers.0.time_emb_proj.weight"] = block_three_sd_orig.pop("3.f_t.weight")
661
+ block_three_sd_new["downsamplers.0.time_emb_proj.bias"] = block_three_sd_orig.pop("3.f_t.bias")
662
+ block_three_sd_new["downsamplers.0.norm2.weight"] = block_three_sd_orig.pop("3.gn_2.weight")
663
+ block_three_sd_new["downsamplers.0.norm2.bias"] = block_three_sd_orig.pop("3.gn_2.bias")
664
+ block_three_sd_new["downsamplers.0.conv2.weight"] = block_three_sd_orig.pop("3.f_2.weight")
665
+ block_three_sd_new["downsamplers.0.conv2.bias"] = block_three_sd_orig.pop("3.f_2.bias")
666
+
667
+ assert len(block_three_sd_orig) == 0
668
+
669
+ block_three = ResnetDownsampleBlock2D(
670
+ in_channels=640,
671
+ out_channels=1024,
672
+ temb_channels=1280,
673
+ num_layers=3,
674
+ add_downsample=True,
675
+ resnet_time_scale_shift="scale_shift",
676
+ resnet_eps=1e-5,
677
+ )
678
+
679
+ block_three.load_state_dict(block_three_sd_new)
680
+
681
+ print("DOWN BLOCK FOUR")
682
+
683
+ block_four_sd_orig = model.down[3].state_dict()
684
+ block_four_sd_new = {}
685
+
686
+ for i in range(3):
687
+ block_four_sd_new[f"resnets.{i}.norm1.weight"] = block_four_sd_orig.pop(f"{i}.gn_1.weight")
688
+ block_four_sd_new[f"resnets.{i}.norm1.bias"] = block_four_sd_orig.pop(f"{i}.gn_1.bias")
689
+ block_four_sd_new[f"resnets.{i}.conv1.weight"] = block_four_sd_orig.pop(f"{i}.f_1.weight")
690
+ block_four_sd_new[f"resnets.{i}.conv1.bias"] = block_four_sd_orig.pop(f"{i}.f_1.bias")
691
+ block_four_sd_new[f"resnets.{i}.time_emb_proj.weight"] = block_four_sd_orig.pop(f"{i}.f_t.weight")
692
+ block_four_sd_new[f"resnets.{i}.time_emb_proj.bias"] = block_four_sd_orig.pop(f"{i}.f_t.bias")
693
+ block_four_sd_new[f"resnets.{i}.norm2.weight"] = block_four_sd_orig.pop(f"{i}.gn_2.weight")
694
+ block_four_sd_new[f"resnets.{i}.norm2.bias"] = block_four_sd_orig.pop(f"{i}.gn_2.bias")
695
+ block_four_sd_new[f"resnets.{i}.conv2.weight"] = block_four_sd_orig.pop(f"{i}.f_2.weight")
696
+ block_four_sd_new[f"resnets.{i}.conv2.bias"] = block_four_sd_orig.pop(f"{i}.f_2.bias")
697
+
698
+ assert len(block_four_sd_orig) == 0
699
+
700
+ block_four = ResnetDownsampleBlock2D(
701
+ in_channels=1024,
702
+ out_channels=1024,
703
+ temb_channels=1280,
704
+ num_layers=3,
705
+ add_downsample=False,
706
+ resnet_time_scale_shift="scale_shift",
707
+ resnet_eps=1e-5,
708
+ )
709
+
710
+ block_four.load_state_dict(block_four_sd_new)
711
+
712
+
713
+ print("MID BLOCK 1")
714
+
715
+ mid_block_one_sd_orig = model.mid.state_dict()
716
+ mid_block_one_sd_new = {}
717
+
718
+ for i in range(2):
719
+ mid_block_one_sd_new[f"resnets.{i}.norm1.weight"] = mid_block_one_sd_orig.pop(f"{i}.gn_1.weight")
720
+ mid_block_one_sd_new[f"resnets.{i}.norm1.bias"] = mid_block_one_sd_orig.pop(f"{i}.gn_1.bias")
721
+ mid_block_one_sd_new[f"resnets.{i}.conv1.weight"] = mid_block_one_sd_orig.pop(f"{i}.f_1.weight")
722
+ mid_block_one_sd_new[f"resnets.{i}.conv1.bias"] = mid_block_one_sd_orig.pop(f"{i}.f_1.bias")
723
+ mid_block_one_sd_new[f"resnets.{i}.time_emb_proj.weight"] = mid_block_one_sd_orig.pop(f"{i}.f_t.weight")
724
+ mid_block_one_sd_new[f"resnets.{i}.time_emb_proj.bias"] = mid_block_one_sd_orig.pop(f"{i}.f_t.bias")
725
+ mid_block_one_sd_new[f"resnets.{i}.norm2.weight"] = mid_block_one_sd_orig.pop(f"{i}.gn_2.weight")
726
+ mid_block_one_sd_new[f"resnets.{i}.norm2.bias"] = mid_block_one_sd_orig.pop(f"{i}.gn_2.bias")
727
+ mid_block_one_sd_new[f"resnets.{i}.conv2.weight"] = mid_block_one_sd_orig.pop(f"{i}.f_2.weight")
728
+ mid_block_one_sd_new[f"resnets.{i}.conv2.bias"] = mid_block_one_sd_orig.pop(f"{i}.f_2.bias")
729
+
730
+ assert len(mid_block_one_sd_orig) == 0
731
+
732
+ mid_block_one = UNetMidBlock2D(
733
+ in_channels=1024,
734
+ temb_channels=1280,
735
+ num_layers=1,
736
+ resnet_time_scale_shift="scale_shift",
737
+ resnet_eps=1e-5,
738
+ add_attention=False,
739
+ )
740
+
741
+ mid_block_one.load_state_dict(mid_block_one_sd_new)
742
+
743
+ print("UP BLOCK ONE")
744
+
745
+ up_block_one_sd_orig = model.up[-1].state_dict()
746
+ up_block_one_sd_new = {}
747
+
748
+ for i in range(4):
749
+ up_block_one_sd_new[f"resnets.{i}.norm1.weight"] = up_block_one_sd_orig.pop(f"{i}.gn_1.weight")
750
+ up_block_one_sd_new[f"resnets.{i}.norm1.bias"] = up_block_one_sd_orig.pop(f"{i}.gn_1.bias")
751
+ up_block_one_sd_new[f"resnets.{i}.conv1.weight"] = up_block_one_sd_orig.pop(f"{i}.f_1.weight")
752
+ up_block_one_sd_new[f"resnets.{i}.conv1.bias"] = up_block_one_sd_orig.pop(f"{i}.f_1.bias")
753
+ up_block_one_sd_new[f"resnets.{i}.time_emb_proj.weight"] = up_block_one_sd_orig.pop(f"{i}.f_t.weight")
754
+ up_block_one_sd_new[f"resnets.{i}.time_emb_proj.bias"] = up_block_one_sd_orig.pop(f"{i}.f_t.bias")
755
+ up_block_one_sd_new[f"resnets.{i}.norm2.weight"] = up_block_one_sd_orig.pop(f"{i}.gn_2.weight")
756
+ up_block_one_sd_new[f"resnets.{i}.norm2.bias"] = up_block_one_sd_orig.pop(f"{i}.gn_2.bias")
757
+ up_block_one_sd_new[f"resnets.{i}.conv2.weight"] = up_block_one_sd_orig.pop(f"{i}.f_2.weight")
758
+ up_block_one_sd_new[f"resnets.{i}.conv2.bias"] = up_block_one_sd_orig.pop(f"{i}.f_2.bias")
759
+ up_block_one_sd_new[f"resnets.{i}.conv_shortcut.weight"] = up_block_one_sd_orig.pop(f"{i}.f_s.weight")
760
+ up_block_one_sd_new[f"resnets.{i}.conv_shortcut.bias"] = up_block_one_sd_orig.pop(f"{i}.f_s.bias")
761
+
762
+ up_block_one_sd_new["upsamplers.0.norm1.weight"] = up_block_one_sd_orig.pop("4.gn_1.weight")
763
+ up_block_one_sd_new["upsamplers.0.norm1.bias"] = up_block_one_sd_orig.pop("4.gn_1.bias")
764
+ up_block_one_sd_new["upsamplers.0.conv1.weight"] = up_block_one_sd_orig.pop("4.f_1.weight")
765
+ up_block_one_sd_new["upsamplers.0.conv1.bias"] = up_block_one_sd_orig.pop("4.f_1.bias")
766
+ up_block_one_sd_new["upsamplers.0.time_emb_proj.weight"] = up_block_one_sd_orig.pop("4.f_t.weight")
767
+ up_block_one_sd_new["upsamplers.0.time_emb_proj.bias"] = up_block_one_sd_orig.pop("4.f_t.bias")
768
+ up_block_one_sd_new["upsamplers.0.norm2.weight"] = up_block_one_sd_orig.pop("4.gn_2.weight")
769
+ up_block_one_sd_new["upsamplers.0.norm2.bias"] = up_block_one_sd_orig.pop("4.gn_2.bias")
770
+ up_block_one_sd_new["upsamplers.0.conv2.weight"] = up_block_one_sd_orig.pop("4.f_2.weight")
771
+ up_block_one_sd_new["upsamplers.0.conv2.bias"] = up_block_one_sd_orig.pop("4.f_2.bias")
772
+
773
+ assert len(up_block_one_sd_orig) == 0
774
+
775
+ up_block_one = ResnetUpsampleBlock2D(
776
+ in_channels=1024,
777
+ prev_output_channel=1024,
778
+ out_channels=1024,
779
+ temb_channels=1280,
780
+ num_layers=4,
781
+ add_upsample=True,
782
+ resnet_time_scale_shift="scale_shift",
783
+ resnet_eps=1e-5,
784
+ )
785
+
786
+ up_block_one.load_state_dict(up_block_one_sd_new)
787
+
788
+ print("UP BLOCK TWO")
789
+
790
+ up_block_two_sd_orig = model.up[-2].state_dict()
791
+ up_block_two_sd_new = {}
792
+
793
+ for i in range(4):
794
+ up_block_two_sd_new[f"resnets.{i}.norm1.weight"] = up_block_two_sd_orig.pop(f"{i}.gn_1.weight")
795
+ up_block_two_sd_new[f"resnets.{i}.norm1.bias"] = up_block_two_sd_orig.pop(f"{i}.gn_1.bias")
796
+ up_block_two_sd_new[f"resnets.{i}.conv1.weight"] = up_block_two_sd_orig.pop(f"{i}.f_1.weight")
797
+ up_block_two_sd_new[f"resnets.{i}.conv1.bias"] = up_block_two_sd_orig.pop(f"{i}.f_1.bias")
798
+ up_block_two_sd_new[f"resnets.{i}.time_emb_proj.weight"] = up_block_two_sd_orig.pop(f"{i}.f_t.weight")
799
+ up_block_two_sd_new[f"resnets.{i}.time_emb_proj.bias"] = up_block_two_sd_orig.pop(f"{i}.f_t.bias")
800
+ up_block_two_sd_new[f"resnets.{i}.norm2.weight"] = up_block_two_sd_orig.pop(f"{i}.gn_2.weight")
801
+ up_block_two_sd_new[f"resnets.{i}.norm2.bias"] = up_block_two_sd_orig.pop(f"{i}.gn_2.bias")
802
+ up_block_two_sd_new[f"resnets.{i}.conv2.weight"] = up_block_two_sd_orig.pop(f"{i}.f_2.weight")
803
+ up_block_two_sd_new[f"resnets.{i}.conv2.bias"] = up_block_two_sd_orig.pop(f"{i}.f_2.bias")
804
+ up_block_two_sd_new[f"resnets.{i}.conv_shortcut.weight"] = up_block_two_sd_orig.pop(f"{i}.f_s.weight")
805
+ up_block_two_sd_new[f"resnets.{i}.conv_shortcut.bias"] = up_block_two_sd_orig.pop(f"{i}.f_s.bias")
806
+
807
+ up_block_two_sd_new["upsamplers.0.norm1.weight"] = up_block_two_sd_orig.pop("4.gn_1.weight")
808
+ up_block_two_sd_new["upsamplers.0.norm1.bias"] = up_block_two_sd_orig.pop("4.gn_1.bias")
809
+ up_block_two_sd_new["upsamplers.0.conv1.weight"] = up_block_two_sd_orig.pop("4.f_1.weight")
810
+ up_block_two_sd_new["upsamplers.0.conv1.bias"] = up_block_two_sd_orig.pop("4.f_1.bias")
811
+ up_block_two_sd_new["upsamplers.0.time_emb_proj.weight"] = up_block_two_sd_orig.pop("4.f_t.weight")
812
+ up_block_two_sd_new["upsamplers.0.time_emb_proj.bias"] = up_block_two_sd_orig.pop("4.f_t.bias")
813
+ up_block_two_sd_new["upsamplers.0.norm2.weight"] = up_block_two_sd_orig.pop("4.gn_2.weight")
814
+ up_block_two_sd_new["upsamplers.0.norm2.bias"] = up_block_two_sd_orig.pop("4.gn_2.bias")
815
+ up_block_two_sd_new["upsamplers.0.conv2.weight"] = up_block_two_sd_orig.pop("4.f_2.weight")
816
+ up_block_two_sd_new["upsamplers.0.conv2.bias"] = up_block_two_sd_orig.pop("4.f_2.bias")
817
+
818
+ assert len(up_block_two_sd_orig) == 0
819
+
820
+ up_block_two = ResnetUpsampleBlock2D(
821
+ in_channels=640,
822
+ prev_output_channel=1024,
823
+ out_channels=1024,
824
+ temb_channels=1280,
825
+ num_layers=4,
826
+ add_upsample=True,
827
+ resnet_time_scale_shift="scale_shift",
828
+ resnet_eps=1e-5,
829
+ )
830
+
831
+ up_block_two.load_state_dict(up_block_two_sd_new)
832
+
833
+ print("UP BLOCK THREE")
834
+
835
+ up_block_three_sd_orig = model.up[-3].state_dict()
836
+ up_block_three_sd_new = {}
837
+
838
+ for i in range(4):
839
+ up_block_three_sd_new[f"resnets.{i}.norm1.weight"] = up_block_three_sd_orig.pop(f"{i}.gn_1.weight")
840
+ up_block_three_sd_new[f"resnets.{i}.norm1.bias"] = up_block_three_sd_orig.pop(f"{i}.gn_1.bias")
841
+ up_block_three_sd_new[f"resnets.{i}.conv1.weight"] = up_block_three_sd_orig.pop(f"{i}.f_1.weight")
842
+ up_block_three_sd_new[f"resnets.{i}.conv1.bias"] = up_block_three_sd_orig.pop(f"{i}.f_1.bias")
843
+ up_block_three_sd_new[f"resnets.{i}.time_emb_proj.weight"] = up_block_three_sd_orig.pop(f"{i}.f_t.weight")
844
+ up_block_three_sd_new[f"resnets.{i}.time_emb_proj.bias"] = up_block_three_sd_orig.pop(f"{i}.f_t.bias")
845
+ up_block_three_sd_new[f"resnets.{i}.norm2.weight"] = up_block_three_sd_orig.pop(f"{i}.gn_2.weight")
846
+ up_block_three_sd_new[f"resnets.{i}.norm2.bias"] = up_block_three_sd_orig.pop(f"{i}.gn_2.bias")
847
+ up_block_three_sd_new[f"resnets.{i}.conv2.weight"] = up_block_three_sd_orig.pop(f"{i}.f_2.weight")
848
+ up_block_three_sd_new[f"resnets.{i}.conv2.bias"] = up_block_three_sd_orig.pop(f"{i}.f_2.bias")
849
+ up_block_three_sd_new[f"resnets.{i}.conv_shortcut.weight"] = up_block_three_sd_orig.pop(f"{i}.f_s.weight")
850
+ up_block_three_sd_new[f"resnets.{i}.conv_shortcut.bias"] = up_block_three_sd_orig.pop(f"{i}.f_s.bias")
851
+
852
+ up_block_three_sd_new["upsamplers.0.norm1.weight"] = up_block_three_sd_orig.pop("4.gn_1.weight")
853
+ up_block_three_sd_new["upsamplers.0.norm1.bias"] = up_block_three_sd_orig.pop("4.gn_1.bias")
854
+ up_block_three_sd_new["upsamplers.0.conv1.weight"] = up_block_three_sd_orig.pop("4.f_1.weight")
855
+ up_block_three_sd_new["upsamplers.0.conv1.bias"] = up_block_three_sd_orig.pop("4.f_1.bias")
856
+ up_block_three_sd_new["upsamplers.0.time_emb_proj.weight"] = up_block_three_sd_orig.pop("4.f_t.weight")
857
+ up_block_three_sd_new["upsamplers.0.time_emb_proj.bias"] = up_block_three_sd_orig.pop("4.f_t.bias")
858
+ up_block_three_sd_new["upsamplers.0.norm2.weight"] = up_block_three_sd_orig.pop("4.gn_2.weight")
859
+ up_block_three_sd_new["upsamplers.0.norm2.bias"] = up_block_three_sd_orig.pop("4.gn_2.bias")
860
+ up_block_three_sd_new["upsamplers.0.conv2.weight"] = up_block_three_sd_orig.pop("4.f_2.weight")
861
+ up_block_three_sd_new["upsamplers.0.conv2.bias"] = up_block_three_sd_orig.pop("4.f_2.bias")
862
+
863
+ assert len(up_block_three_sd_orig) == 0
864
+
865
+ up_block_three = ResnetUpsampleBlock2D(
866
+ in_channels=320,
867
+ prev_output_channel=1024,
868
+ out_channels=640,
869
+ temb_channels=1280,
870
+ num_layers=4,
871
+ add_upsample=True,
872
+ resnet_time_scale_shift="scale_shift",
873
+ resnet_eps=1e-5,
874
+ )
875
+
876
+ up_block_three.load_state_dict(up_block_three_sd_new)
877
+
878
+ print("UP BLOCK FOUR")
879
+
880
+ up_block_four_sd_orig = model.up[-4].state_dict()
881
+ up_block_four_sd_new = {}
882
+
883
+ for i in range(4):
884
+ up_block_four_sd_new[f"resnets.{i}.norm1.weight"] = up_block_four_sd_orig.pop(f"{i}.gn_1.weight")
885
+ up_block_four_sd_new[f"resnets.{i}.norm1.bias"] = up_block_four_sd_orig.pop(f"{i}.gn_1.bias")
886
+ up_block_four_sd_new[f"resnets.{i}.conv1.weight"] = up_block_four_sd_orig.pop(f"{i}.f_1.weight")
887
+ up_block_four_sd_new[f"resnets.{i}.conv1.bias"] = up_block_four_sd_orig.pop(f"{i}.f_1.bias")
888
+ up_block_four_sd_new[f"resnets.{i}.time_emb_proj.weight"] = up_block_four_sd_orig.pop(f"{i}.f_t.weight")
889
+ up_block_four_sd_new[f"resnets.{i}.time_emb_proj.bias"] = up_block_four_sd_orig.pop(f"{i}.f_t.bias")
890
+ up_block_four_sd_new[f"resnets.{i}.norm2.weight"] = up_block_four_sd_orig.pop(f"{i}.gn_2.weight")
891
+ up_block_four_sd_new[f"resnets.{i}.norm2.bias"] = up_block_four_sd_orig.pop(f"{i}.gn_2.bias")
892
+ up_block_four_sd_new[f"resnets.{i}.conv2.weight"] = up_block_four_sd_orig.pop(f"{i}.f_2.weight")
893
+ up_block_four_sd_new[f"resnets.{i}.conv2.bias"] = up_block_four_sd_orig.pop(f"{i}.f_2.bias")
894
+ up_block_four_sd_new[f"resnets.{i}.conv_shortcut.weight"] = up_block_four_sd_orig.pop(f"{i}.f_s.weight")
895
+ up_block_four_sd_new[f"resnets.{i}.conv_shortcut.bias"] = up_block_four_sd_orig.pop(f"{i}.f_s.bias")
896
+
897
+ assert len(up_block_four_sd_orig) == 0
898
+
899
+ up_block_four = ResnetUpsampleBlock2D(
900
+ in_channels=320,
901
+ prev_output_channel=640,
902
+ out_channels=320,
903
+ temb_channels=1280,
904
+ num_layers=4,
905
+ add_upsample=False,
906
+ resnet_time_scale_shift="scale_shift",
907
+ resnet_eps=1e-5,
908
+ )
909
+
910
+ up_block_four.load_state_dict(up_block_four_sd_new)
911
+
912
+ print("initial projection (conv_in)")
913
+
914
+ conv_in_sd_orig = model.embed_image.state_dict()
915
+ conv_in_sd_new = {}
916
+
917
+ conv_in_sd_new["weight"] = conv_in_sd_orig.pop("f.weight")
918
+ conv_in_sd_new["bias"] = conv_in_sd_orig.pop("f.bias")
919
+
920
+ assert len(conv_in_sd_orig) == 0
921
+
922
+ block_out_channels = [320, 640, 1024, 1024]
923
+
924
+ in_channels = 7
925
+ conv_in_kernel = 3
926
+ conv_in_padding = (conv_in_kernel - 1) // 2
927
+ conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding)
928
+
929
+ conv_in.load_state_dict(conv_in_sd_new)
930
+
931
+ print("out projection (conv_out) (conv_norm_out)")
932
+ out_channels = 6
933
+ norm_num_groups = 32
934
+ norm_eps = 1e-5
935
+ act_fn = "silu"
936
+ conv_out_kernel = 3
937
+ conv_out_padding = (conv_out_kernel - 1) // 2
938
+ conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
939
+ # uses torch.functional in orig
940
+ # conv_act = get_activation(act_fn)
941
+ conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding)
942
+
943
+ conv_norm_out.load_state_dict(model.output.gn.state_dict())
944
+ conv_out.load_state_dict(model.output.f.state_dict())
945
+
946
+ print("timestep projection (time_proj) (time_embedding)")
947
+
948
+ f1_sd = model.embed_time.f_1.state_dict()
949
+ f2_sd = model.embed_time.f_2.state_dict()
950
+
951
+ time_embedding_sd = {
952
+ "linear_1.weight": f1_sd.pop("weight"),
953
+ "linear_1.bias": f1_sd.pop("bias"),
954
+ "linear_2.weight": f2_sd.pop("weight"),
955
+ "linear_2.bias": f2_sd.pop("bias"),
956
+ }
957
+
958
+ assert len(f1_sd) == 0
959
+ assert len(f2_sd) == 0
960
+
961
+ time_embedding_type = "learned"
962
+ num_train_timesteps = 1024
963
+ time_embedding_dim = 1280
964
+
965
+ time_proj = nn.Embedding(num_train_timesteps, block_out_channels[0])
966
+ timestep_input_dim = block_out_channels[0]
967
+
968
+ time_embedding = TimestepEmbedding(timestep_input_dim, time_embedding_dim)
969
+
970
+ time_proj.load_state_dict(model.embed_time.emb.state_dict())
971
+ time_embedding.load_state_dict(time_embedding_sd)
972
+
973
+ print("CONVERT")
974
+
975
+ time_embedding.to("cuda")
976
+ time_proj.to("cuda")
977
+ conv_in.to("cuda")
978
+
979
+ block_one.to("cuda")
980
+ block_two.to("cuda")
981
+ block_three.to("cuda")
982
+ block_four.to("cuda")
983
+
984
+ mid_block_one.to("cuda")
985
+
986
+ up_block_one.to("cuda")
987
+ up_block_two.to("cuda")
988
+ up_block_three.to("cuda")
989
+ up_block_four.to("cuda")
990
+
991
+ conv_norm_out.to("cuda")
992
+ conv_out.to("cuda")
993
+
994
+ model.time_proj = time_proj
995
+ model.time_embedding = time_embedding
996
+ model.embed_image = conv_in
997
+
998
+ model.down[0] = block_one
999
+ model.down[1] = block_two
1000
+ model.down[2] = block_three
1001
+ model.down[3] = block_four
1002
+
1003
+ model.mid = mid_block_one
1004
+
1005
+ model.up[-1] = up_block_one
1006
+ model.up[-2] = up_block_two
1007
+ model.up[-3] = up_block_three
1008
+ model.up[-4] = up_block_four
1009
+
1010
+ model.output.gn = conv_norm_out
1011
+ model.output.f = conv_out
1012
+
1013
+ model.converted = True
1014
+
1015
+ sample_consistency_new = decoder_consistency(latent, generator=torch.Generator("cpu").manual_seed(0))
1016
+ save_image(sample_consistency_new, "con_new.png")
1017
+
1018
+ assert (sample_consistency_orig == sample_consistency_new).all()
1019
+
1020
+ print("making unet")
1021
+
1022
+ unet = UNet2DModel(
1023
+ in_channels=in_channels,
1024
+ out_channels=out_channels,
1025
+ down_block_types=(
1026
+ "ResnetDownsampleBlock2D",
1027
+ "ResnetDownsampleBlock2D",
1028
+ "ResnetDownsampleBlock2D",
1029
+ "ResnetDownsampleBlock2D",
1030
+ ),
1031
+ up_block_types=(
1032
+ "ResnetUpsampleBlock2D",
1033
+ "ResnetUpsampleBlock2D",
1034
+ "ResnetUpsampleBlock2D",
1035
+ "ResnetUpsampleBlock2D",
1036
+ ),
1037
+ block_out_channels=block_out_channels,
1038
+ layers_per_block=3,
1039
+ norm_num_groups=norm_num_groups,
1040
+ norm_eps=norm_eps,
1041
+ resnet_time_scale_shift="scale_shift",
1042
+ time_embedding_type="learned",
1043
+ num_train_timesteps=num_train_timesteps,
1044
+ add_attention=False,
1045
+ )
1046
+
1047
+ unet_state_dict = {}
1048
+
1049
+
1050
+ def add_state_dict(prefix, mod):
1051
+ for k, v in mod.state_dict().items():
1052
+ unet_state_dict[f"{prefix}.{k}"] = v
1053
+
1054
+
1055
+ add_state_dict("conv_in", conv_in)
1056
+ add_state_dict("time_proj", time_proj)
1057
+ add_state_dict("time_embedding", time_embedding)
1058
+ add_state_dict("down_blocks.0", block_one)
1059
+ add_state_dict("down_blocks.1", block_two)
1060
+ add_state_dict("down_blocks.2", block_three)
1061
+ add_state_dict("down_blocks.3", block_four)
1062
+ add_state_dict("mid_block", mid_block_one)
1063
+ add_state_dict("up_blocks.0", up_block_one)
1064
+ add_state_dict("up_blocks.1", up_block_two)
1065
+ add_state_dict("up_blocks.2", up_block_three)
1066
+ add_state_dict("up_blocks.3", up_block_four)
1067
+ add_state_dict("conv_norm_out", conv_norm_out)
1068
+ add_state_dict("conv_out", conv_out)
1069
+
1070
+ unet.load_state_dict(unet_state_dict)
1071
+
1072
+ print("running with diffusers unet")
1073
+
1074
+ unet.to("cuda")
1075
+
1076
+ decoder_consistency.ckpt = unet
1077
+
1078
+ sample_consistency_new_2 = decoder_consistency(latent, generator=torch.Generator("cpu").manual_seed(0))
1079
+ save_image(sample_consistency_new_2, "con_new_2.png")
1080
+
1081
+ assert (sample_consistency_orig == sample_consistency_new_2).all()
1082
+
1083
+ print("running with diffusers model")
1084
+
1085
+ Encoder.old_constructor = Encoder.__init__
1086
+
1087
+
1088
+ def new_constructor(self, **kwargs):
1089
+ self.old_constructor(**kwargs)
1090
+ self.constructor_arguments = kwargs
1091
+
1092
+
1093
+ Encoder.__init__ = new_constructor
1094
+
1095
+
1096
+ vae = AutoencoderKL.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="vae")
1097
+ consistency_vae = ConsistencyDecoderVAE(
1098
+ encoder_args=vae.encoder.constructor_arguments,
1099
+ decoder_args=unet.config,
1100
+ scaling_factor=vae.config.scaling_factor,
1101
+ block_out_channels=vae.config.block_out_channels,
1102
+ latent_channels=vae.config.latent_channels,
1103
+ )
1104
+ consistency_vae.encoder.load_state_dict(vae.encoder.state_dict())
1105
+ consistency_vae.quant_conv.load_state_dict(vae.quant_conv.state_dict())
1106
+ consistency_vae.decoder_unet.load_state_dict(unet.state_dict())
1107
+
1108
+ consistency_vae.to(dtype=torch.float16, device="cuda")
1109
+
1110
+ sample_consistency_new_3 = consistency_vae.decode(
1111
+ 0.18215 * latent, generator=torch.Generator("cpu").manual_seed(0)
1112
+ ).sample
1113
+
1114
+ print("max difference")
1115
+ print((sample_consistency_orig - sample_consistency_new_3).abs().max())
1116
+ print("total difference")
1117
+ print((sample_consistency_orig - sample_consistency_new_3).abs().sum())
1118
+ # assert (sample_consistency_orig == sample_consistency_new_3).all()
1119
+
1120
+ print("running with diffusers pipeline")
1121
+
1122
+ pipe = DiffusionPipeline.from_pretrained(
1123
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", vae=consistency_vae, torch_dtype=torch.float16
1124
+ )
1125
+ pipe.to("cuda")
1126
+
1127
+ pipe("horse", generator=torch.Generator("cpu").manual_seed(0)).images[0].save("horse.png")
1128
+
1129
+
1130
+ if args.save_pretrained is not None:
1131
+ consistency_vae.save_pretrained(args.save_pretrained)
tasks/tasksmith-ee553a5e62c1/environment/source/scripts/convert_consistency_to_diffusers.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import torch
5
+
6
+ from diffusers import (
7
+ CMStochasticIterativeScheduler,
8
+ ConsistencyModelPipeline,
9
+ UNet2DModel,
10
+ )
11
+
12
+
13
+ TEST_UNET_CONFIG = {
14
+ "sample_size": 32,
15
+ "in_channels": 3,
16
+ "out_channels": 3,
17
+ "layers_per_block": 2,
18
+ "num_class_embeds": 1000,
19
+ "block_out_channels": [32, 64],
20
+ "attention_head_dim": 8,
21
+ "down_block_types": [
22
+ "ResnetDownsampleBlock2D",
23
+ "AttnDownBlock2D",
24
+ ],
25
+ "up_block_types": [
26
+ "AttnUpBlock2D",
27
+ "ResnetUpsampleBlock2D",
28
+ ],
29
+ "resnet_time_scale_shift": "scale_shift",
30
+ "attn_norm_num_groups": 32,
31
+ "upsample_type": "resnet",
32
+ "downsample_type": "resnet",
33
+ }
34
+
35
+ IMAGENET_64_UNET_CONFIG = {
36
+ "sample_size": 64,
37
+ "in_channels": 3,
38
+ "out_channels": 3,
39
+ "layers_per_block": 3,
40
+ "num_class_embeds": 1000,
41
+ "block_out_channels": [192, 192 * 2, 192 * 3, 192 * 4],
42
+ "attention_head_dim": 64,
43
+ "down_block_types": [
44
+ "ResnetDownsampleBlock2D",
45
+ "AttnDownBlock2D",
46
+ "AttnDownBlock2D",
47
+ "AttnDownBlock2D",
48
+ ],
49
+ "up_block_types": [
50
+ "AttnUpBlock2D",
51
+ "AttnUpBlock2D",
52
+ "AttnUpBlock2D",
53
+ "ResnetUpsampleBlock2D",
54
+ ],
55
+ "resnet_time_scale_shift": "scale_shift",
56
+ "attn_norm_num_groups": 32,
57
+ "upsample_type": "resnet",
58
+ "downsample_type": "resnet",
59
+ }
60
+
61
+ LSUN_256_UNET_CONFIG = {
62
+ "sample_size": 256,
63
+ "in_channels": 3,
64
+ "out_channels": 3,
65
+ "layers_per_block": 2,
66
+ "num_class_embeds": None,
67
+ "block_out_channels": [256, 256, 256 * 2, 256 * 2, 256 * 4, 256 * 4],
68
+ "attention_head_dim": 64,
69
+ "down_block_types": [
70
+ "ResnetDownsampleBlock2D",
71
+ "ResnetDownsampleBlock2D",
72
+ "ResnetDownsampleBlock2D",
73
+ "AttnDownBlock2D",
74
+ "AttnDownBlock2D",
75
+ "AttnDownBlock2D",
76
+ ],
77
+ "up_block_types": [
78
+ "AttnUpBlock2D",
79
+ "AttnUpBlock2D",
80
+ "AttnUpBlock2D",
81
+ "ResnetUpsampleBlock2D",
82
+ "ResnetUpsampleBlock2D",
83
+ "ResnetUpsampleBlock2D",
84
+ ],
85
+ "resnet_time_scale_shift": "default",
86
+ "upsample_type": "resnet",
87
+ "downsample_type": "resnet",
88
+ }
89
+
90
+ CD_SCHEDULER_CONFIG = {
91
+ "num_train_timesteps": 40,
92
+ "sigma_min": 0.002,
93
+ "sigma_max": 80.0,
94
+ }
95
+
96
+ CT_IMAGENET_64_SCHEDULER_CONFIG = {
97
+ "num_train_timesteps": 201,
98
+ "sigma_min": 0.002,
99
+ "sigma_max": 80.0,
100
+ }
101
+
102
+ CT_LSUN_256_SCHEDULER_CONFIG = {
103
+ "num_train_timesteps": 151,
104
+ "sigma_min": 0.002,
105
+ "sigma_max": 80.0,
106
+ }
107
+
108
+
109
+ def str2bool(v):
110
+ """
111
+ https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
112
+ """
113
+ if isinstance(v, bool):
114
+ return v
115
+ if v.lower() in ("yes", "true", "t", "y", "1"):
116
+ return True
117
+ elif v.lower() in ("no", "false", "f", "n", "0"):
118
+ return False
119
+ else:
120
+ raise argparse.ArgumentTypeError("boolean value expected")
121
+
122
+
123
+ def convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix, has_skip=False):
124
+ new_checkpoint[f"{new_prefix}.norm1.weight"] = checkpoint[f"{old_prefix}.in_layers.0.weight"]
125
+ new_checkpoint[f"{new_prefix}.norm1.bias"] = checkpoint[f"{old_prefix}.in_layers.0.bias"]
126
+ new_checkpoint[f"{new_prefix}.conv1.weight"] = checkpoint[f"{old_prefix}.in_layers.2.weight"]
127
+ new_checkpoint[f"{new_prefix}.conv1.bias"] = checkpoint[f"{old_prefix}.in_layers.2.bias"]
128
+ new_checkpoint[f"{new_prefix}.time_emb_proj.weight"] = checkpoint[f"{old_prefix}.emb_layers.1.weight"]
129
+ new_checkpoint[f"{new_prefix}.time_emb_proj.bias"] = checkpoint[f"{old_prefix}.emb_layers.1.bias"]
130
+ new_checkpoint[f"{new_prefix}.norm2.weight"] = checkpoint[f"{old_prefix}.out_layers.0.weight"]
131
+ new_checkpoint[f"{new_prefix}.norm2.bias"] = checkpoint[f"{old_prefix}.out_layers.0.bias"]
132
+ new_checkpoint[f"{new_prefix}.conv2.weight"] = checkpoint[f"{old_prefix}.out_layers.3.weight"]
133
+ new_checkpoint[f"{new_prefix}.conv2.bias"] = checkpoint[f"{old_prefix}.out_layers.3.bias"]
134
+
135
+ if has_skip:
136
+ new_checkpoint[f"{new_prefix}.conv_shortcut.weight"] = checkpoint[f"{old_prefix}.skip_connection.weight"]
137
+ new_checkpoint[f"{new_prefix}.conv_shortcut.bias"] = checkpoint[f"{old_prefix}.skip_connection.bias"]
138
+
139
+ return new_checkpoint
140
+
141
+
142
+ def convert_attention(checkpoint, new_checkpoint, old_prefix, new_prefix, attention_dim=None):
143
+ weight_q, weight_k, weight_v = checkpoint[f"{old_prefix}.qkv.weight"].chunk(3, dim=0)
144
+ bias_q, bias_k, bias_v = checkpoint[f"{old_prefix}.qkv.bias"].chunk(3, dim=0)
145
+
146
+ new_checkpoint[f"{new_prefix}.group_norm.weight"] = checkpoint[f"{old_prefix}.norm.weight"]
147
+ new_checkpoint[f"{new_prefix}.group_norm.bias"] = checkpoint[f"{old_prefix}.norm.bias"]
148
+
149
+ new_checkpoint[f"{new_prefix}.to_q.weight"] = weight_q.squeeze(-1).squeeze(-1)
150
+ new_checkpoint[f"{new_prefix}.to_q.bias"] = bias_q.squeeze(-1).squeeze(-1)
151
+ new_checkpoint[f"{new_prefix}.to_k.weight"] = weight_k.squeeze(-1).squeeze(-1)
152
+ new_checkpoint[f"{new_prefix}.to_k.bias"] = bias_k.squeeze(-1).squeeze(-1)
153
+ new_checkpoint[f"{new_prefix}.to_v.weight"] = weight_v.squeeze(-1).squeeze(-1)
154
+ new_checkpoint[f"{new_prefix}.to_v.bias"] = bias_v.squeeze(-1).squeeze(-1)
155
+
156
+ new_checkpoint[f"{new_prefix}.to_out.0.weight"] = (
157
+ checkpoint[f"{old_prefix}.proj_out.weight"].squeeze(-1).squeeze(-1)
158
+ )
159
+ new_checkpoint[f"{new_prefix}.to_out.0.bias"] = checkpoint[f"{old_prefix}.proj_out.bias"].squeeze(-1).squeeze(-1)
160
+
161
+ return new_checkpoint
162
+
163
+
164
+ def con_pt_to_diffuser(checkpoint_path: str, unet_config):
165
+ checkpoint = torch.load(checkpoint_path, map_location="cpu")
166
+ new_checkpoint = {}
167
+
168
+ new_checkpoint["time_embedding.linear_1.weight"] = checkpoint["time_embed.0.weight"]
169
+ new_checkpoint["time_embedding.linear_1.bias"] = checkpoint["time_embed.0.bias"]
170
+ new_checkpoint["time_embedding.linear_2.weight"] = checkpoint["time_embed.2.weight"]
171
+ new_checkpoint["time_embedding.linear_2.bias"] = checkpoint["time_embed.2.bias"]
172
+
173
+ if unet_config["num_class_embeds"] is not None:
174
+ new_checkpoint["class_embedding.weight"] = checkpoint["label_emb.weight"]
175
+
176
+ new_checkpoint["conv_in.weight"] = checkpoint["input_blocks.0.0.weight"]
177
+ new_checkpoint["conv_in.bias"] = checkpoint["input_blocks.0.0.bias"]
178
+
179
+ down_block_types = unet_config["down_block_types"]
180
+ layers_per_block = unet_config["layers_per_block"]
181
+ attention_head_dim = unet_config["attention_head_dim"]
182
+ channels_list = unet_config["block_out_channels"]
183
+ current_layer = 1
184
+ prev_channels = channels_list[0]
185
+
186
+ for i, layer_type in enumerate(down_block_types):
187
+ current_channels = channels_list[i]
188
+ downsample_block_has_skip = current_channels != prev_channels
189
+ if layer_type == "ResnetDownsampleBlock2D":
190
+ for j in range(layers_per_block):
191
+ new_prefix = f"down_blocks.{i}.resnets.{j}"
192
+ old_prefix = f"input_blocks.{current_layer}.0"
193
+ has_skip = True if j == 0 and downsample_block_has_skip else False
194
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix, has_skip=has_skip)
195
+ current_layer += 1
196
+
197
+ elif layer_type == "AttnDownBlock2D":
198
+ for j in range(layers_per_block):
199
+ new_prefix = f"down_blocks.{i}.resnets.{j}"
200
+ old_prefix = f"input_blocks.{current_layer}.0"
201
+ has_skip = True if j == 0 and downsample_block_has_skip else False
202
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix, has_skip=has_skip)
203
+ new_prefix = f"down_blocks.{i}.attentions.{j}"
204
+ old_prefix = f"input_blocks.{current_layer}.1"
205
+ new_checkpoint = convert_attention(
206
+ checkpoint, new_checkpoint, old_prefix, new_prefix, attention_head_dim
207
+ )
208
+ current_layer += 1
209
+
210
+ if i != len(down_block_types) - 1:
211
+ new_prefix = f"down_blocks.{i}.downsamplers.0"
212
+ old_prefix = f"input_blocks.{current_layer}.0"
213
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix)
214
+ current_layer += 1
215
+
216
+ prev_channels = current_channels
217
+
218
+ # hardcoded the mid-block for now
219
+ new_prefix = "mid_block.resnets.0"
220
+ old_prefix = "middle_block.0"
221
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix)
222
+ new_prefix = "mid_block.attentions.0"
223
+ old_prefix = "middle_block.1"
224
+ new_checkpoint = convert_attention(checkpoint, new_checkpoint, old_prefix, new_prefix, attention_head_dim)
225
+ new_prefix = "mid_block.resnets.1"
226
+ old_prefix = "middle_block.2"
227
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix)
228
+
229
+ current_layer = 0
230
+ up_block_types = unet_config["up_block_types"]
231
+
232
+ for i, layer_type in enumerate(up_block_types):
233
+ if layer_type == "ResnetUpsampleBlock2D":
234
+ for j in range(layers_per_block + 1):
235
+ new_prefix = f"up_blocks.{i}.resnets.{j}"
236
+ old_prefix = f"output_blocks.{current_layer}.0"
237
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix, has_skip=True)
238
+ current_layer += 1
239
+
240
+ if i != len(up_block_types) - 1:
241
+ new_prefix = f"up_blocks.{i}.upsamplers.0"
242
+ old_prefix = f"output_blocks.{current_layer - 1}.1"
243
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix)
244
+ elif layer_type == "AttnUpBlock2D":
245
+ for j in range(layers_per_block + 1):
246
+ new_prefix = f"up_blocks.{i}.resnets.{j}"
247
+ old_prefix = f"output_blocks.{current_layer}.0"
248
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix, has_skip=True)
249
+ new_prefix = f"up_blocks.{i}.attentions.{j}"
250
+ old_prefix = f"output_blocks.{current_layer}.1"
251
+ new_checkpoint = convert_attention(
252
+ checkpoint, new_checkpoint, old_prefix, new_prefix, attention_head_dim
253
+ )
254
+ current_layer += 1
255
+
256
+ if i != len(up_block_types) - 1:
257
+ new_prefix = f"up_blocks.{i}.upsamplers.0"
258
+ old_prefix = f"output_blocks.{current_layer - 1}.2"
259
+ new_checkpoint = convert_resnet(checkpoint, new_checkpoint, old_prefix, new_prefix)
260
+
261
+ new_checkpoint["conv_norm_out.weight"] = checkpoint["out.0.weight"]
262
+ new_checkpoint["conv_norm_out.bias"] = checkpoint["out.0.bias"]
263
+ new_checkpoint["conv_out.weight"] = checkpoint["out.2.weight"]
264
+ new_checkpoint["conv_out.bias"] = checkpoint["out.2.bias"]
265
+
266
+ return new_checkpoint
267
+
268
+
269
+ if __name__ == "__main__":
270
+ parser = argparse.ArgumentParser()
271
+
272
+ parser.add_argument("--unet_path", default=None, type=str, required=True, help="Path to the unet.pt to convert.")
273
+ parser.add_argument(
274
+ "--dump_path", default=None, type=str, required=True, help="Path to output the converted UNet model."
275
+ )
276
+ parser.add_argument("--class_cond", default=True, type=str, help="Whether the model is class-conditional.")
277
+
278
+ args = parser.parse_args()
279
+ args.class_cond = str2bool(args.class_cond)
280
+
281
+ ckpt_name = os.path.basename(args.unet_path)
282
+ print(f"Checkpoint: {ckpt_name}")
283
+
284
+ # Get U-Net config
285
+ if "imagenet64" in ckpt_name:
286
+ unet_config = IMAGENET_64_UNET_CONFIG
287
+ elif "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
288
+ unet_config = LSUN_256_UNET_CONFIG
289
+ elif "test" in ckpt_name:
290
+ unet_config = TEST_UNET_CONFIG
291
+ else:
292
+ raise ValueError(f"Checkpoint type {ckpt_name} is not currently supported.")
293
+
294
+ if not args.class_cond:
295
+ unet_config["num_class_embeds"] = None
296
+
297
+ converted_unet_ckpt = con_pt_to_diffuser(args.unet_path, unet_config)
298
+
299
+ image_unet = UNet2DModel(**unet_config)
300
+ image_unet.load_state_dict(converted_unet_ckpt)
301
+
302
+ # Get scheduler config
303
+ if "cd" in ckpt_name or "test" in ckpt_name:
304
+ scheduler_config = CD_SCHEDULER_CONFIG
305
+ elif "ct" in ckpt_name and "imagenet64" in ckpt_name:
306
+ scheduler_config = CT_IMAGENET_64_SCHEDULER_CONFIG
307
+ elif "ct" in ckpt_name and "256" in ckpt_name and (("bedroom" in ckpt_name) or ("cat" in ckpt_name)):
308
+ scheduler_config = CT_LSUN_256_SCHEDULER_CONFIG
309
+ else:
310
+ raise ValueError(f"Checkpoint type {ckpt_name} is not currently supported.")
311
+
312
+ cm_scheduler = CMStochasticIterativeScheduler(**scheduler_config)
313
+
314
+ consistency_model = ConsistencyModelPipeline(unet=image_unet, scheduler=cm_scheduler)
315
+ consistency_model.save_pretrained(args.dump_path)