AdithyaSK HF Staff commited on
Commit
b2e752e
·
verified ·
1 Parent(s): ff22d1e

Stage Harbor release files 61001-61500

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-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md +93 -0
  2. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt +7 -0
  3. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py +112 -0
  4. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py +996 -0
  5. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/README.md +226 -0
  6. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/requirements.txt +4 -0
  7. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py +415 -0
  8. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py +422 -0
  9. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py +445 -0
  10. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py +520 -0
  11. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/README.md +83 -0
  12. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/requirements.txt +8 -0
  13. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/train_text_to_image_lora.py +1026 -0
  14. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/README.md +338 -0
  15. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/requirements.txt +6 -0
  16. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py +1195 -0
  17. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/README.md +93 -0
  18. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/requirements.txt +8 -0
  19. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/train_multi_subject_dreambooth_inpainting.py +661 -0
  20. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/README.md +143 -0
  21. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/multi_token_clip.py +104 -0
  22. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/requirements.txt +6 -0
  23. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/requirements_flax.txt +8 -0
  24. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion.py +938 -0
  25. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion_flax.py +654 -0
  26. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/README.md +5 -0
  27. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/README.md +74 -0
  28. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/requirements.txt +7 -0
  29. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/train_text_to_image.py +955 -0
  30. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/textual_inversion/README.md +94 -0
  31. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/textual_inversion/requirements.txt +6 -0
  32. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/textual_inversion/textual_inversion.py +959 -0
  33. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/README.md +50 -0
  34. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/requirements.txt +4 -0
  35. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/train_unconditional.py +697 -0
  36. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/.gitignore +2 -0
  37. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/controlnet_pixart_alpha.py +291 -0
  38. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/pipeline_pixart_alpha_controlnet.py +1098 -0
  39. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/requirements.txt +6 -0
  40. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/run_pixart_alpha_controlnet_pipeline.py +75 -0
  41. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/train_controlnet_hf_diffusers.sh +23 -0
  42. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/train_pixart_controlnet_hf.py +1174 -0
  43. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/README.md +49 -0
  44. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/convert_original_promptdiffusion_to_diffusers.py +2119 -0
  45. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/pipeline_prompt_diffusion.py +1339 -0
  46. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/promptdiffusioncontrolnet.py +386 -0
  47. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/inference/flux/README.md +166 -0
  48. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/inference/flux/flux_inference.py +134 -0
  49. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/training/text_to_image/README.md +170 -0
  50. tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/training/text_to_image/requirements.txt +8 -0
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Distillation for quantization on Textual Inversion models to personalize text2image
2
+
3
+ [Textual inversion](https://huggingface.co/papers/2208.01618) is a method to personalize text2image models like stable diffusion on your own images._By using just 3-5 images new concepts can be taught to Stable Diffusion and the model personalized on your own images_
4
+ The `textual_inversion.py` script shows how to implement the training procedure and adapt it for stable diffusion.
5
+ We have enabled distillation for quantization in `textual_inversion.py` to do quantization aware training as well as distillation on the model generated by Textual Inversion method.
6
+
7
+ ## Installing the dependencies
8
+
9
+ Before running the scripts, make sure to install the library's training dependencies:
10
+
11
+ ```bash
12
+ pip install -r requirements.txt
13
+ ```
14
+
15
+ ## Prepare Datasets
16
+
17
+ One picture which is from the huggingface datasets [sd-concepts-library/dicoo2](https://huggingface.co/sd-concepts-library/dicoo2) is needed, and save it to the `./dicoo` directory. The picture is shown below:
18
+
19
+ <a href="https://huggingface.co/sd-concepts-library/dicoo2/blob/main/concept_images/1.jpeg">
20
+ <img src="https://huggingface.co/sd-concepts-library/dicoo2/resolve/main/concept_images/1.jpeg" width = "300" height="300">
21
+ </a>
22
+
23
+ ## Get a FP32 Textual Inversion model
24
+
25
+ Use the following command to fine-tune the Stable Diffusion model on the above dataset to obtain the FP32 Textual Inversion model.
26
+
27
+ ```bash
28
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
29
+ export DATA_DIR="./dicoo"
30
+
31
+ accelerate launch textual_inversion.py \
32
+ --pretrained_model_name_or_path=$MODEL_NAME \
33
+ --train_data_dir=$DATA_DIR \
34
+ --learnable_property="object" \
35
+ --placeholder_token="<dicoo>" --initializer_token="toy" \
36
+ --resolution=512 \
37
+ --train_batch_size=1 \
38
+ --gradient_accumulation_steps=4 \
39
+ --max_train_steps=3000 \
40
+ --learning_rate=5.0e-04 --scale_lr \
41
+ --lr_scheduler="constant" \
42
+ --lr_warmup_steps=0 \
43
+ --output_dir="dicoo_model"
44
+ ```
45
+
46
+ ## Do distillation for quantization
47
+
48
+ Distillation for quantization is a method that combines [intermediate layer knowledge distillation](https://github.com/intel/neural-compressor/blob/master/docs/source/distillation.md#intermediate-layer-knowledge-distillation) and [quantization aware training](https://github.com/intel/neural-compressor/blob/master/docs/source/quantization.md#quantization-aware-training) in the same training process to improve the performance of the quantized model. Provided a FP32 model, the distillation for quantization approach will take this model itself as the teacher model and transfer the knowledges of the specified layers to the student model, i.e. quantized version of the FP32 model, during the quantization aware training process.
49
+
50
+ Once you have the FP32 Textual Inversion model, the following command will take the FP32 Textual Inversion model as input to do distillation for quantization and generate the INT8 Textual Inversion model.
51
+
52
+ ```bash
53
+ export FP32_MODEL_NAME="./dicoo_model"
54
+ export DATA_DIR="./dicoo"
55
+
56
+ accelerate launch textual_inversion.py \
57
+ --pretrained_model_name_or_path=$FP32_MODEL_NAME \
58
+ --train_data_dir=$DATA_DIR \
59
+ --use_ema --learnable_property="object" \
60
+ --placeholder_token="<dicoo>" --initializer_token="toy" \
61
+ --resolution=512 \
62
+ --train_batch_size=1 \
63
+ --gradient_accumulation_steps=4 \
64
+ --max_train_steps=300 \
65
+ --learning_rate=5.0e-04 --max_grad_norm=3 \
66
+ --lr_scheduler="constant" \
67
+ --lr_warmup_steps=0 \
68
+ --output_dir="int8_model" \
69
+ --do_quantization --do_distillation --verify_loading
70
+ ```
71
+
72
+ After the distillation for quantization process, the quantized UNet would be 4 times smaller (3279MB -> 827MB).
73
+
74
+ ## Inference
75
+
76
+ Once you have trained a INT8 model with the above command, the inference can be done simply using the `text2images.py` script. Make sure to include the `placeholder_token` in your prompt.
77
+
78
+ ```bash
79
+ export INT8_MODEL_NAME="./int8_model"
80
+
81
+ python text2images.py \
82
+ --pretrained_model_name_or_path=$INT8_MODEL_NAME \
83
+ --caption "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brightly buildings." \
84
+ --images_num 4
85
+ ```
86
+
87
+ Here is the comparison of images generated by the FP32 model (left) and INT8 model (right) respectively:
88
+
89
+ <p float="left">
90
+ <img src="https://huggingface.co/datasets/Intel/textual_inversion_dicoo_dfq/resolve/main/FP32.png" width = "300" height = "300" alt="FP32" align=center />
91
+ <img src="https://huggingface.co/datasets/Intel/textual_inversion_dicoo_dfq/resolve/main/INT8.png" width = "300" height = "300" alt="INT8" align=center />
92
+ </p>
93
+
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ torchvision
3
+ transformers>=4.25.0
4
+ ftfy
5
+ tensorboard
6
+ modelcards
7
+ neural-compressor
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+
5
+ import torch
6
+ from neural_compressor.utils.pytorch import load
7
+ from PIL import Image
8
+ from transformers import CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import AutoencoderKL, StableDiffusionPipeline, UNet2DConditionModel
11
+
12
+
13
+ def parse_args():
14
+ parser = argparse.ArgumentParser()
15
+ parser.add_argument(
16
+ "-m",
17
+ "--pretrained_model_name_or_path",
18
+ type=str,
19
+ default=None,
20
+ required=True,
21
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
22
+ )
23
+ parser.add_argument(
24
+ "-c",
25
+ "--caption",
26
+ type=str,
27
+ default="robotic cat with wings",
28
+ help="Text used to generate images.",
29
+ )
30
+ parser.add_argument(
31
+ "-n",
32
+ "--images_num",
33
+ type=int,
34
+ default=4,
35
+ help="How much images to generate.",
36
+ )
37
+ parser.add_argument(
38
+ "-s",
39
+ "--seed",
40
+ type=int,
41
+ default=42,
42
+ help="Seed for random process.",
43
+ )
44
+ parser.add_argument(
45
+ "-ci",
46
+ "--cuda_id",
47
+ type=int,
48
+ default=0,
49
+ help="cuda_id.",
50
+ )
51
+ args = parser.parse_args()
52
+ return args
53
+
54
+
55
+ def image_grid(imgs, rows, cols):
56
+ if not len(imgs) == rows * cols:
57
+ raise ValueError("The specified number of rows and columns are not correct.")
58
+
59
+ w, h = imgs[0].size
60
+ grid = Image.new("RGB", size=(cols * w, rows * h))
61
+ grid_w, grid_h = grid.size
62
+
63
+ for i, img in enumerate(imgs):
64
+ grid.paste(img, box=(i % cols * w, i // cols * h))
65
+ return grid
66
+
67
+
68
+ def generate_images(
69
+ pipeline,
70
+ prompt="robotic cat with wings",
71
+ guidance_scale=7.5,
72
+ num_inference_steps=50,
73
+ num_images_per_prompt=1,
74
+ seed=42,
75
+ ):
76
+ generator = torch.Generator(pipeline.device).manual_seed(seed)
77
+ images = pipeline(
78
+ prompt,
79
+ guidance_scale=guidance_scale,
80
+ num_inference_steps=num_inference_steps,
81
+ generator=generator,
82
+ num_images_per_prompt=num_images_per_prompt,
83
+ ).images
84
+ _rows = int(math.sqrt(num_images_per_prompt))
85
+ grid = image_grid(images, rows=_rows, cols=num_images_per_prompt // _rows)
86
+ return grid, images
87
+
88
+
89
+ args = parse_args()
90
+ # Load models and create wrapper for stable diffusion
91
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
92
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
93
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
94
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
95
+
96
+ pipeline = StableDiffusionPipeline.from_pretrained(
97
+ args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
98
+ )
99
+ pipeline.safety_checker = lambda images, clip_input: (images, False)
100
+ if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")):
101
+ unet = load(args.pretrained_model_name_or_path, model=unet)
102
+ unet.eval()
103
+ setattr(pipeline, "unet", unet)
104
+ else:
105
+ unet = unet.to(torch.device("cuda", args.cuda_id))
106
+ pipeline = pipeline.to(unet.device)
107
+ grid, images = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
108
+ grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split()))))
109
+ dirname = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split()))
110
+ os.makedirs(dirname, exist_ok=True)
111
+ for idx, image in enumerate(images):
112
+ image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py ADDED
@@ -0,0 +1,996 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import math
4
+ import os
5
+ import random
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ import numpy as np
10
+ import PIL
11
+ import torch
12
+ import torch.nn.functional as F
13
+ import torch.utils.checkpoint
14
+ from accelerate import Accelerator
15
+ from accelerate.utils import ProjectConfiguration, set_seed
16
+ from huggingface_hub import create_repo, upload_folder
17
+ from neural_compressor.utils import logger
18
+ from packaging import version
19
+ from PIL import Image
20
+ from torch.utils.data import Dataset
21
+ from torchvision import transforms
22
+ from tqdm.auto import tqdm
23
+ from transformers import CLIPTextModel, CLIPTokenizer
24
+
25
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
26
+ from diffusers.optimization import get_scheduler
27
+ from diffusers.utils import make_image_grid
28
+
29
+
30
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
31
+ PIL_INTERPOLATION = {
32
+ "linear": PIL.Image.Resampling.BILINEAR,
33
+ "bilinear": PIL.Image.Resampling.BILINEAR,
34
+ "bicubic": PIL.Image.Resampling.BICUBIC,
35
+ "lanczos": PIL.Image.Resampling.LANCZOS,
36
+ "nearest": PIL.Image.Resampling.NEAREST,
37
+ }
38
+ else:
39
+ PIL_INTERPOLATION = {
40
+ "linear": PIL.Image.LINEAR,
41
+ "bilinear": PIL.Image.BILINEAR,
42
+ "bicubic": PIL.Image.BICUBIC,
43
+ "lanczos": PIL.Image.LANCZOS,
44
+ "nearest": PIL.Image.NEAREST,
45
+ }
46
+ # ------------------------------------------------------------------------------
47
+
48
+
49
+ def save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path):
50
+ logger.info("Saving embeddings")
51
+ learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]
52
+ learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
53
+ torch.save(learned_embeds_dict, save_path)
54
+
55
+
56
+ def parse_args():
57
+ parser = argparse.ArgumentParser(description="Example of distillation for quantization on Textual Inversion.")
58
+ parser.add_argument(
59
+ "--save_steps",
60
+ type=int,
61
+ default=500,
62
+ help="Save learned_embeds.bin every X updates steps.",
63
+ )
64
+ parser.add_argument(
65
+ "--pretrained_model_name_or_path",
66
+ type=str,
67
+ default=None,
68
+ required=True,
69
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
70
+ )
71
+ parser.add_argument(
72
+ "--revision",
73
+ type=str,
74
+ default=None,
75
+ required=False,
76
+ help="Revision of pretrained model identifier from huggingface.co/models.",
77
+ )
78
+ parser.add_argument(
79
+ "--tokenizer_name",
80
+ type=str,
81
+ default=None,
82
+ help="Pretrained tokenizer name or path if not the same as model_name",
83
+ )
84
+ parser.add_argument(
85
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
86
+ )
87
+ parser.add_argument(
88
+ "--placeholder_token",
89
+ type=str,
90
+ default=None,
91
+ required=True,
92
+ help="A token to use as a placeholder for the concept.",
93
+ )
94
+ parser.add_argument(
95
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
96
+ )
97
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
98
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
99
+ parser.add_argument(
100
+ "--output_dir",
101
+ type=str,
102
+ default="text-inversion-model",
103
+ help="The output directory where the model predictions and checkpoints will be written.",
104
+ )
105
+ parser.add_argument(
106
+ "--cache_dir",
107
+ type=str,
108
+ default=None,
109
+ help="The directory where the downloaded models and datasets will be stored.",
110
+ )
111
+ parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible training.")
112
+ parser.add_argument(
113
+ "--resolution",
114
+ type=int,
115
+ default=512,
116
+ help=(
117
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
118
+ " resolution"
119
+ ),
120
+ )
121
+ parser.add_argument(
122
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
123
+ )
124
+ parser.add_argument(
125
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
126
+ )
127
+ parser.add_argument("--num_train_epochs", type=int, default=100)
128
+ parser.add_argument(
129
+ "--max_train_steps",
130
+ type=int,
131
+ default=5000,
132
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
133
+ )
134
+ parser.add_argument(
135
+ "--gradient_accumulation_steps",
136
+ type=int,
137
+ default=1,
138
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
139
+ )
140
+ parser.add_argument(
141
+ "--learning_rate",
142
+ type=float,
143
+ default=1e-4,
144
+ help="Initial learning rate (after the potential warmup period) to use.",
145
+ )
146
+ parser.add_argument(
147
+ "--scale_lr",
148
+ action="store_true",
149
+ default=False,
150
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
151
+ )
152
+ parser.add_argument(
153
+ "--lr_scheduler",
154
+ type=str,
155
+ default="constant",
156
+ help=(
157
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
158
+ ' "constant", "constant_with_warmup"]'
159
+ ),
160
+ )
161
+ parser.add_argument(
162
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
163
+ )
164
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
165
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
166
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
167
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
168
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
169
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
170
+ parser.add_argument(
171
+ "--hub_model_id",
172
+ type=str,
173
+ default=None,
174
+ help="The name of the repository to keep in sync with the local `output_dir`.",
175
+ )
176
+ parser.add_argument(
177
+ "--logging_dir",
178
+ type=str,
179
+ default="logs",
180
+ help=(
181
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
182
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
183
+ ),
184
+ )
185
+ parser.add_argument(
186
+ "--mixed_precision",
187
+ type=str,
188
+ default="no",
189
+ choices=["no", "fp16", "bf16"],
190
+ help=(
191
+ "Whether to use mixed precision. Choose"
192
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
193
+ "and an Nvidia Ampere GPU."
194
+ ),
195
+ )
196
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
197
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
198
+ parser.add_argument("--do_quantization", action="store_true", help="Whether or not to do quantization.")
199
+ parser.add_argument("--do_distillation", action="store_true", help="Whether or not to do distillation.")
200
+ parser.add_argument(
201
+ "--verify_loading", action="store_true", help="Whether or not to verify the loading of the quantized model."
202
+ )
203
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
204
+
205
+ args = parser.parse_args()
206
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
207
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
208
+ args.local_rank = env_local_rank
209
+
210
+ if args.train_data_dir is None:
211
+ raise ValueError("You must specify a train data directory.")
212
+
213
+ return args
214
+
215
+
216
+ imagenet_templates_small = [
217
+ "a photo of a {}",
218
+ "a rendering of a {}",
219
+ "a cropped photo of the {}",
220
+ "the photo of a {}",
221
+ "a photo of a clean {}",
222
+ "a photo of a dirty {}",
223
+ "a dark photo of the {}",
224
+ "a photo of my {}",
225
+ "a photo of the cool {}",
226
+ "a close-up photo of a {}",
227
+ "a bright photo of the {}",
228
+ "a cropped photo of a {}",
229
+ "a photo of the {}",
230
+ "a good photo of the {}",
231
+ "a photo of one {}",
232
+ "a close-up photo of the {}",
233
+ "a rendition of the {}",
234
+ "a photo of the clean {}",
235
+ "a rendition of a {}",
236
+ "a photo of a nice {}",
237
+ "a good photo of a {}",
238
+ "a photo of the nice {}",
239
+ "a photo of the small {}",
240
+ "a photo of the weird {}",
241
+ "a photo of the large {}",
242
+ "a photo of a cool {}",
243
+ "a photo of a small {}",
244
+ ]
245
+
246
+ imagenet_style_templates_small = [
247
+ "a painting in the style of {}",
248
+ "a rendering in the style of {}",
249
+ "a cropped painting in the style of {}",
250
+ "the painting in the style of {}",
251
+ "a clean painting in the style of {}",
252
+ "a dirty painting in the style of {}",
253
+ "a dark painting in the style of {}",
254
+ "a picture in the style of {}",
255
+ "a cool painting in the style of {}",
256
+ "a close-up painting in the style of {}",
257
+ "a bright painting in the style of {}",
258
+ "a cropped painting in the style of {}",
259
+ "a good painting in the style of {}",
260
+ "a close-up painting in the style of {}",
261
+ "a rendition in the style of {}",
262
+ "a nice painting in the style of {}",
263
+ "a small painting in the style of {}",
264
+ "a weird painting in the style of {}",
265
+ "a large painting in the style of {}",
266
+ ]
267
+
268
+
269
+ # Adapted from torch-ema https://github.com/fadel/pytorch_ema/blob/master/torch_ema/ema.py#L14
270
+ class EMAModel:
271
+ """
272
+ Exponential Moving Average of models weights
273
+ """
274
+
275
+ def __init__(self, parameters: Iterable[torch.nn.Parameter], decay=0.9999):
276
+ parameters = list(parameters)
277
+ self.shadow_params = [p.clone().detach() for p in parameters]
278
+
279
+ self.decay = decay
280
+ self.optimization_step = 0
281
+
282
+ def get_decay(self, optimization_step):
283
+ """
284
+ Compute the decay factor for the exponential moving average.
285
+ """
286
+ value = (1 + optimization_step) / (10 + optimization_step)
287
+ return 1 - min(self.decay, value)
288
+
289
+ @torch.no_grad()
290
+ def step(self, parameters):
291
+ parameters = list(parameters)
292
+
293
+ self.optimization_step += 1
294
+ self.decay = self.get_decay(self.optimization_step)
295
+
296
+ for s_param, param in zip(self.shadow_params, parameters):
297
+ if param.requires_grad:
298
+ tmp = self.decay * (s_param - param)
299
+ s_param.sub_(tmp)
300
+ else:
301
+ s_param.copy_(param)
302
+
303
+ torch.cuda.empty_cache()
304
+
305
+ def copy_to(self, parameters: Iterable[torch.nn.Parameter]) -> None:
306
+ """
307
+ Copy current averaged parameters into given collection of parameters.
308
+ Args:
309
+ parameters: Iterable of `torch.nn.Parameter`; the parameters to be
310
+ updated with the stored moving averages. If `None`, the
311
+ parameters with which this `ExponentialMovingAverage` was
312
+ initialized will be used.
313
+ """
314
+ parameters = list(parameters)
315
+ for s_param, param in zip(self.shadow_params, parameters):
316
+ param.data.copy_(s_param.data)
317
+
318
+ def to(self, device=None, dtype=None) -> None:
319
+ r"""Move internal buffers of the ExponentialMovingAverage to `device`.
320
+ Args:
321
+ device: like `device` argument to `torch.Tensor.to`
322
+ """
323
+ # .to() on the tensors handles None correctly
324
+ self.shadow_params = [
325
+ p.to(device=device, dtype=dtype) if p.is_floating_point() else p.to(device=device)
326
+ for p in self.shadow_params
327
+ ]
328
+
329
+
330
+ class TextualInversionDataset(Dataset):
331
+ def __init__(
332
+ self,
333
+ data_root,
334
+ tokenizer,
335
+ learnable_property="object", # [object, style]
336
+ size=512,
337
+ repeats=100,
338
+ interpolation="bicubic",
339
+ flip_p=0.5,
340
+ set="train",
341
+ placeholder_token="*",
342
+ center_crop=False,
343
+ ):
344
+ self.data_root = data_root
345
+ self.tokenizer = tokenizer
346
+ self.learnable_property = learnable_property
347
+ self.size = size
348
+ self.placeholder_token = placeholder_token
349
+ self.center_crop = center_crop
350
+ self.flip_p = flip_p
351
+
352
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
353
+
354
+ self.num_images = len(self.image_paths)
355
+ self._length = self.num_images
356
+
357
+ if set == "train":
358
+ self._length = self.num_images * repeats
359
+
360
+ self.interpolation = {
361
+ "linear": PIL_INTERPOLATION["linear"],
362
+ "bilinear": PIL_INTERPOLATION["bilinear"],
363
+ "bicubic": PIL_INTERPOLATION["bicubic"],
364
+ "lanczos": PIL_INTERPOLATION["lanczos"],
365
+ }[interpolation]
366
+
367
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
368
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
369
+
370
+ def __len__(self):
371
+ return self._length
372
+
373
+ def __getitem__(self, i):
374
+ example = {}
375
+ image = Image.open(self.image_paths[i % self.num_images])
376
+
377
+ if not image.mode == "RGB":
378
+ image = image.convert("RGB")
379
+
380
+ placeholder_string = self.placeholder_token
381
+ text = random.choice(self.templates).format(placeholder_string)
382
+
383
+ example["input_ids"] = self.tokenizer(
384
+ text,
385
+ padding="max_length",
386
+ truncation=True,
387
+ max_length=self.tokenizer.model_max_length,
388
+ return_tensors="pt",
389
+ ).input_ids[0]
390
+
391
+ # default to score-sde preprocessing
392
+ img = np.array(image).astype(np.uint8)
393
+
394
+ if self.center_crop:
395
+ crop = min(img.shape[0], img.shape[1])
396
+ (
397
+ h,
398
+ w,
399
+ ) = (
400
+ img.shape[0],
401
+ img.shape[1],
402
+ )
403
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
404
+
405
+ image = Image.fromarray(img)
406
+ image = image.resize((self.size, self.size), resample=self.interpolation)
407
+
408
+ image = self.flip_transform(image)
409
+ image = np.array(image).astype(np.uint8)
410
+ image = (image / 127.5 - 1.0).astype(np.float32)
411
+
412
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
413
+ return example
414
+
415
+
416
+ def freeze_params(params):
417
+ for param in params:
418
+ param.requires_grad = False
419
+
420
+
421
+ def generate_images(pipeline, prompt="", guidance_scale=7.5, num_inference_steps=50, num_images_per_prompt=1, seed=42):
422
+ generator = torch.Generator(pipeline.device).manual_seed(seed)
423
+ images = pipeline(
424
+ prompt,
425
+ guidance_scale=guidance_scale,
426
+ num_inference_steps=num_inference_steps,
427
+ generator=generator,
428
+ num_images_per_prompt=num_images_per_prompt,
429
+ ).images
430
+ _rows = int(math.sqrt(num_images_per_prompt))
431
+ grid = make_image_grid(images, rows=_rows, cols=num_images_per_prompt // _rows)
432
+ return grid
433
+
434
+
435
+ def main():
436
+ args = parse_args()
437
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
438
+
439
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
440
+
441
+ accelerator = Accelerator(
442
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
443
+ mixed_precision=args.mixed_precision,
444
+ log_with="tensorboard",
445
+ project_config=accelerator_project_config,
446
+ )
447
+
448
+ # If passed along, set the training seed now.
449
+ if args.seed is not None:
450
+ set_seed(args.seed)
451
+
452
+ # Handle the repository creation
453
+ if accelerator.is_main_process:
454
+ if args.output_dir is not None:
455
+ os.makedirs(args.output_dir, exist_ok=True)
456
+
457
+ if args.push_to_hub:
458
+ repo_id = create_repo(
459
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
460
+ ).repo_id
461
+
462
+ # Load the tokenizer and add the placeholder token as a additional special token
463
+ if args.tokenizer_name:
464
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
465
+ elif args.pretrained_model_name_or_path:
466
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
467
+
468
+ # Load models and create wrapper for stable diffusion
469
+ noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
470
+ text_encoder = CLIPTextModel.from_pretrained(
471
+ args.pretrained_model_name_or_path,
472
+ subfolder="text_encoder",
473
+ revision=args.revision,
474
+ )
475
+ vae = AutoencoderKL.from_pretrained(
476
+ args.pretrained_model_name_or_path,
477
+ subfolder="vae",
478
+ revision=args.revision,
479
+ )
480
+ unet = UNet2DConditionModel.from_pretrained(
481
+ args.pretrained_model_name_or_path,
482
+ subfolder="unet",
483
+ revision=args.revision,
484
+ )
485
+
486
+ train_unet = False
487
+ # Freeze vae and unet
488
+ freeze_params(vae.parameters())
489
+ if not args.do_quantization and not args.do_distillation:
490
+ # Add the placeholder token in tokenizer
491
+ num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
492
+ if num_added_tokens == 0:
493
+ raise ValueError(
494
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
495
+ " `placeholder_token` that is not already in the tokenizer."
496
+ )
497
+
498
+ # Convert the initializer_token, placeholder_token to ids
499
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
500
+ # Check if initializer_token is a single token or a sequence of tokens
501
+ if len(token_ids) > 1:
502
+ raise ValueError("The initializer token must be a single token.")
503
+
504
+ initializer_token_id = token_ids[0]
505
+ placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
506
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
507
+ text_encoder.resize_token_embeddings(len(tokenizer))
508
+
509
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
510
+ token_embeds = text_encoder.get_input_embeddings().weight.data
511
+ token_embeds[placeholder_token_id] = token_embeds[initializer_token_id]
512
+
513
+ freeze_params(unet.parameters())
514
+ # Freeze all parameters except for the token embeddings in text encoder
515
+ params_to_freeze = itertools.chain(
516
+ text_encoder.text_model.encoder.parameters(),
517
+ text_encoder.text_model.final_layer_norm.parameters(),
518
+ text_encoder.text_model.embeddings.position_embedding.parameters(),
519
+ )
520
+ freeze_params(params_to_freeze)
521
+ else:
522
+ train_unet = True
523
+ freeze_params(text_encoder.parameters())
524
+
525
+ if args.scale_lr:
526
+ args.learning_rate = (
527
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
528
+ )
529
+
530
+ # Initialize the optimizer
531
+ optimizer = torch.optim.AdamW(
532
+ # only optimize the unet or embeddings of text_encoder
533
+ unet.parameters() if train_unet else text_encoder.get_input_embeddings().parameters(),
534
+ lr=args.learning_rate,
535
+ betas=(args.adam_beta1, args.adam_beta2),
536
+ weight_decay=args.adam_weight_decay,
537
+ eps=args.adam_epsilon,
538
+ )
539
+
540
+ train_dataset = TextualInversionDataset(
541
+ data_root=args.train_data_dir,
542
+ tokenizer=tokenizer,
543
+ size=args.resolution,
544
+ placeholder_token=args.placeholder_token,
545
+ repeats=args.repeats,
546
+ learnable_property=args.learnable_property,
547
+ center_crop=args.center_crop,
548
+ set="train",
549
+ )
550
+ train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True)
551
+
552
+ # Scheduler and math around the number of training steps.
553
+ overrode_max_train_steps = False
554
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
555
+ if args.max_train_steps is None:
556
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
557
+ overrode_max_train_steps = True
558
+
559
+ lr_scheduler = get_scheduler(
560
+ args.lr_scheduler,
561
+ optimizer=optimizer,
562
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
563
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
564
+ )
565
+
566
+ if not train_unet:
567
+ text_encoder = accelerator.prepare(text_encoder)
568
+ unet.to(accelerator.device)
569
+ unet.eval()
570
+ else:
571
+ unet = accelerator.prepare(unet)
572
+ text_encoder.to(accelerator.device)
573
+ text_encoder.eval()
574
+ optimizer, train_dataloader, lr_scheduler = accelerator.prepare(optimizer, train_dataloader, lr_scheduler)
575
+
576
+ # Move vae to device
577
+ vae.to(accelerator.device)
578
+
579
+ # Keep vae in eval model as we don't train these
580
+ vae.eval()
581
+
582
+ compression_manager = None
583
+
584
+ def train_func(model):
585
+ if train_unet:
586
+ unet_ = model
587
+ text_encoder_ = text_encoder
588
+ else:
589
+ unet_ = unet
590
+ text_encoder_ = model
591
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
592
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
593
+ if overrode_max_train_steps:
594
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
595
+ # Afterwards we recalculate our number of training epochs
596
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
597
+
598
+ # We need to initialize the trackers we use, and also store our configuration.
599
+ # The trackers initializes automatically on the main process.
600
+ if accelerator.is_main_process:
601
+ accelerator.init_trackers("textual_inversion", config=vars(args))
602
+
603
+ # Train!
604
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
605
+
606
+ logger.info("***** Running training *****")
607
+ logger.info(f" Num examples = {len(train_dataset)}")
608
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
609
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
610
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
611
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
612
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
613
+ # Only show the progress bar once on each machine.
614
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
615
+ progress_bar.set_description("Steps")
616
+ global_step = 0
617
+
618
+ if train_unet and args.use_ema:
619
+ ema_unet = EMAModel(unet_.parameters())
620
+
621
+ for epoch in range(args.num_train_epochs):
622
+ model.train()
623
+ train_loss = 0.0
624
+ for step, batch in enumerate(train_dataloader):
625
+ with accelerator.accumulate(model):
626
+ # Convert images to latent space
627
+ latents = vae.encode(batch["pixel_values"]).latent_dist.sample().detach()
628
+ latents = latents * 0.18215
629
+
630
+ # Sample noise that we'll add to the latents
631
+ noise = torch.randn(latents.shape).to(latents.device)
632
+ bsz = latents.shape[0]
633
+ # Sample a random timestep for each image
634
+ timesteps = torch.randint(
635
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
636
+ ).long()
637
+
638
+ # Add noise to the latents according to the noise magnitude at each timestep
639
+ # (this is the forward diffusion process)
640
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
641
+
642
+ # Get the text embedding for conditioning
643
+ encoder_hidden_states = text_encoder_(batch["input_ids"])[0]
644
+
645
+ # Predict the noise residual
646
+ model_pred = unet_(noisy_latents, timesteps, encoder_hidden_states).sample
647
+
648
+ loss = F.mse_loss(model_pred, noise, reduction="none").mean([1, 2, 3]).mean()
649
+ if train_unet and compression_manager:
650
+ unet_inputs = {
651
+ "sample": noisy_latents,
652
+ "timestep": timesteps,
653
+ "encoder_hidden_states": encoder_hidden_states,
654
+ }
655
+ loss = compression_manager.callbacks.on_after_compute_loss(unet_inputs, model_pred, loss)
656
+
657
+ # Gather the losses across all processes for logging (if we use distributed training).
658
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
659
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
660
+
661
+ # Backpropagate
662
+ accelerator.backward(loss)
663
+
664
+ if train_unet:
665
+ if accelerator.sync_gradients:
666
+ accelerator.clip_grad_norm_(unet_.parameters(), args.max_grad_norm)
667
+ else:
668
+ # Zero out the gradients for all token embeddings except the newly added
669
+ # embeddings for the concept, as we only want to optimize the concept embeddings
670
+ if accelerator.num_processes > 1:
671
+ grads = text_encoder_.module.get_input_embeddings().weight.grad
672
+ else:
673
+ grads = text_encoder_.get_input_embeddings().weight.grad
674
+ # Get the index for tokens that we want to zero the grads for
675
+ index_grads_to_zero = torch.arange(len(tokenizer)) != placeholder_token_id
676
+ grads.data[index_grads_to_zero, :] = grads.data[index_grads_to_zero, :].fill_(0)
677
+
678
+ optimizer.step()
679
+ lr_scheduler.step()
680
+ optimizer.zero_grad()
681
+
682
+ # Checks if the accelerator has performed an optimization step behind the scenes
683
+ if accelerator.sync_gradients:
684
+ if train_unet and args.use_ema:
685
+ ema_unet.step(unet_.parameters())
686
+ progress_bar.update(1)
687
+ global_step += 1
688
+ accelerator.log({"train_loss": train_loss}, step=global_step)
689
+ train_loss = 0.0
690
+ if not train_unet and global_step % args.save_steps == 0:
691
+ save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
692
+ save_progress(text_encoder_, placeholder_token_id, accelerator, args, save_path)
693
+
694
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
695
+ progress_bar.set_postfix(**logs)
696
+ accelerator.log(logs, step=global_step)
697
+
698
+ if global_step >= args.max_train_steps:
699
+ break
700
+ accelerator.wait_for_everyone()
701
+
702
+ if train_unet and args.use_ema:
703
+ ema_unet.copy_to(unet_.parameters())
704
+
705
+ if not train_unet:
706
+ return text_encoder_
707
+
708
+ if not train_unet:
709
+ text_encoder = train_func(text_encoder)
710
+ else:
711
+ import copy
712
+
713
+ model = copy.deepcopy(unet)
714
+ confs = []
715
+ if args.do_quantization:
716
+ from neural_compressor import QuantizationAwareTrainingConfig
717
+
718
+ q_conf = QuantizationAwareTrainingConfig()
719
+ confs.append(q_conf)
720
+
721
+ if args.do_distillation:
722
+ teacher_model = copy.deepcopy(model)
723
+
724
+ def attention_fetcher(x):
725
+ return x.sample
726
+
727
+ layer_mappings = [
728
+ [
729
+ [
730
+ "conv_in",
731
+ ]
732
+ ],
733
+ [
734
+ [
735
+ "time_embedding",
736
+ ]
737
+ ],
738
+ [["down_blocks.0.attentions.0", attention_fetcher]],
739
+ [["down_blocks.0.attentions.1", attention_fetcher]],
740
+ [
741
+ [
742
+ "down_blocks.0.resnets.0",
743
+ ]
744
+ ],
745
+ [
746
+ [
747
+ "down_blocks.0.resnets.1",
748
+ ]
749
+ ],
750
+ [
751
+ [
752
+ "down_blocks.0.downsamplers.0",
753
+ ]
754
+ ],
755
+ [["down_blocks.1.attentions.0", attention_fetcher]],
756
+ [["down_blocks.1.attentions.1", attention_fetcher]],
757
+ [
758
+ [
759
+ "down_blocks.1.resnets.0",
760
+ ]
761
+ ],
762
+ [
763
+ [
764
+ "down_blocks.1.resnets.1",
765
+ ]
766
+ ],
767
+ [
768
+ [
769
+ "down_blocks.1.downsamplers.0",
770
+ ]
771
+ ],
772
+ [["down_blocks.2.attentions.0", attention_fetcher]],
773
+ [["down_blocks.2.attentions.1", attention_fetcher]],
774
+ [
775
+ [
776
+ "down_blocks.2.resnets.0",
777
+ ]
778
+ ],
779
+ [
780
+ [
781
+ "down_blocks.2.resnets.1",
782
+ ]
783
+ ],
784
+ [
785
+ [
786
+ "down_blocks.2.downsamplers.0",
787
+ ]
788
+ ],
789
+ [
790
+ [
791
+ "down_blocks.3.resnets.0",
792
+ ]
793
+ ],
794
+ [
795
+ [
796
+ "down_blocks.3.resnets.1",
797
+ ]
798
+ ],
799
+ [
800
+ [
801
+ "up_blocks.0.resnets.0",
802
+ ]
803
+ ],
804
+ [
805
+ [
806
+ "up_blocks.0.resnets.1",
807
+ ]
808
+ ],
809
+ [
810
+ [
811
+ "up_blocks.0.resnets.2",
812
+ ]
813
+ ],
814
+ [
815
+ [
816
+ "up_blocks.0.upsamplers.0",
817
+ ]
818
+ ],
819
+ [["up_blocks.1.attentions.0", attention_fetcher]],
820
+ [["up_blocks.1.attentions.1", attention_fetcher]],
821
+ [["up_blocks.1.attentions.2", attention_fetcher]],
822
+ [
823
+ [
824
+ "up_blocks.1.resnets.0",
825
+ ]
826
+ ],
827
+ [
828
+ [
829
+ "up_blocks.1.resnets.1",
830
+ ]
831
+ ],
832
+ [
833
+ [
834
+ "up_blocks.1.resnets.2",
835
+ ]
836
+ ],
837
+ [
838
+ [
839
+ "up_blocks.1.upsamplers.0",
840
+ ]
841
+ ],
842
+ [["up_blocks.2.attentions.0", attention_fetcher]],
843
+ [["up_blocks.2.attentions.1", attention_fetcher]],
844
+ [["up_blocks.2.attentions.2", attention_fetcher]],
845
+ [
846
+ [
847
+ "up_blocks.2.resnets.0",
848
+ ]
849
+ ],
850
+ [
851
+ [
852
+ "up_blocks.2.resnets.1",
853
+ ]
854
+ ],
855
+ [
856
+ [
857
+ "up_blocks.2.resnets.2",
858
+ ]
859
+ ],
860
+ [
861
+ [
862
+ "up_blocks.2.upsamplers.0",
863
+ ]
864
+ ],
865
+ [["up_blocks.3.attentions.0", attention_fetcher]],
866
+ [["up_blocks.3.attentions.1", attention_fetcher]],
867
+ [["up_blocks.3.attentions.2", attention_fetcher]],
868
+ [
869
+ [
870
+ "up_blocks.3.resnets.0",
871
+ ]
872
+ ],
873
+ [
874
+ [
875
+ "up_blocks.3.resnets.1",
876
+ ]
877
+ ],
878
+ [
879
+ [
880
+ "up_blocks.3.resnets.2",
881
+ ]
882
+ ],
883
+ [["mid_block.attentions.0", attention_fetcher]],
884
+ [
885
+ [
886
+ "mid_block.resnets.0",
887
+ ]
888
+ ],
889
+ [
890
+ [
891
+ "mid_block.resnets.1",
892
+ ]
893
+ ],
894
+ [
895
+ [
896
+ "conv_out",
897
+ ]
898
+ ],
899
+ ]
900
+ layer_names = [layer_mapping[0][0] for layer_mapping in layer_mappings]
901
+ if not set(layer_names).issubset([n[0] for n in model.named_modules()]):
902
+ raise ValueError(
903
+ "Provided model is not compatible with the default layer_mappings, "
904
+ 'please use the model fine-tuned from "CompVis/stable-diffusion-v1-4", '
905
+ "or modify the layer_mappings variable to fit your model."
906
+ f"\nDefault layer_mappings are as such:\n{layer_mappings}"
907
+ )
908
+ from neural_compressor.config import DistillationConfig, IntermediateLayersKnowledgeDistillationLossConfig
909
+
910
+ distillation_criterion = IntermediateLayersKnowledgeDistillationLossConfig(
911
+ layer_mappings=layer_mappings,
912
+ loss_types=["MSE"] * len(layer_mappings),
913
+ loss_weights=[1.0 / len(layer_mappings)] * len(layer_mappings),
914
+ add_origin_loss=True,
915
+ )
916
+ d_conf = DistillationConfig(teacher_model=teacher_model, criterion=distillation_criterion)
917
+ confs.append(d_conf)
918
+
919
+ from neural_compressor.training import prepare_compression
920
+
921
+ compression_manager = prepare_compression(model, confs)
922
+ compression_manager.callbacks.on_train_begin()
923
+ model = compression_manager.model
924
+ train_func(model)
925
+ compression_manager.callbacks.on_train_end()
926
+
927
+ # Save the resulting model and its corresponding configuration in the given directory
928
+ model.save(args.output_dir)
929
+
930
+ logger.info(f"Optimized model saved to: {args.output_dir}.")
931
+
932
+ # change to framework model for further use
933
+ model = model.model
934
+
935
+ # Create the pipeline using using the trained modules and save it.
936
+ templates = imagenet_style_templates_small if args.learnable_property == "style" else imagenet_templates_small
937
+ prompt = templates[0].format(args.placeholder_token)
938
+ if accelerator.is_main_process:
939
+ pipeline = StableDiffusionPipeline.from_pretrained(
940
+ args.pretrained_model_name_or_path,
941
+ text_encoder=accelerator.unwrap_model(text_encoder),
942
+ vae=vae,
943
+ unet=accelerator.unwrap_model(unet),
944
+ tokenizer=tokenizer,
945
+ )
946
+ pipeline.save_pretrained(args.output_dir)
947
+ pipeline = pipeline.to(unet.device)
948
+ baseline_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
949
+ baseline_model_images.save(
950
+ os.path.join(args.output_dir, "{}_baseline_model.png".format("_".join(prompt.split())))
951
+ )
952
+
953
+ if not train_unet:
954
+ # Also save the newly trained embeddings
955
+ save_path = os.path.join(args.output_dir, "learned_embeds.bin")
956
+ save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
957
+ else:
958
+ setattr(pipeline, "unet", accelerator.unwrap_model(model))
959
+ if args.do_quantization:
960
+ pipeline = pipeline.to(torch.device("cpu"))
961
+
962
+ optimized_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
963
+ optimized_model_images.save(
964
+ os.path.join(args.output_dir, "{}_optimized_model.png".format("_".join(prompt.split())))
965
+ )
966
+
967
+ if args.push_to_hub:
968
+ upload_folder(
969
+ repo_id=repo_id,
970
+ folder_path=args.output_dir,
971
+ commit_message="End of training",
972
+ ignore_patterns=["step_*", "epoch_*"],
973
+ )
974
+
975
+ accelerator.end_training()
976
+
977
+ if args.do_quantization and args.verify_loading:
978
+ # Load the model obtained after Intel Neural Compressor quantization
979
+ from neural_compressor.utils.pytorch import load
980
+
981
+ loaded_model = load(args.output_dir, model=unet)
982
+ loaded_model.eval()
983
+
984
+ setattr(pipeline, "unet", loaded_model)
985
+ if args.do_quantization:
986
+ pipeline = pipeline.to(torch.device("cpu"))
987
+
988
+ loaded_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
989
+ if loaded_model_images != optimized_model_images:
990
+ logger.info("The quantized model was not successfully loaded.")
991
+ else:
992
+ logger.info("The quantized model was successfully loaded.")
993
+
994
+
995
+ if __name__ == "__main__":
996
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/README.md ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # IP Adapter Training Example
2
+
3
+ [IP Adapter](https://huggingface.co/papers/2308.06721) is a novel approach designed to enhance text-to-image models such as Stable Diffusion by enabling them to generate images based on image prompts rather than text prompts alone. Unlike traditional methods that rely solely on complex text prompts, IP Adapter introduces the concept of using image prompts, leveraging the idea that "an image is worth a thousand words." By decoupling cross-attention layers for text and image features, IP Adapter effectively integrates image prompts into the generation process without the need for extensive fine-tuning or large computing resources.
4
+
5
+ ## Training locally with PyTorch
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
+
15
+ ```bash
16
+ git clone https://github.com/huggingface/diffusers
17
+ cd diffusers
18
+ pip install -e .
19
+ ```
20
+
21
+ Then cd in the example folder and run
22
+
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
28
+
29
+ ```bash
30
+ accelerate config
31
+ ```
32
+
33
+ Or for a default accelerate configuration without answering questions about your environment
34
+
35
+ ```bash
36
+ accelerate config default
37
+ ```
38
+
39
+ Or if your environment doesn't support an interactive shell e.g. a notebook
40
+
41
+ ```python
42
+ from accelerate.utils import write_basic_config
43
+ write_basic_config()
44
+ ```
45
+
46
+ Certainly! Below is the documentation in pure Markdown format:
47
+
48
+ ### Accelerate Launch Command Documentation
49
+
50
+ #### Description:
51
+ The Accelerate launch command is used to train a model using multiple GPUs and mixed precision training. It launches the training script `tutorial_train_ip-adapter.py` with specified parameters and configurations.
52
+
53
+ #### Usage Example:
54
+
55
+ ```
56
+ accelerate launch --mixed_precision "fp16" \
57
+ tutorial_train_ip-adapter.py \
58
+ --pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5/" \
59
+ --image_encoder_path="{image_encoder_path}" \
60
+ --data_json_file="{data.json}" \
61
+ --data_root_path="{image_path}" \
62
+ --mixed_precision="fp16" \
63
+ --resolution=512 \
64
+ --train_batch_size=8 \
65
+ --dataloader_num_workers=4 \
66
+ --learning_rate=1e-04 \
67
+ --weight_decay=0.01 \
68
+ --output_dir="{output_dir}" \
69
+ --save_steps=10000
70
+ ```
71
+
72
+ ### Multi-GPU Script:
73
+ ```
74
+ accelerate launch --num_processes 8 --multi_gpu --mixed_precision "fp16" \
75
+ tutorial_train_ip-adapter.py \
76
+ --pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5/" \
77
+ --image_encoder_path="{image_encoder_path}" \
78
+ --data_json_file="{data.json}" \
79
+ --data_root_path="{image_path}" \
80
+ --mixed_precision="fp16" \
81
+ --resolution=512 \
82
+ --train_batch_size=8 \
83
+ --dataloader_num_workers=4 \
84
+ --learning_rate=1e-04 \
85
+ --weight_decay=0.01 \
86
+ --output_dir="{output_dir}" \
87
+ --save_steps=10000
88
+ ```
89
+
90
+ #### Parameters:
91
+ - `--num_processes`: Number of processes to launch for distributed training (in this example, 8 processes).
92
+ - `--multi_gpu`: Flag indicating the usage of multiple GPUs for training.
93
+ - `--mixed_precision "fp16"`: Enables mixed precision training with 16-bit floating-point precision.
94
+ - `tutorial_train_ip-adapter.py`: Name of the training script to be executed.
95
+ - `--pretrained_model_name_or_path`: Path or identifier for a pretrained model.
96
+ - `--image_encoder_path`: Path to the CLIP image encoder.
97
+ - `--data_json_file`: Path to the training data in JSON format.
98
+ - `--data_root_path`: Root path where training images are located.
99
+ - `--resolution`: Resolution of input images (512x512 in this example).
100
+ - `--train_batch_size`: Batch size for training data (8 in this example).
101
+ - `--dataloader_num_workers`: Number of subprocesses for data loading (4 in this example).
102
+ - `--learning_rate`: Learning rate for training (1e-04 in this example).
103
+ - `--weight_decay`: Weight decay for regularization (0.01 in this example).
104
+ - `--output_dir`: Directory to save model checkpoints and predictions.
105
+ - `--save_steps`: Frequency of saving checkpoints during training (10000 in this example).
106
+
107
+ ### Inference
108
+
109
+ #### Description:
110
+ The provided inference code is used to load a trained model checkpoint and extract the components related to image projection and IP (Image Processing) adapter. These components are then saved into a binary file for later use in inference.
111
+
112
+ #### Usage Example:
113
+ ```python
114
+ from safetensors.torch import load_file, save_file
115
+
116
+ # Load the trained model checkpoint in safetensors format
117
+ ckpt = "checkpoint-50000/pytorch_model.safetensors"
118
+ sd = load_file(ckpt) # Using safetensors load function
119
+
120
+ # Extract image projection and IP adapter components
121
+ image_proj_sd = {}
122
+ ip_sd = {}
123
+
124
+ for k in sd:
125
+ if k.startswith("unet"):
126
+ pass # Skip unet-related keys
127
+ elif k.startswith("image_proj_model"):
128
+ image_proj_sd[k.replace("image_proj_model.", "")] = sd[k]
129
+ elif k.startswith("adapter_modules"):
130
+ ip_sd[k.replace("adapter_modules.", "")] = sd[k]
131
+
132
+ # Save the components into separate safetensors files
133
+ save_file(image_proj_sd, "image_proj.safetensors")
134
+ save_file(ip_sd, "ip_adapter.safetensors")
135
+ ```
136
+
137
+ ### Sample Inference Script using the CLIP Model
138
+
139
+ ```python
140
+
141
+ import torch
142
+ from safetensors.torch import load_file
143
+ from transformers import CLIPProcessor, CLIPModel # Using the Hugging Face CLIP model
144
+
145
+ # Load model components from safetensors
146
+ image_proj_ckpt = "image_proj.safetensors"
147
+ ip_adapter_ckpt = "ip_adapter.safetensors"
148
+
149
+ # Load the saved weights
150
+ image_proj_sd = load_file(image_proj_ckpt)
151
+ ip_adapter_sd = load_file(ip_adapter_ckpt)
152
+
153
+ # Define the model Parameters
154
+ class ImageProjectionModel(torch.nn.Module):
155
+ def __init__(self, input_dim=768, output_dim=512): # CLIP's default embedding size is 768
156
+ super().__init__()
157
+ self.model = torch.nn.Linear(input_dim, output_dim)
158
+
159
+ def forward(self, x):
160
+ return self.model(x)
161
+
162
+ class IPAdapterModel(torch.nn.Module):
163
+ def __init__(self, input_dim=512, output_dim=10): # Example for 10 classes
164
+ super().__init__()
165
+ self.model = torch.nn.Linear(input_dim, output_dim)
166
+
167
+ def forward(self, x):
168
+ return self.model(x)
169
+
170
+ # Initialize models
171
+ image_proj_model = ImageProjectionModel()
172
+ ip_adapter_model = IPAdapterModel()
173
+
174
+ # Load weights into models
175
+ image_proj_model.load_state_dict(image_proj_sd)
176
+ ip_adapter_model.load_state_dict(ip_adapter_sd)
177
+
178
+ # Set models to evaluation mode
179
+ image_proj_model.eval()
180
+ ip_adapter_model.eval()
181
+
182
+ #Inference pipeline
183
+ def inference(image_tensor):
184
+ """
185
+ Run inference using the loaded models.
186
+
187
+ Args:
188
+ image_tensor: Preprocessed image tensor from CLIPProcessor
189
+
190
+ Returns:
191
+ Final inference results
192
+ """
193
+ with torch.no_grad():
194
+ # Step 1: Project the image features
195
+ image_proj = image_proj_model(image_tensor)
196
+
197
+ # Step 2: Pass the projected features through the IP Adapter
198
+ result = ip_adapter_model(image_proj)
199
+
200
+ return result
201
+
202
+ # Using CLIP for image preprocessing
203
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
204
+ clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
205
+
206
+ #Image file path
207
+ image_path = "path/to/image.jpg"
208
+
209
+ # Preprocess the image
210
+ inputs = processor(images=image_path, return_tensors="pt")
211
+ image_features = clip_model.get_image_features(inputs["pixel_values"])
212
+
213
+ # Normalize the image features as per CLIP's recommendations
214
+ image_features = image_features / image_features.norm(dim=-1, keepdim=True)
215
+
216
+ # Run inference
217
+ output = inference(image_features)
218
+ print("Inference output:", output)
219
+ ```
220
+
221
+ #### Parameters:
222
+ - `ckpt`: Path to the trained model checkpoint file.
223
+ - `map_location="cpu"`: Specifies that the model should be loaded onto the CPU.
224
+ - `image_proj_sd`: Dictionary to store the components related to image projection.
225
+ - `ip_sd`: Dictionary to store the components related to the IP adapter.
226
+ - `"unet"`, `"image_proj_model"`, `"adapter_modules"`: Prefixes indicating components of the model.
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ accelerate
2
+ torchvision
3
+ transformers>=4.25.1
4
+ ip_adapter
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from accelerate import Accelerator
12
+ from accelerate.utils import ProjectConfiguration
13
+ from ip_adapter.attention_processor_faceid import LoRAAttnProcessor, LoRAIPAttnProcessor
14
+ from ip_adapter.ip_adapter_faceid import MLPProjModel
15
+ from PIL import Image
16
+ from torchvision import transforms
17
+ from transformers import CLIPTextModel, CLIPTokenizer
18
+
19
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
20
+
21
+
22
+ # Dataset
23
+ class MyDataset(torch.utils.data.Dataset):
24
+ def __init__(
25
+ self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
26
+ ):
27
+ super().__init__()
28
+
29
+ self.tokenizer = tokenizer
30
+ self.size = size
31
+ self.i_drop_rate = i_drop_rate
32
+ self.t_drop_rate = t_drop_rate
33
+ self.ti_drop_rate = ti_drop_rate
34
+ self.image_root_path = image_root_path
35
+
36
+ self.data = json.load(
37
+ open(json_file)
38
+ ) # list of dict: [{"image_file": "1.png", "id_embed_file": "faceid.bin"}]
39
+
40
+ self.transform = transforms.Compose(
41
+ [
42
+ transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
43
+ transforms.CenterCrop(self.size),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize([0.5], [0.5]),
46
+ ]
47
+ )
48
+
49
+ def __getitem__(self, idx):
50
+ item = self.data[idx]
51
+ text = item["text"]
52
+ image_file = item["image_file"]
53
+
54
+ # read image
55
+ raw_image = Image.open(os.path.join(self.image_root_path, image_file))
56
+ image = self.transform(raw_image.convert("RGB"))
57
+
58
+ face_id_embed = torch.load(item["id_embed_file"], map_location="cpu")
59
+ face_id_embed = torch.from_numpy(face_id_embed)
60
+
61
+ # drop
62
+ drop_image_embed = 0
63
+ rand_num = random.random()
64
+ if rand_num < self.i_drop_rate:
65
+ drop_image_embed = 1
66
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate):
67
+ text = ""
68
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
69
+ text = ""
70
+ drop_image_embed = 1
71
+ if drop_image_embed:
72
+ face_id_embed = torch.zeros_like(face_id_embed)
73
+ # get text and tokenize
74
+ text_input_ids = self.tokenizer(
75
+ text,
76
+ max_length=self.tokenizer.model_max_length,
77
+ padding="max_length",
78
+ truncation=True,
79
+ return_tensors="pt",
80
+ ).input_ids
81
+
82
+ return {
83
+ "image": image,
84
+ "text_input_ids": text_input_ids,
85
+ "face_id_embed": face_id_embed,
86
+ "drop_image_embed": drop_image_embed,
87
+ }
88
+
89
+ def __len__(self):
90
+ return len(self.data)
91
+
92
+
93
+ def collate_fn(data):
94
+ images = torch.stack([example["image"] for example in data])
95
+ text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
96
+ face_id_embed = torch.stack([example["face_id_embed"] for example in data])
97
+ drop_image_embeds = [example["drop_image_embed"] for example in data]
98
+
99
+ return {
100
+ "images": images,
101
+ "text_input_ids": text_input_ids,
102
+ "face_id_embed": face_id_embed,
103
+ "drop_image_embeds": drop_image_embeds,
104
+ }
105
+
106
+
107
+ class IPAdapter(torch.nn.Module):
108
+ """IP-Adapter"""
109
+
110
+ def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
111
+ super().__init__()
112
+ self.unet = unet
113
+ self.image_proj_model = image_proj_model
114
+ self.adapter_modules = adapter_modules
115
+
116
+ if ckpt_path is not None:
117
+ self.load_from_checkpoint(ckpt_path)
118
+
119
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
120
+ ip_tokens = self.image_proj_model(image_embeds)
121
+ encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
122
+ # Predict the noise residual
123
+ noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
124
+ return noise_pred
125
+
126
+ def load_from_checkpoint(self, ckpt_path: str):
127
+ # Calculate original checksums
128
+ orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
129
+ orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
130
+
131
+ state_dict = torch.load(ckpt_path, map_location="cpu")
132
+
133
+ # Load state dict for image_proj_model and adapter_modules
134
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
135
+ self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
136
+
137
+ # Calculate new checksums
138
+ new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
139
+ new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
140
+
141
+ # Verify if the weights have changed
142
+ assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
143
+ assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
144
+
145
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
146
+
147
+
148
+ def parse_args():
149
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
150
+ parser.add_argument(
151
+ "--pretrained_model_name_or_path",
152
+ type=str,
153
+ default=None,
154
+ required=True,
155
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
156
+ )
157
+ parser.add_argument(
158
+ "--pretrained_ip_adapter_path",
159
+ type=str,
160
+ default=None,
161
+ help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
162
+ )
163
+ parser.add_argument(
164
+ "--data_json_file",
165
+ type=str,
166
+ default=None,
167
+ required=True,
168
+ help="Training data",
169
+ )
170
+ parser.add_argument(
171
+ "--data_root_path",
172
+ type=str,
173
+ default="",
174
+ required=True,
175
+ help="Training data root path",
176
+ )
177
+ parser.add_argument(
178
+ "--image_encoder_path",
179
+ type=str,
180
+ default=None,
181
+ required=True,
182
+ help="Path to CLIP image encoder",
183
+ )
184
+ parser.add_argument(
185
+ "--output_dir",
186
+ type=str,
187
+ default="sd-ip_adapter",
188
+ help="The output directory where the model predictions and checkpoints will be written.",
189
+ )
190
+ parser.add_argument(
191
+ "--logging_dir",
192
+ type=str,
193
+ default="logs",
194
+ help=(
195
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
196
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
197
+ ),
198
+ )
199
+ parser.add_argument(
200
+ "--resolution",
201
+ type=int,
202
+ default=512,
203
+ help=("The resolution for input images"),
204
+ )
205
+ parser.add_argument(
206
+ "--learning_rate",
207
+ type=float,
208
+ default=1e-4,
209
+ help="Learning rate to use.",
210
+ )
211
+ parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
212
+ parser.add_argument("--num_train_epochs", type=int, default=100)
213
+ parser.add_argument(
214
+ "--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
215
+ )
216
+ parser.add_argument(
217
+ "--dataloader_num_workers",
218
+ type=int,
219
+ default=0,
220
+ help=(
221
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
222
+ ),
223
+ )
224
+ parser.add_argument(
225
+ "--save_steps",
226
+ type=int,
227
+ default=2000,
228
+ help=("Save a checkpoint of the training state every X updates"),
229
+ )
230
+ parser.add_argument(
231
+ "--mixed_precision",
232
+ type=str,
233
+ default=None,
234
+ choices=["no", "fp16", "bf16"],
235
+ help=(
236
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
237
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
238
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
239
+ ),
240
+ )
241
+ parser.add_argument(
242
+ "--report_to",
243
+ type=str,
244
+ default="tensorboard",
245
+ help=(
246
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
247
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
248
+ ),
249
+ )
250
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
251
+
252
+ args = parser.parse_args()
253
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
254
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
255
+ args.local_rank = env_local_rank
256
+
257
+ return args
258
+
259
+
260
+ def main():
261
+ args = parse_args()
262
+ logging_dir = Path(args.output_dir, args.logging_dir)
263
+
264
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
265
+
266
+ accelerator = Accelerator(
267
+ mixed_precision=args.mixed_precision,
268
+ log_with=args.report_to,
269
+ project_config=accelerator_project_config,
270
+ )
271
+
272
+ if accelerator.is_main_process:
273
+ if args.output_dir is not None:
274
+ os.makedirs(args.output_dir, exist_ok=True)
275
+
276
+ # Load scheduler, tokenizer and models.
277
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
278
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
279
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
280
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
281
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
282
+ # image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
283
+ # freeze parameters of models to save more memory
284
+ unet.requires_grad_(False)
285
+ vae.requires_grad_(False)
286
+ text_encoder.requires_grad_(False)
287
+ # image_encoder.requires_grad_(False)
288
+
289
+ # ip-adapter
290
+ image_proj_model = MLPProjModel(
291
+ cross_attention_dim=unet.config.cross_attention_dim,
292
+ id_embeddings_dim=512,
293
+ num_tokens=4,
294
+ )
295
+ # init adapter modules
296
+ lora_rank = 128
297
+ attn_procs = {}
298
+ unet_sd = unet.state_dict()
299
+ for name in unet.attn_processors.keys():
300
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
301
+ if name.startswith("mid_block"):
302
+ hidden_size = unet.config.block_out_channels[-1]
303
+ elif name.startswith("up_blocks"):
304
+ block_id = int(name[len("up_blocks.")])
305
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
306
+ elif name.startswith("down_blocks"):
307
+ block_id = int(name[len("down_blocks.")])
308
+ hidden_size = unet.config.block_out_channels[block_id]
309
+ if cross_attention_dim is None:
310
+ attn_procs[name] = LoRAAttnProcessor(
311
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank
312
+ )
313
+ else:
314
+ layer_name = name.split(".processor")[0]
315
+ weights = {
316
+ "to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
317
+ "to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
318
+ }
319
+ attn_procs[name] = LoRAIPAttnProcessor(
320
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank
321
+ )
322
+ attn_procs[name].load_state_dict(weights, strict=False)
323
+ unet.set_attn_processor(attn_procs)
324
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
325
+
326
+ ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
327
+
328
+ weight_dtype = torch.float32
329
+ if accelerator.mixed_precision == "fp16":
330
+ weight_dtype = torch.float16
331
+ elif accelerator.mixed_precision == "bf16":
332
+ weight_dtype = torch.bfloat16
333
+ # unet.to(accelerator.device, dtype=weight_dtype)
334
+ vae.to(accelerator.device, dtype=weight_dtype)
335
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
336
+ # image_encoder.to(accelerator.device, dtype=weight_dtype)
337
+
338
+ # optimizer
339
+ params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
340
+ optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
341
+
342
+ # dataloader
343
+ train_dataset = MyDataset(
344
+ args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
345
+ )
346
+ train_dataloader = torch.utils.data.DataLoader(
347
+ train_dataset,
348
+ shuffle=True,
349
+ collate_fn=collate_fn,
350
+ batch_size=args.train_batch_size,
351
+ num_workers=args.dataloader_num_workers,
352
+ )
353
+
354
+ # Prepare everything with our `accelerator`.
355
+ ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
356
+
357
+ global_step = 0
358
+ for epoch in range(0, args.num_train_epochs):
359
+ begin = time.perf_counter()
360
+ for step, batch in enumerate(train_dataloader):
361
+ load_data_time = time.perf_counter() - begin
362
+ with accelerator.accumulate(ip_adapter):
363
+ # Convert images to latent space
364
+ with torch.no_grad():
365
+ latents = vae.encode(
366
+ batch["images"].to(accelerator.device, dtype=weight_dtype)
367
+ ).latent_dist.sample()
368
+ latents = latents * vae.config.scaling_factor
369
+
370
+ # Sample noise that we'll add to the latents
371
+ noise = torch.randn_like(latents)
372
+ bsz = latents.shape[0]
373
+ # Sample a random timestep for each image
374
+ timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
375
+ timesteps = timesteps.long()
376
+
377
+ # Add noise to the latents according to the noise magnitude at each timestep
378
+ # (this is the forward diffusion process)
379
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
380
+
381
+ image_embeds = batch["face_id_embed"].to(accelerator.device, dtype=weight_dtype)
382
+
383
+ with torch.no_grad():
384
+ encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
385
+
386
+ noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
387
+
388
+ loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
389
+
390
+ # Gather the losses across all processes for logging (if we use distributed training).
391
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
392
+
393
+ # Backpropagate
394
+ accelerator.backward(loss)
395
+ optimizer.step()
396
+ optimizer.zero_grad()
397
+
398
+ if accelerator.is_main_process:
399
+ print(
400
+ "Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
401
+ epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
402
+ )
403
+ )
404
+
405
+ global_step += 1
406
+
407
+ if global_step % args.save_steps == 0:
408
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
409
+ accelerator.save_state(save_path)
410
+
411
+ begin = time.perf_counter()
412
+
413
+
414
+ if __name__ == "__main__":
415
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from accelerate import Accelerator
12
+ from accelerate.utils import ProjectConfiguration
13
+ from ip_adapter.ip_adapter import ImageProjModel
14
+ from ip_adapter.utils import is_torch2_available
15
+ from PIL import Image
16
+ from torchvision import transforms
17
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
18
+
19
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
20
+
21
+
22
+ if is_torch2_available():
23
+ from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
24
+ from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
25
+ else:
26
+ from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
27
+
28
+
29
+ # Dataset
30
+ class MyDataset(torch.utils.data.Dataset):
31
+ def __init__(
32
+ self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
33
+ ):
34
+ super().__init__()
35
+
36
+ self.tokenizer = tokenizer
37
+ self.size = size
38
+ self.i_drop_rate = i_drop_rate
39
+ self.t_drop_rate = t_drop_rate
40
+ self.ti_drop_rate = ti_drop_rate
41
+ self.image_root_path = image_root_path
42
+
43
+ self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
44
+
45
+ self.transform = transforms.Compose(
46
+ [
47
+ transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
48
+ transforms.CenterCrop(self.size),
49
+ transforms.ToTensor(),
50
+ transforms.Normalize([0.5], [0.5]),
51
+ ]
52
+ )
53
+ self.clip_image_processor = CLIPImageProcessor()
54
+
55
+ def __getitem__(self, idx):
56
+ item = self.data[idx]
57
+ text = item["text"]
58
+ image_file = item["image_file"]
59
+
60
+ # read image
61
+ raw_image = Image.open(os.path.join(self.image_root_path, image_file))
62
+ image = self.transform(raw_image.convert("RGB"))
63
+ clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
64
+
65
+ # drop
66
+ drop_image_embed = 0
67
+ rand_num = random.random()
68
+ if rand_num < self.i_drop_rate:
69
+ drop_image_embed = 1
70
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate):
71
+ text = ""
72
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
73
+ text = ""
74
+ drop_image_embed = 1
75
+ # get text and tokenize
76
+ text_input_ids = self.tokenizer(
77
+ text,
78
+ max_length=self.tokenizer.model_max_length,
79
+ padding="max_length",
80
+ truncation=True,
81
+ return_tensors="pt",
82
+ ).input_ids
83
+
84
+ return {
85
+ "image": image,
86
+ "text_input_ids": text_input_ids,
87
+ "clip_image": clip_image,
88
+ "drop_image_embed": drop_image_embed,
89
+ }
90
+
91
+ def __len__(self):
92
+ return len(self.data)
93
+
94
+
95
+ def collate_fn(data):
96
+ images = torch.stack([example["image"] for example in data])
97
+ text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
98
+ clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
99
+ drop_image_embeds = [example["drop_image_embed"] for example in data]
100
+
101
+ return {
102
+ "images": images,
103
+ "text_input_ids": text_input_ids,
104
+ "clip_images": clip_images,
105
+ "drop_image_embeds": drop_image_embeds,
106
+ }
107
+
108
+
109
+ class IPAdapter(torch.nn.Module):
110
+ """IP-Adapter"""
111
+
112
+ def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
113
+ super().__init__()
114
+ self.unet = unet
115
+ self.image_proj_model = image_proj_model
116
+ self.adapter_modules = adapter_modules
117
+
118
+ if ckpt_path is not None:
119
+ self.load_from_checkpoint(ckpt_path)
120
+
121
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
122
+ ip_tokens = self.image_proj_model(image_embeds)
123
+ encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
124
+ # Predict the noise residual
125
+ noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
126
+ return noise_pred
127
+
128
+ def load_from_checkpoint(self, ckpt_path: str):
129
+ # Calculate original checksums
130
+ orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
131
+ orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
132
+
133
+ state_dict = torch.load(ckpt_path, map_location="cpu")
134
+
135
+ # Load state dict for image_proj_model and adapter_modules
136
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
137
+ self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
138
+
139
+ # Calculate new checksums
140
+ new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
141
+ new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
142
+
143
+ # Verify if the weights have changed
144
+ assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
145
+ assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
146
+
147
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
148
+
149
+
150
+ def parse_args():
151
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
152
+ parser.add_argument(
153
+ "--pretrained_model_name_or_path",
154
+ type=str,
155
+ default=None,
156
+ required=True,
157
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
158
+ )
159
+ parser.add_argument(
160
+ "--pretrained_ip_adapter_path",
161
+ type=str,
162
+ default=None,
163
+ help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
164
+ )
165
+ parser.add_argument(
166
+ "--data_json_file",
167
+ type=str,
168
+ default=None,
169
+ required=True,
170
+ help="Training data",
171
+ )
172
+ parser.add_argument(
173
+ "--data_root_path",
174
+ type=str,
175
+ default="",
176
+ required=True,
177
+ help="Training data root path",
178
+ )
179
+ parser.add_argument(
180
+ "--image_encoder_path",
181
+ type=str,
182
+ default=None,
183
+ required=True,
184
+ help="Path to CLIP image encoder",
185
+ )
186
+ parser.add_argument(
187
+ "--output_dir",
188
+ type=str,
189
+ default="sd-ip_adapter",
190
+ help="The output directory where the model predictions and checkpoints will be written.",
191
+ )
192
+ parser.add_argument(
193
+ "--logging_dir",
194
+ type=str,
195
+ default="logs",
196
+ help=(
197
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
198
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
199
+ ),
200
+ )
201
+ parser.add_argument(
202
+ "--resolution",
203
+ type=int,
204
+ default=512,
205
+ help=("The resolution for input images"),
206
+ )
207
+ parser.add_argument(
208
+ "--learning_rate",
209
+ type=float,
210
+ default=1e-4,
211
+ help="Learning rate to use.",
212
+ )
213
+ parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
214
+ parser.add_argument("--num_train_epochs", type=int, default=100)
215
+ parser.add_argument(
216
+ "--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
217
+ )
218
+ parser.add_argument(
219
+ "--dataloader_num_workers",
220
+ type=int,
221
+ default=0,
222
+ help=(
223
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
224
+ ),
225
+ )
226
+ parser.add_argument(
227
+ "--save_steps",
228
+ type=int,
229
+ default=2000,
230
+ help=("Save a checkpoint of the training state every X updates"),
231
+ )
232
+ parser.add_argument(
233
+ "--mixed_precision",
234
+ type=str,
235
+ default=None,
236
+ choices=["no", "fp16", "bf16"],
237
+ help=(
238
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
239
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
240
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
241
+ ),
242
+ )
243
+ parser.add_argument(
244
+ "--report_to",
245
+ type=str,
246
+ default="tensorboard",
247
+ help=(
248
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
249
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
250
+ ),
251
+ )
252
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
253
+
254
+ args = parser.parse_args()
255
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
256
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
257
+ args.local_rank = env_local_rank
258
+
259
+ return args
260
+
261
+
262
+ def main():
263
+ args = parse_args()
264
+ logging_dir = Path(args.output_dir, args.logging_dir)
265
+
266
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
267
+
268
+ accelerator = Accelerator(
269
+ mixed_precision=args.mixed_precision,
270
+ log_with=args.report_to,
271
+ project_config=accelerator_project_config,
272
+ )
273
+
274
+ if accelerator.is_main_process:
275
+ if args.output_dir is not None:
276
+ os.makedirs(args.output_dir, exist_ok=True)
277
+
278
+ # Load scheduler, tokenizer and models.
279
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
280
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
281
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
282
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
283
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
284
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
285
+ # freeze parameters of models to save more memory
286
+ unet.requires_grad_(False)
287
+ vae.requires_grad_(False)
288
+ text_encoder.requires_grad_(False)
289
+ image_encoder.requires_grad_(False)
290
+
291
+ # ip-adapter
292
+ image_proj_model = ImageProjModel(
293
+ cross_attention_dim=unet.config.cross_attention_dim,
294
+ clip_embeddings_dim=image_encoder.config.projection_dim,
295
+ clip_extra_context_tokens=4,
296
+ )
297
+ # init adapter modules
298
+ attn_procs = {}
299
+ unet_sd = unet.state_dict()
300
+ for name in unet.attn_processors.keys():
301
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
302
+ if name.startswith("mid_block"):
303
+ hidden_size = unet.config.block_out_channels[-1]
304
+ elif name.startswith("up_blocks"):
305
+ block_id = int(name[len("up_blocks.")])
306
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
307
+ elif name.startswith("down_blocks"):
308
+ block_id = int(name[len("down_blocks.")])
309
+ hidden_size = unet.config.block_out_channels[block_id]
310
+ if cross_attention_dim is None:
311
+ attn_procs[name] = AttnProcessor()
312
+ else:
313
+ layer_name = name.split(".processor")[0]
314
+ weights = {
315
+ "to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
316
+ "to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
317
+ }
318
+ attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
319
+ attn_procs[name].load_state_dict(weights)
320
+ unet.set_attn_processor(attn_procs)
321
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
322
+
323
+ ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
324
+
325
+ weight_dtype = torch.float32
326
+ if accelerator.mixed_precision == "fp16":
327
+ weight_dtype = torch.float16
328
+ elif accelerator.mixed_precision == "bf16":
329
+ weight_dtype = torch.bfloat16
330
+ # unet.to(accelerator.device, dtype=weight_dtype)
331
+ vae.to(accelerator.device, dtype=weight_dtype)
332
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
333
+ image_encoder.to(accelerator.device, dtype=weight_dtype)
334
+
335
+ # optimizer
336
+ params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
337
+ optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
338
+
339
+ # dataloader
340
+ train_dataset = MyDataset(
341
+ args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
342
+ )
343
+ train_dataloader = torch.utils.data.DataLoader(
344
+ train_dataset,
345
+ shuffle=True,
346
+ collate_fn=collate_fn,
347
+ batch_size=args.train_batch_size,
348
+ num_workers=args.dataloader_num_workers,
349
+ )
350
+
351
+ # Prepare everything with our `accelerator`.
352
+ ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
353
+
354
+ global_step = 0
355
+ for epoch in range(0, args.num_train_epochs):
356
+ begin = time.perf_counter()
357
+ for step, batch in enumerate(train_dataloader):
358
+ load_data_time = time.perf_counter() - begin
359
+ with accelerator.accumulate(ip_adapter):
360
+ # Convert images to latent space
361
+ with torch.no_grad():
362
+ latents = vae.encode(
363
+ batch["images"].to(accelerator.device, dtype=weight_dtype)
364
+ ).latent_dist.sample()
365
+ latents = latents * vae.config.scaling_factor
366
+
367
+ # Sample noise that we'll add to the latents
368
+ noise = torch.randn_like(latents)
369
+ bsz = latents.shape[0]
370
+ # Sample a random timestep for each image
371
+ timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
372
+ timesteps = timesteps.long()
373
+
374
+ # Add noise to the latents according to the noise magnitude at each timestep
375
+ # (this is the forward diffusion process)
376
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
377
+
378
+ with torch.no_grad():
379
+ image_embeds = image_encoder(
380
+ batch["clip_images"].to(accelerator.device, dtype=weight_dtype)
381
+ ).image_embeds
382
+ image_embeds_ = []
383
+ for image_embed, drop_image_embed in zip(image_embeds, batch["drop_image_embeds"]):
384
+ if drop_image_embed == 1:
385
+ image_embeds_.append(torch.zeros_like(image_embed))
386
+ else:
387
+ image_embeds_.append(image_embed)
388
+ image_embeds = torch.stack(image_embeds_)
389
+
390
+ with torch.no_grad():
391
+ encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
392
+
393
+ noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
394
+
395
+ loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
396
+
397
+ # Gather the losses across all processes for logging (if we use distributed training).
398
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
399
+
400
+ # Backpropagate
401
+ accelerator.backward(loss)
402
+ optimizer.step()
403
+ optimizer.zero_grad()
404
+
405
+ if accelerator.is_main_process:
406
+ print(
407
+ "Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
408
+ epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
409
+ )
410
+ )
411
+
412
+ global_step += 1
413
+
414
+ if global_step % args.save_steps == 0:
415
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
416
+ accelerator.save_state(save_path)
417
+
418
+ begin = time.perf_counter()
419
+
420
+
421
+ if __name__ == "__main__":
422
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from accelerate import Accelerator
12
+ from accelerate.utils import ProjectConfiguration
13
+ from ip_adapter.resampler import Resampler
14
+ from ip_adapter.utils import is_torch2_available
15
+ from PIL import Image
16
+ from torchvision import transforms
17
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
18
+
19
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
20
+
21
+
22
+ if is_torch2_available():
23
+ from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
24
+ from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
25
+ else:
26
+ from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
27
+
28
+
29
+ # Dataset
30
+ class MyDataset(torch.utils.data.Dataset):
31
+ def __init__(
32
+ self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
33
+ ):
34
+ super().__init__()
35
+
36
+ self.tokenizer = tokenizer
37
+ self.size = size
38
+ self.i_drop_rate = i_drop_rate
39
+ self.t_drop_rate = t_drop_rate
40
+ self.ti_drop_rate = ti_drop_rate
41
+ self.image_root_path = image_root_path
42
+
43
+ self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
44
+
45
+ self.transform = transforms.Compose(
46
+ [
47
+ transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
48
+ transforms.CenterCrop(self.size),
49
+ transforms.ToTensor(),
50
+ transforms.Normalize([0.5], [0.5]),
51
+ ]
52
+ )
53
+ self.clip_image_processor = CLIPImageProcessor()
54
+
55
+ def __getitem__(self, idx):
56
+ item = self.data[idx]
57
+ text = item["text"]
58
+ image_file = item["image_file"]
59
+
60
+ # read image
61
+ raw_image = Image.open(os.path.join(self.image_root_path, image_file))
62
+ image = self.transform(raw_image.convert("RGB"))
63
+ clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
64
+
65
+ # drop
66
+ drop_image_embed = 0
67
+ rand_num = random.random()
68
+ if rand_num < self.i_drop_rate:
69
+ drop_image_embed = 1
70
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate):
71
+ text = ""
72
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
73
+ text = ""
74
+ drop_image_embed = 1
75
+ # get text and tokenize
76
+ text_input_ids = self.tokenizer(
77
+ text,
78
+ max_length=self.tokenizer.model_max_length,
79
+ padding="max_length",
80
+ truncation=True,
81
+ return_tensors="pt",
82
+ ).input_ids
83
+
84
+ return {
85
+ "image": image,
86
+ "text_input_ids": text_input_ids,
87
+ "clip_image": clip_image,
88
+ "drop_image_embed": drop_image_embed,
89
+ }
90
+
91
+ def __len__(self):
92
+ return len(self.data)
93
+
94
+
95
+ def collate_fn(data):
96
+ images = torch.stack([example["image"] for example in data])
97
+ text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
98
+ clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
99
+ drop_image_embeds = [example["drop_image_embed"] for example in data]
100
+
101
+ return {
102
+ "images": images,
103
+ "text_input_ids": text_input_ids,
104
+ "clip_images": clip_images,
105
+ "drop_image_embeds": drop_image_embeds,
106
+ }
107
+
108
+
109
+ class IPAdapter(torch.nn.Module):
110
+ """IP-Adapter"""
111
+
112
+ def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
113
+ super().__init__()
114
+ self.unet = unet
115
+ self.image_proj_model = image_proj_model
116
+ self.adapter_modules = adapter_modules
117
+
118
+ if ckpt_path is not None:
119
+ self.load_from_checkpoint(ckpt_path)
120
+
121
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
122
+ ip_tokens = self.image_proj_model(image_embeds)
123
+ encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
124
+ # Predict the noise residual
125
+ noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
126
+ return noise_pred
127
+
128
+ def load_from_checkpoint(self, ckpt_path: str):
129
+ # Calculate original checksums
130
+ orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
131
+ orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
132
+
133
+ state_dict = torch.load(ckpt_path, map_location="cpu")
134
+
135
+ # Check if 'latents' exists in both the saved state_dict and the current model's state_dict
136
+ strict_load_image_proj_model = True
137
+ if "latents" in state_dict["image_proj"] and "latents" in self.image_proj_model.state_dict():
138
+ # Check if the shapes are mismatched
139
+ if state_dict["image_proj"]["latents"].shape != self.image_proj_model.state_dict()["latents"].shape:
140
+ print(f"Shapes of 'image_proj.latents' in checkpoint {ckpt_path} and current model do not match.")
141
+ print("Removing 'latents' from checkpoint and loading the rest of the weights.")
142
+ del state_dict["image_proj"]["latents"]
143
+ strict_load_image_proj_model = False
144
+
145
+ # Load state dict for image_proj_model and adapter_modules
146
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=strict_load_image_proj_model)
147
+ self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
148
+
149
+ # Calculate new checksums
150
+ new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
151
+ new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
152
+
153
+ # Verify if the weights have changed
154
+ assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
155
+ assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
156
+
157
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
158
+
159
+
160
+ def parse_args():
161
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
162
+ parser.add_argument(
163
+ "--pretrained_model_name_or_path",
164
+ type=str,
165
+ default=None,
166
+ required=True,
167
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
168
+ )
169
+ parser.add_argument(
170
+ "--pretrained_ip_adapter_path",
171
+ type=str,
172
+ default=None,
173
+ help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
174
+ )
175
+ parser.add_argument(
176
+ "--num_tokens",
177
+ type=int,
178
+ default=16,
179
+ help="Number of tokens to query from the CLIP image encoding.",
180
+ )
181
+ parser.add_argument(
182
+ "--data_json_file",
183
+ type=str,
184
+ default=None,
185
+ required=True,
186
+ help="Training data",
187
+ )
188
+ parser.add_argument(
189
+ "--data_root_path",
190
+ type=str,
191
+ default="",
192
+ required=True,
193
+ help="Training data root path",
194
+ )
195
+ parser.add_argument(
196
+ "--image_encoder_path",
197
+ type=str,
198
+ default=None,
199
+ required=True,
200
+ help="Path to CLIP image encoder",
201
+ )
202
+ parser.add_argument(
203
+ "--output_dir",
204
+ type=str,
205
+ default="sd-ip_adapter",
206
+ help="The output directory where the model predictions and checkpoints will be written.",
207
+ )
208
+ parser.add_argument(
209
+ "--logging_dir",
210
+ type=str,
211
+ default="logs",
212
+ help=(
213
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
214
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
215
+ ),
216
+ )
217
+ parser.add_argument(
218
+ "--resolution",
219
+ type=int,
220
+ default=512,
221
+ help=("The resolution for input images"),
222
+ )
223
+ parser.add_argument(
224
+ "--learning_rate",
225
+ type=float,
226
+ default=1e-4,
227
+ help="Learning rate to use.",
228
+ )
229
+ parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
230
+ parser.add_argument("--num_train_epochs", type=int, default=100)
231
+ parser.add_argument(
232
+ "--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
233
+ )
234
+ parser.add_argument(
235
+ "--dataloader_num_workers",
236
+ type=int,
237
+ default=0,
238
+ help=(
239
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
240
+ ),
241
+ )
242
+ parser.add_argument(
243
+ "--save_steps",
244
+ type=int,
245
+ default=2000,
246
+ help=("Save a checkpoint of the training state every X updates"),
247
+ )
248
+ parser.add_argument(
249
+ "--mixed_precision",
250
+ type=str,
251
+ default=None,
252
+ choices=["no", "fp16", "bf16"],
253
+ help=(
254
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
255
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
256
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
257
+ ),
258
+ )
259
+ parser.add_argument(
260
+ "--report_to",
261
+ type=str,
262
+ default="tensorboard",
263
+ help=(
264
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
265
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
266
+ ),
267
+ )
268
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
269
+
270
+ args = parser.parse_args()
271
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
272
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
273
+ args.local_rank = env_local_rank
274
+
275
+ return args
276
+
277
+
278
+ def main():
279
+ args = parse_args()
280
+ logging_dir = Path(args.output_dir, args.logging_dir)
281
+
282
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
283
+
284
+ accelerator = Accelerator(
285
+ mixed_precision=args.mixed_precision,
286
+ log_with=args.report_to,
287
+ project_config=accelerator_project_config,
288
+ )
289
+
290
+ if accelerator.is_main_process:
291
+ if args.output_dir is not None:
292
+ os.makedirs(args.output_dir, exist_ok=True)
293
+
294
+ # Load scheduler, tokenizer and models.
295
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
296
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
297
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
298
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
299
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
300
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
301
+ # freeze parameters of models to save more memory
302
+ unet.requires_grad_(False)
303
+ vae.requires_grad_(False)
304
+ text_encoder.requires_grad_(False)
305
+ image_encoder.requires_grad_(False)
306
+
307
+ # ip-adapter-plus
308
+ image_proj_model = Resampler(
309
+ dim=unet.config.cross_attention_dim,
310
+ depth=4,
311
+ dim_head=64,
312
+ heads=12,
313
+ num_queries=args.num_tokens,
314
+ embedding_dim=image_encoder.config.hidden_size,
315
+ output_dim=unet.config.cross_attention_dim,
316
+ ff_mult=4,
317
+ )
318
+ # init adapter modules
319
+ attn_procs = {}
320
+ unet_sd = unet.state_dict()
321
+ for name in unet.attn_processors.keys():
322
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
323
+ if name.startswith("mid_block"):
324
+ hidden_size = unet.config.block_out_channels[-1]
325
+ elif name.startswith("up_blocks"):
326
+ block_id = int(name[len("up_blocks.")])
327
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
328
+ elif name.startswith("down_blocks"):
329
+ block_id = int(name[len("down_blocks.")])
330
+ hidden_size = unet.config.block_out_channels[block_id]
331
+ if cross_attention_dim is None:
332
+ attn_procs[name] = AttnProcessor()
333
+ else:
334
+ layer_name = name.split(".processor")[0]
335
+ weights = {
336
+ "to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
337
+ "to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
338
+ }
339
+ attn_procs[name] = IPAttnProcessor(
340
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=args.num_tokens
341
+ )
342
+ attn_procs[name].load_state_dict(weights)
343
+ unet.set_attn_processor(attn_procs)
344
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
345
+
346
+ ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
347
+
348
+ weight_dtype = torch.float32
349
+ if accelerator.mixed_precision == "fp16":
350
+ weight_dtype = torch.float16
351
+ elif accelerator.mixed_precision == "bf16":
352
+ weight_dtype = torch.bfloat16
353
+ # unet.to(accelerator.device, dtype=weight_dtype)
354
+ vae.to(accelerator.device, dtype=weight_dtype)
355
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
356
+ image_encoder.to(accelerator.device, dtype=weight_dtype)
357
+
358
+ # optimizer
359
+ params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
360
+ optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
361
+
362
+ # dataloader
363
+ train_dataset = MyDataset(
364
+ args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
365
+ )
366
+ train_dataloader = torch.utils.data.DataLoader(
367
+ train_dataset,
368
+ shuffle=True,
369
+ collate_fn=collate_fn,
370
+ batch_size=args.train_batch_size,
371
+ num_workers=args.dataloader_num_workers,
372
+ )
373
+
374
+ # Prepare everything with our `accelerator`.
375
+ ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
376
+
377
+ global_step = 0
378
+ for epoch in range(0, args.num_train_epochs):
379
+ begin = time.perf_counter()
380
+ for step, batch in enumerate(train_dataloader):
381
+ load_data_time = time.perf_counter() - begin
382
+ with accelerator.accumulate(ip_adapter):
383
+ # Convert images to latent space
384
+ with torch.no_grad():
385
+ latents = vae.encode(
386
+ batch["images"].to(accelerator.device, dtype=weight_dtype)
387
+ ).latent_dist.sample()
388
+ latents = latents * vae.config.scaling_factor
389
+
390
+ # Sample noise that we'll add to the latents
391
+ noise = torch.randn_like(latents)
392
+ bsz = latents.shape[0]
393
+ # Sample a random timestep for each image
394
+ timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
395
+ timesteps = timesteps.long()
396
+
397
+ # Add noise to the latents according to the noise magnitude at each timestep
398
+ # (this is the forward diffusion process)
399
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
400
+
401
+ clip_images = []
402
+ for clip_image, drop_image_embed in zip(batch["clip_images"], batch["drop_image_embeds"]):
403
+ if drop_image_embed == 1:
404
+ clip_images.append(torch.zeros_like(clip_image))
405
+ else:
406
+ clip_images.append(clip_image)
407
+ clip_images = torch.stack(clip_images, dim=0)
408
+ with torch.no_grad():
409
+ image_embeds = image_encoder(
410
+ clip_images.to(accelerator.device, dtype=weight_dtype), output_hidden_states=True
411
+ ).hidden_states[-2]
412
+
413
+ with torch.no_grad():
414
+ encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
415
+
416
+ noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
417
+
418
+ loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
419
+
420
+ # Gather the losses across all processes for logging (if we use distributed training).
421
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
422
+
423
+ # Backpropagate
424
+ accelerator.backward(loss)
425
+ optimizer.step()
426
+ optimizer.zero_grad()
427
+
428
+ if accelerator.is_main_process:
429
+ print(
430
+ "Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
431
+ epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
432
+ )
433
+ )
434
+
435
+ global_step += 1
436
+
437
+ if global_step % args.save_steps == 0:
438
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
439
+ accelerator.save_state(save_path)
440
+
441
+ begin = time.perf_counter()
442
+
443
+
444
+ if __name__ == "__main__":
445
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import json
4
+ import os
5
+ import random
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from accelerate import Accelerator
13
+ from accelerate.utils import ProjectConfiguration
14
+ from ip_adapter.ip_adapter import ImageProjModel
15
+ from ip_adapter.utils import is_torch2_available
16
+ from PIL import Image
17
+ from torchvision import transforms
18
+ from transformers import (
19
+ CLIPImageProcessor,
20
+ CLIPTextModel,
21
+ CLIPTextModelWithProjection,
22
+ CLIPTokenizer,
23
+ CLIPVisionModelWithProjection,
24
+ )
25
+
26
+ from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
27
+
28
+
29
+ if is_torch2_available():
30
+ from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
31
+ from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
32
+ else:
33
+ from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
34
+
35
+
36
+ # Dataset
37
+ class MyDataset(torch.utils.data.Dataset):
38
+ def __init__(
39
+ self,
40
+ json_file,
41
+ tokenizer,
42
+ tokenizer_2,
43
+ size=1024,
44
+ center_crop=True,
45
+ t_drop_rate=0.05,
46
+ i_drop_rate=0.05,
47
+ ti_drop_rate=0.05,
48
+ image_root_path="",
49
+ ):
50
+ super().__init__()
51
+
52
+ self.tokenizer = tokenizer
53
+ self.tokenizer_2 = tokenizer_2
54
+ self.size = size
55
+ self.center_crop = center_crop
56
+ self.i_drop_rate = i_drop_rate
57
+ self.t_drop_rate = t_drop_rate
58
+ self.ti_drop_rate = ti_drop_rate
59
+ self.image_root_path = image_root_path
60
+
61
+ self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
62
+
63
+ self.transform = transforms.Compose(
64
+ [
65
+ transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
66
+ transforms.ToTensor(),
67
+ transforms.Normalize([0.5], [0.5]),
68
+ ]
69
+ )
70
+
71
+ self.clip_image_processor = CLIPImageProcessor()
72
+
73
+ def __getitem__(self, idx):
74
+ item = self.data[idx]
75
+ text = item["text"]
76
+ image_file = item["image_file"]
77
+
78
+ # read image
79
+ raw_image = Image.open(os.path.join(self.image_root_path, image_file))
80
+
81
+ # original size
82
+ original_width, original_height = raw_image.size
83
+ original_size = torch.tensor([original_height, original_width])
84
+
85
+ image_tensor = self.transform(raw_image.convert("RGB"))
86
+ # random crop
87
+ delta_h = image_tensor.shape[1] - self.size
88
+ delta_w = image_tensor.shape[2] - self.size
89
+ assert not all([delta_h, delta_w])
90
+
91
+ if self.center_crop:
92
+ top = delta_h // 2
93
+ left = delta_w // 2
94
+ else:
95
+ top = np.random.randint(0, delta_h + 1)
96
+ left = np.random.randint(0, delta_w + 1)
97
+ image = transforms.functional.crop(image_tensor, top=top, left=left, height=self.size, width=self.size)
98
+ crop_coords_top_left = torch.tensor([top, left])
99
+
100
+ clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
101
+
102
+ # drop
103
+ drop_image_embed = 0
104
+ rand_num = random.random()
105
+ if rand_num < self.i_drop_rate:
106
+ drop_image_embed = 1
107
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate):
108
+ text = ""
109
+ elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
110
+ text = ""
111
+ drop_image_embed = 1
112
+
113
+ # get text and tokenize
114
+ text_input_ids = self.tokenizer(
115
+ text,
116
+ max_length=self.tokenizer.model_max_length,
117
+ padding="max_length",
118
+ truncation=True,
119
+ return_tensors="pt",
120
+ ).input_ids
121
+
122
+ text_input_ids_2 = self.tokenizer_2(
123
+ text,
124
+ max_length=self.tokenizer_2.model_max_length,
125
+ padding="max_length",
126
+ truncation=True,
127
+ return_tensors="pt",
128
+ ).input_ids
129
+
130
+ return {
131
+ "image": image,
132
+ "text_input_ids": text_input_ids,
133
+ "text_input_ids_2": text_input_ids_2,
134
+ "clip_image": clip_image,
135
+ "drop_image_embed": drop_image_embed,
136
+ "original_size": original_size,
137
+ "crop_coords_top_left": crop_coords_top_left,
138
+ "target_size": torch.tensor([self.size, self.size]),
139
+ }
140
+
141
+ def __len__(self):
142
+ return len(self.data)
143
+
144
+
145
+ def collate_fn(data):
146
+ images = torch.stack([example["image"] for example in data])
147
+ text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
148
+ text_input_ids_2 = torch.cat([example["text_input_ids_2"] for example in data], dim=0)
149
+ clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
150
+ drop_image_embeds = [example["drop_image_embed"] for example in data]
151
+ original_size = torch.stack([example["original_size"] for example in data])
152
+ crop_coords_top_left = torch.stack([example["crop_coords_top_left"] for example in data])
153
+ target_size = torch.stack([example["target_size"] for example in data])
154
+
155
+ return {
156
+ "images": images,
157
+ "text_input_ids": text_input_ids,
158
+ "text_input_ids_2": text_input_ids_2,
159
+ "clip_images": clip_images,
160
+ "drop_image_embeds": drop_image_embeds,
161
+ "original_size": original_size,
162
+ "crop_coords_top_left": crop_coords_top_left,
163
+ "target_size": target_size,
164
+ }
165
+
166
+
167
+ class IPAdapter(torch.nn.Module):
168
+ """IP-Adapter"""
169
+
170
+ def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
171
+ super().__init__()
172
+ self.unet = unet
173
+ self.image_proj_model = image_proj_model
174
+ self.adapter_modules = adapter_modules
175
+
176
+ if ckpt_path is not None:
177
+ self.load_from_checkpoint(ckpt_path)
178
+
179
+ def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds):
180
+ ip_tokens = self.image_proj_model(image_embeds)
181
+ encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
182
+ # Predict the noise residual
183
+ noise_pred = self.unet(
184
+ noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=unet_added_cond_kwargs
185
+ ).sample
186
+ return noise_pred
187
+
188
+ def load_from_checkpoint(self, ckpt_path: str):
189
+ # Calculate original checksums
190
+ orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
191
+ orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
192
+
193
+ state_dict = torch.load(ckpt_path, map_location="cpu")
194
+
195
+ # Load state dict for image_proj_model and adapter_modules
196
+ self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
197
+ self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
198
+
199
+ # Calculate new checksums
200
+ new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
201
+ new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
202
+
203
+ # Verify if the weights have changed
204
+ assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
205
+ assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
206
+
207
+ print(f"Successfully loaded weights from checkpoint {ckpt_path}")
208
+
209
+
210
+ def parse_args():
211
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
212
+ parser.add_argument(
213
+ "--pretrained_model_name_or_path",
214
+ type=str,
215
+ default=None,
216
+ required=True,
217
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
218
+ )
219
+ parser.add_argument(
220
+ "--pretrained_ip_adapter_path",
221
+ type=str,
222
+ default=None,
223
+ help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
224
+ )
225
+ parser.add_argument(
226
+ "--data_json_file",
227
+ type=str,
228
+ default=None,
229
+ required=True,
230
+ help="Training data",
231
+ )
232
+ parser.add_argument(
233
+ "--data_root_path",
234
+ type=str,
235
+ default="",
236
+ required=True,
237
+ help="Training data root path",
238
+ )
239
+ parser.add_argument(
240
+ "--image_encoder_path",
241
+ type=str,
242
+ default=None,
243
+ required=True,
244
+ help="Path to CLIP image encoder",
245
+ )
246
+ parser.add_argument(
247
+ "--output_dir",
248
+ type=str,
249
+ default="sd-ip_adapter",
250
+ help="The output directory where the model predictions and checkpoints will be written.",
251
+ )
252
+ parser.add_argument(
253
+ "--logging_dir",
254
+ type=str,
255
+ default="logs",
256
+ help=(
257
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
258
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
259
+ ),
260
+ )
261
+ parser.add_argument(
262
+ "--resolution",
263
+ type=int,
264
+ default=512,
265
+ help=("The resolution for input images"),
266
+ )
267
+ parser.add_argument(
268
+ "--learning_rate",
269
+ type=float,
270
+ default=1e-4,
271
+ help="Learning rate to use.",
272
+ )
273
+ parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
274
+ parser.add_argument("--num_train_epochs", type=int, default=100)
275
+ parser.add_argument(
276
+ "--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
277
+ )
278
+ parser.add_argument("--noise_offset", type=float, default=None, help="noise offset")
279
+ parser.add_argument(
280
+ "--dataloader_num_workers",
281
+ type=int,
282
+ default=0,
283
+ help=(
284
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
285
+ ),
286
+ )
287
+ parser.add_argument(
288
+ "--save_steps",
289
+ type=int,
290
+ default=2000,
291
+ help=("Save a checkpoint of the training state every X updates"),
292
+ )
293
+ parser.add_argument(
294
+ "--mixed_precision",
295
+ type=str,
296
+ default=None,
297
+ choices=["no", "fp16", "bf16"],
298
+ help=(
299
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
300
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
301
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
302
+ ),
303
+ )
304
+ parser.add_argument(
305
+ "--report_to",
306
+ type=str,
307
+ default="tensorboard",
308
+ help=(
309
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
310
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
311
+ ),
312
+ )
313
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
314
+
315
+ args = parser.parse_args()
316
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
317
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
318
+ args.local_rank = env_local_rank
319
+
320
+ return args
321
+
322
+
323
+ def main():
324
+ args = parse_args()
325
+ logging_dir = Path(args.output_dir, args.logging_dir)
326
+
327
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
328
+
329
+ accelerator = Accelerator(
330
+ mixed_precision=args.mixed_precision,
331
+ log_with=args.report_to,
332
+ project_config=accelerator_project_config,
333
+ )
334
+
335
+ if accelerator.is_main_process:
336
+ if args.output_dir is not None:
337
+ os.makedirs(args.output_dir, exist_ok=True)
338
+
339
+ # Load scheduler, tokenizer and models.
340
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
341
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
342
+ text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
343
+ tokenizer_2 = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer_2")
344
+ text_encoder_2 = CLIPTextModelWithProjection.from_pretrained(
345
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2"
346
+ )
347
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
348
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
349
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
350
+ # freeze parameters of models to save more memory
351
+ unet.requires_grad_(False)
352
+ vae.requires_grad_(False)
353
+ text_encoder.requires_grad_(False)
354
+ text_encoder_2.requires_grad_(False)
355
+ image_encoder.requires_grad_(False)
356
+
357
+ # ip-adapter
358
+ num_tokens = 4
359
+ image_proj_model = ImageProjModel(
360
+ cross_attention_dim=unet.config.cross_attention_dim,
361
+ clip_embeddings_dim=image_encoder.config.projection_dim,
362
+ clip_extra_context_tokens=num_tokens,
363
+ )
364
+ # init adapter modules
365
+ attn_procs = {}
366
+ unet_sd = unet.state_dict()
367
+ for name in unet.attn_processors.keys():
368
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
369
+ if name.startswith("mid_block"):
370
+ hidden_size = unet.config.block_out_channels[-1]
371
+ elif name.startswith("up_blocks"):
372
+ block_id = int(name[len("up_blocks.")])
373
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
374
+ elif name.startswith("down_blocks"):
375
+ block_id = int(name[len("down_blocks.")])
376
+ hidden_size = unet.config.block_out_channels[block_id]
377
+ if cross_attention_dim is None:
378
+ attn_procs[name] = AttnProcessor()
379
+ else:
380
+ layer_name = name.split(".processor")[0]
381
+ weights = {
382
+ "to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
383
+ "to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
384
+ }
385
+ attn_procs[name] = IPAttnProcessor(
386
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=num_tokens
387
+ )
388
+ attn_procs[name].load_state_dict(weights)
389
+ unet.set_attn_processor(attn_procs)
390
+ adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
391
+
392
+ ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
393
+
394
+ weight_dtype = torch.float32
395
+ if accelerator.mixed_precision == "fp16":
396
+ weight_dtype = torch.float16
397
+ elif accelerator.mixed_precision == "bf16":
398
+ weight_dtype = torch.bfloat16
399
+ # unet.to(accelerator.device, dtype=weight_dtype)
400
+ vae.to(accelerator.device) # use fp32
401
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
402
+ text_encoder_2.to(accelerator.device, dtype=weight_dtype)
403
+ image_encoder.to(accelerator.device, dtype=weight_dtype)
404
+
405
+ # optimizer
406
+ params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
407
+ optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
408
+
409
+ # dataloader
410
+ train_dataset = MyDataset(
411
+ args.data_json_file,
412
+ tokenizer=tokenizer,
413
+ tokenizer_2=tokenizer_2,
414
+ size=args.resolution,
415
+ image_root_path=args.data_root_path,
416
+ )
417
+ train_dataloader = torch.utils.data.DataLoader(
418
+ train_dataset,
419
+ shuffle=True,
420
+ collate_fn=collate_fn,
421
+ batch_size=args.train_batch_size,
422
+ num_workers=args.dataloader_num_workers,
423
+ )
424
+
425
+ # Prepare everything with our `accelerator`.
426
+ ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
427
+
428
+ global_step = 0
429
+ for epoch in range(0, args.num_train_epochs):
430
+ begin = time.perf_counter()
431
+ for step, batch in enumerate(train_dataloader):
432
+ load_data_time = time.perf_counter() - begin
433
+ with accelerator.accumulate(ip_adapter):
434
+ # Convert images to latent space
435
+ with torch.no_grad():
436
+ # vae of sdxl should use fp32
437
+ latents = vae.encode(batch["images"].to(accelerator.device, dtype=vae.dtype)).latent_dist.sample()
438
+ latents = latents * vae.config.scaling_factor
439
+ latents = latents.to(accelerator.device, dtype=weight_dtype)
440
+
441
+ # Sample noise that we'll add to the latents
442
+ noise = torch.randn_like(latents)
443
+ if args.noise_offset:
444
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
445
+ noise += args.noise_offset * torch.randn((latents.shape[0], latents.shape[1], 1, 1)).to(
446
+ accelerator.device, dtype=weight_dtype
447
+ )
448
+
449
+ bsz = latents.shape[0]
450
+ # Sample a random timestep for each image
451
+ timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
452
+ timesteps = timesteps.long()
453
+
454
+ # Add noise to the latents according to the noise magnitude at each timestep
455
+ # (this is the forward diffusion process)
456
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
457
+
458
+ with torch.no_grad():
459
+ image_embeds = image_encoder(
460
+ batch["clip_images"].to(accelerator.device, dtype=weight_dtype)
461
+ ).image_embeds
462
+ image_embeds_ = []
463
+ for image_embed, drop_image_embed in zip(image_embeds, batch["drop_image_embeds"]):
464
+ if drop_image_embed == 1:
465
+ image_embeds_.append(torch.zeros_like(image_embed))
466
+ else:
467
+ image_embeds_.append(image_embed)
468
+ image_embeds = torch.stack(image_embeds_)
469
+
470
+ with torch.no_grad():
471
+ encoder_output = text_encoder(
472
+ batch["text_input_ids"].to(accelerator.device), output_hidden_states=True
473
+ )
474
+ text_embeds = encoder_output.hidden_states[-2]
475
+ encoder_output_2 = text_encoder_2(
476
+ batch["text_input_ids_2"].to(accelerator.device), output_hidden_states=True
477
+ )
478
+ pooled_text_embeds = encoder_output_2[0]
479
+ text_embeds_2 = encoder_output_2.hidden_states[-2]
480
+ text_embeds = torch.concat([text_embeds, text_embeds_2], dim=-1) # concat
481
+
482
+ # add cond
483
+ add_time_ids = [
484
+ batch["original_size"].to(accelerator.device),
485
+ batch["crop_coords_top_left"].to(accelerator.device),
486
+ batch["target_size"].to(accelerator.device),
487
+ ]
488
+ add_time_ids = torch.cat(add_time_ids, dim=1).to(accelerator.device, dtype=weight_dtype)
489
+ unet_added_cond_kwargs = {"text_embeds": pooled_text_embeds, "time_ids": add_time_ids}
490
+
491
+ noise_pred = ip_adapter(noisy_latents, timesteps, text_embeds, unet_added_cond_kwargs, image_embeds)
492
+
493
+ loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
494
+
495
+ # Gather the losses across all processes for logging (if we use distributed training).
496
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
497
+
498
+ # Backpropagate
499
+ accelerator.backward(loss)
500
+ optimizer.step()
501
+ optimizer.zero_grad()
502
+
503
+ if accelerator.is_main_process:
504
+ print(
505
+ "Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
506
+ epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
507
+ )
508
+ )
509
+
510
+ global_step += 1
511
+
512
+ if global_step % args.save_steps == 0:
513
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
514
+ accelerator.save_state(save_path)
515
+
516
+ begin = time.perf_counter()
517
+
518
+
519
+ if __name__ == "__main__":
520
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/README.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion text-to-image fine-tuning
2
+ This extended LoRA training script was authored by [haofanwang](https://github.com/haofanwang).
3
+ This is an experimental LoRA extension of [this example](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py). We further support add LoRA layers for text encoder.
4
+
5
+ ## Training with LoRA
6
+
7
+ 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*.
8
+
9
+ 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:
10
+
11
+ - Previous pretrained weights are kept frozen so that model is not prone to [catastrophic forgetting](https://www.pnas.org/doi/10.1073/pnas.1611835114).
12
+ - Rank-decomposition matrices have significantly fewer parameters than original model, which means that trained LoRA weights are easily portable.
13
+ - LoRA attention layers allow to control to which extent the model is adapted toward new training images via a `scale` parameter.
14
+
15
+ [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.
16
+
17
+ With LoRA, it's possible to fine-tune Stable Diffusion on a custom image-caption pair dataset
18
+ on consumer GPUs like Tesla T4, Tesla V100.
19
+
20
+ ### Training
21
+
22
+ 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).
23
+
24
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
25
+
26
+ **___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.___**
27
+
28
+ ```bash
29
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
30
+ export DATASET_NAME="lambdalabs/naruto-blip-captions"
31
+ ```
32
+
33
+ For this example we want to directly store the trained LoRA embeddings on the Hub, so
34
+ we need to be logged in and add the `--push_to_hub` flag.
35
+
36
+ ```bash
37
+ hf auth login
38
+ ```
39
+
40
+ Now we can start training!
41
+
42
+ ```bash
43
+ accelerate launch --mixed_precision="fp16" train_text_to_image_lora.py \
44
+ --pretrained_model_name_or_path=$MODEL_NAME \
45
+ --dataset_name=$DATASET_NAME --caption_column="text" \
46
+ --resolution=512 --random_flip \
47
+ --train_batch_size=1 \
48
+ --num_train_epochs=100 --checkpointing_steps=5000 \
49
+ --learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
50
+ --seed=42 \
51
+ --output_dir="sd-naruto-model-lora" \
52
+ --validation_prompt="cute dragon creature" --report_to="wandb"
53
+ --use_peft \
54
+ --lora_r=4 --lora_alpha=32 \
55
+ --lora_text_encoder_r=4 --lora_text_encoder_alpha=32
56
+ ```
57
+
58
+ The above command will also run inference as fine-tuning progresses and log the results to Weights and Biases.
59
+
60
+ **___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.___**
61
+
62
+ 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.___**
63
+
64
+ 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).
65
+
66
+ ### Inference
67
+
68
+ 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
69
+ need to pass the `output_dir` for loading the LoRA weights which, in this case, is `sd-naruto-model-lora`.
70
+
71
+ ```python
72
+ from diffusers import StableDiffusionPipeline
73
+ import torch
74
+
75
+ model_path = "sayakpaul/sd-model-finetuned-lora-t4"
76
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
77
+ pipe.unet.load_attn_procs(model_path)
78
+ pipe.to("cuda")
79
+
80
+ prompt = "A naruto with green eyes and red legs."
81
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
82
+ image.save("naruto.png")
83
+ ```
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ datasets
5
+ ftfy
6
+ tensorboard
7
+ Jinja2
8
+ git+https://github.com/huggingface/peft.git
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/lora/train_text_to_image_lora.py ADDED
@@ -0,0 +1,1026 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
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
+ """Fine-tuning script for Stable Diffusion for text2image with support for LoRA."""
16
+
17
+ import argparse
18
+ import itertools
19
+ import json
20
+ import logging
21
+ import math
22
+ import os
23
+ import random
24
+ from pathlib import Path
25
+
26
+ import datasets
27
+ import numpy as np
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 datasets import load_dataset
36
+ from huggingface_hub import create_repo, upload_folder
37
+ from packaging import version
38
+ from torchvision import transforms
39
+ from tqdm.auto import tqdm
40
+ from transformers import CLIPTextModel, CLIPTokenizer
41
+
42
+ import diffusers
43
+ from diffusers import AutoencoderKL, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel
44
+ from diffusers.loaders import AttnProcsLayers
45
+ from diffusers.models.attention_processor import LoRAAttnProcessor
46
+ from diffusers.optimization import get_scheduler
47
+ from diffusers.utils import check_min_version, is_wandb_available
48
+ from diffusers.utils.import_utils import is_xformers_available
49
+
50
+
51
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
52
+ check_min_version("0.14.0.dev0")
53
+
54
+ logger = get_logger(__name__, log_level="INFO")
55
+
56
+
57
+ def save_model_card(repo_id: str, images=None, base_model=str, dataset_name=str, repo_folder=None):
58
+ img_str = ""
59
+ for i, image in enumerate(images):
60
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
61
+ img_str += f"![img_{i}](./image_{i}.png)\n"
62
+
63
+ yaml = f"""
64
+ ---
65
+ license: creativeml-openrail-m
66
+ base_model: {base_model}
67
+ tags:
68
+ - stable-diffusion
69
+ - stable-diffusion-diffusers
70
+ - text-to-image
71
+ - diffusers
72
+ - diffusers-training
73
+ - lora
74
+ inference: true
75
+ ---
76
+ """
77
+ model_card = f"""
78
+ # LoRA text2image fine-tuning - {repo_id}
79
+ 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
80
+ {img_str}
81
+ """
82
+ with open(os.path.join(repo_folder, "README.md"), "w") as f:
83
+ f.write(yaml + model_card)
84
+
85
+
86
+ def parse_args():
87
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
88
+ parser.add_argument(
89
+ "--pretrained_model_name_or_path",
90
+ type=str,
91
+ default=None,
92
+ required=True,
93
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
94
+ )
95
+ parser.add_argument(
96
+ "--revision",
97
+ type=str,
98
+ default=None,
99
+ required=False,
100
+ help="Revision of pretrained model identifier from huggingface.co/models.",
101
+ )
102
+ parser.add_argument(
103
+ "--dataset_name",
104
+ type=str,
105
+ default=None,
106
+ help=(
107
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
108
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
109
+ " or to a folder containing files that 🤗 Datasets can understand."
110
+ ),
111
+ )
112
+ parser.add_argument(
113
+ "--dataset_config_name",
114
+ type=str,
115
+ default=None,
116
+ help="The config of the Dataset, leave as None if there's only one config.",
117
+ )
118
+ parser.add_argument(
119
+ "--train_data_dir",
120
+ type=str,
121
+ default=None,
122
+ help=(
123
+ "A folder containing the training data. Folder contents must follow the structure described in"
124
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
125
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
126
+ ),
127
+ )
128
+ parser.add_argument(
129
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
130
+ )
131
+ parser.add_argument(
132
+ "--caption_column",
133
+ type=str,
134
+ default="text",
135
+ help="The column of the dataset containing a caption or a list of captions.",
136
+ )
137
+ parser.add_argument(
138
+ "--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
139
+ )
140
+ parser.add_argument(
141
+ "--num_validation_images",
142
+ type=int,
143
+ default=4,
144
+ help="Number of images that should be generated during validation with `validation_prompt`.",
145
+ )
146
+ parser.add_argument(
147
+ "--validation_epochs",
148
+ type=int,
149
+ default=1,
150
+ help=(
151
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
152
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
153
+ ),
154
+ )
155
+ parser.add_argument(
156
+ "--max_train_samples",
157
+ type=int,
158
+ default=None,
159
+ help=(
160
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
161
+ "value if set."
162
+ ),
163
+ )
164
+ parser.add_argument(
165
+ "--output_dir",
166
+ type=str,
167
+ default="sd-model-finetuned-lora",
168
+ help="The output directory where the model predictions and checkpoints will be written.",
169
+ )
170
+ parser.add_argument(
171
+ "--cache_dir",
172
+ type=str,
173
+ default=None,
174
+ help="The directory where the downloaded models and datasets will be stored.",
175
+ )
176
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
177
+ parser.add_argument(
178
+ "--resolution",
179
+ type=int,
180
+ default=512,
181
+ help=(
182
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
183
+ " resolution"
184
+ ),
185
+ )
186
+ parser.add_argument(
187
+ "--center_crop",
188
+ default=False,
189
+ action="store_true",
190
+ help=(
191
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
192
+ " cropped. The images will be resized to the resolution first before cropping."
193
+ ),
194
+ )
195
+ parser.add_argument(
196
+ "--random_flip",
197
+ action="store_true",
198
+ help="whether to randomly flip images horizontally",
199
+ )
200
+ parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
201
+
202
+ # lora args
203
+ parser.add_argument("--use_peft", action="store_true", help="Whether to use peft to support lora")
204
+ parser.add_argument("--lora_r", type=int, default=4, help="Lora rank, only used if use_lora is True")
205
+ parser.add_argument("--lora_alpha", type=int, default=32, help="Lora alpha, only used if lora is True")
206
+ parser.add_argument("--lora_dropout", type=float, default=0.0, help="Lora dropout, only used if use_lora is True")
207
+ parser.add_argument(
208
+ "--lora_bias",
209
+ type=str,
210
+ default="none",
211
+ help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora is True",
212
+ )
213
+ parser.add_argument(
214
+ "--lora_text_encoder_r",
215
+ type=int,
216
+ default=4,
217
+ help="Lora rank for text encoder, only used if `use_lora` and `train_text_encoder` are True",
218
+ )
219
+ parser.add_argument(
220
+ "--lora_text_encoder_alpha",
221
+ type=int,
222
+ default=32,
223
+ help="Lora alpha for text encoder, only used if `use_lora` and `train_text_encoder` are True",
224
+ )
225
+ parser.add_argument(
226
+ "--lora_text_encoder_dropout",
227
+ type=float,
228
+ default=0.0,
229
+ help="Lora dropout for text encoder, only used if `use_lora` and `train_text_encoder` are True",
230
+ )
231
+ parser.add_argument(
232
+ "--lora_text_encoder_bias",
233
+ type=str,
234
+ default="none",
235
+ help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora and `train_text_encoder` are True",
236
+ )
237
+
238
+ parser.add_argument(
239
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
240
+ )
241
+ parser.add_argument("--num_train_epochs", type=int, default=100)
242
+ parser.add_argument(
243
+ "--max_train_steps",
244
+ type=int,
245
+ default=None,
246
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
247
+ )
248
+ parser.add_argument(
249
+ "--gradient_accumulation_steps",
250
+ type=int,
251
+ default=1,
252
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
253
+ )
254
+ parser.add_argument(
255
+ "--gradient_checkpointing",
256
+ action="store_true",
257
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
258
+ )
259
+ parser.add_argument(
260
+ "--learning_rate",
261
+ type=float,
262
+ default=1e-4,
263
+ help="Initial learning rate (after the potential warmup period) to use.",
264
+ )
265
+ parser.add_argument(
266
+ "--scale_lr",
267
+ action="store_true",
268
+ default=False,
269
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
270
+ )
271
+ parser.add_argument(
272
+ "--lr_scheduler",
273
+ type=str,
274
+ default="constant",
275
+ help=(
276
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
277
+ ' "constant", "constant_with_warmup"]'
278
+ ),
279
+ )
280
+ parser.add_argument(
281
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
282
+ )
283
+ parser.add_argument(
284
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
285
+ )
286
+ parser.add_argument(
287
+ "--allow_tf32",
288
+ action="store_true",
289
+ help=(
290
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
291
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
292
+ ),
293
+ )
294
+ parser.add_argument(
295
+ "--dataloader_num_workers",
296
+ type=int,
297
+ default=0,
298
+ help=(
299
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
300
+ ),
301
+ )
302
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
303
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
304
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
305
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
306
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
307
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
308
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
309
+ parser.add_argument(
310
+ "--hub_model_id",
311
+ type=str,
312
+ default=None,
313
+ help="The name of the repository to keep in sync with the local `output_dir`.",
314
+ )
315
+ parser.add_argument(
316
+ "--logging_dir",
317
+ type=str,
318
+ default="logs",
319
+ help=(
320
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
321
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
322
+ ),
323
+ )
324
+ parser.add_argument(
325
+ "--mixed_precision",
326
+ type=str,
327
+ default=None,
328
+ choices=["no", "fp16", "bf16"],
329
+ help=(
330
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
331
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
332
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
333
+ ),
334
+ )
335
+ parser.add_argument(
336
+ "--report_to",
337
+ type=str,
338
+ default="tensorboard",
339
+ help=(
340
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
341
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
342
+ ),
343
+ )
344
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
345
+ parser.add_argument(
346
+ "--checkpointing_steps",
347
+ type=int,
348
+ default=500,
349
+ help=(
350
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
351
+ " training using `--resume_from_checkpoint`."
352
+ ),
353
+ )
354
+ parser.add_argument(
355
+ "--checkpoints_total_limit",
356
+ type=int,
357
+ default=None,
358
+ help=(
359
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
360
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
361
+ " for more docs"
362
+ ),
363
+ )
364
+ parser.add_argument(
365
+ "--resume_from_checkpoint",
366
+ type=str,
367
+ default=None,
368
+ help=(
369
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
370
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
371
+ ),
372
+ )
373
+ parser.add_argument(
374
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
375
+ )
376
+
377
+ args = parser.parse_args()
378
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
379
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
380
+ args.local_rank = env_local_rank
381
+
382
+ # Sanity checks
383
+ if args.dataset_name is None and args.train_data_dir is None:
384
+ raise ValueError("Need either a dataset name or a training folder.")
385
+
386
+ return args
387
+
388
+
389
+ DATASET_NAME_MAPPING = {
390
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
391
+ }
392
+
393
+
394
+ def main():
395
+ args = parse_args()
396
+ if args.report_to == "wandb" and args.hub_token is not None:
397
+ raise ValueError(
398
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
399
+ " Please use `hf auth login` to authenticate with the Hub."
400
+ )
401
+
402
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
403
+
404
+ accelerator_project_config = ProjectConfiguration(
405
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
406
+ )
407
+
408
+ accelerator = Accelerator(
409
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
410
+ mixed_precision=args.mixed_precision,
411
+ log_with=args.report_to,
412
+ project_config=accelerator_project_config,
413
+ )
414
+
415
+ # Disable AMP for MPS.
416
+ if torch.backends.mps.is_available():
417
+ accelerator.native_amp = False
418
+
419
+ if args.report_to == "wandb":
420
+ if not is_wandb_available():
421
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
422
+ import wandb
423
+
424
+ # Make one log on every process with the configuration for debugging.
425
+ logging.basicConfig(
426
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
427
+ datefmt="%m/%d/%Y %H:%M:%S",
428
+ level=logging.INFO,
429
+ )
430
+ logger.info(accelerator.state, main_process_only=False)
431
+ if accelerator.is_local_main_process:
432
+ datasets.utils.logging.set_verbosity_warning()
433
+ transformers.utils.logging.set_verbosity_warning()
434
+ diffusers.utils.logging.set_verbosity_info()
435
+ else:
436
+ datasets.utils.logging.set_verbosity_error()
437
+ transformers.utils.logging.set_verbosity_error()
438
+ diffusers.utils.logging.set_verbosity_error()
439
+
440
+ # If passed along, set the training seed now.
441
+ if args.seed is not None:
442
+ set_seed(args.seed)
443
+
444
+ # Handle the repository creation
445
+ if accelerator.is_main_process:
446
+ if args.output_dir is not None:
447
+ os.makedirs(args.output_dir, exist_ok=True)
448
+
449
+ if args.push_to_hub:
450
+ repo_id = create_repo(
451
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
452
+ ).repo_id
453
+
454
+ # Load scheduler, tokenizer and models.
455
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
456
+ tokenizer = CLIPTokenizer.from_pretrained(
457
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
458
+ )
459
+ text_encoder = CLIPTextModel.from_pretrained(
460
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
461
+ )
462
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
463
+ unet = UNet2DConditionModel.from_pretrained(
464
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
465
+ )
466
+
467
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
468
+ # as these models are only used for inference, keeping weights in full precision is not required.
469
+ weight_dtype = torch.float32
470
+ if accelerator.mixed_precision == "fp16":
471
+ weight_dtype = torch.float16
472
+ elif accelerator.mixed_precision == "bf16":
473
+ weight_dtype = torch.bfloat16
474
+
475
+ if args.use_peft:
476
+ from peft import LoraConfig, LoraModel, get_peft_model_state_dict, set_peft_model_state_dict
477
+
478
+ UNET_TARGET_MODULES = ["to_q", "to_v", "query", "value"]
479
+ TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
480
+
481
+ config = LoraConfig(
482
+ r=args.lora_r,
483
+ lora_alpha=args.lora_alpha,
484
+ target_modules=UNET_TARGET_MODULES,
485
+ lora_dropout=args.lora_dropout,
486
+ bias=args.lora_bias,
487
+ )
488
+ unet = LoraModel(config, unet)
489
+
490
+ vae.requires_grad_(False)
491
+ if args.train_text_encoder:
492
+ config = LoraConfig(
493
+ r=args.lora_text_encoder_r,
494
+ lora_alpha=args.lora_text_encoder_alpha,
495
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
496
+ lora_dropout=args.lora_text_encoder_dropout,
497
+ bias=args.lora_text_encoder_bias,
498
+ )
499
+ text_encoder = LoraModel(config, text_encoder)
500
+ else:
501
+ # freeze parameters of models to save more memory
502
+ unet.requires_grad_(False)
503
+ vae.requires_grad_(False)
504
+
505
+ text_encoder.requires_grad_(False)
506
+
507
+ # now we will add new LoRA weights to the attention layers
508
+ # It's important to realize here how many attention weights will be added and of which sizes
509
+ # The sizes of the attention layers consist only of two different variables:
510
+ # 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`.
511
+ # 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`.
512
+
513
+ # Let's first see how many attention processors we will have to set.
514
+ # For Stable Diffusion, it should be equal to:
515
+ # - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12
516
+ # - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2
517
+ # - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18
518
+ # => 32 layers
519
+
520
+ # Set correct lora layers
521
+ lora_attn_procs = {}
522
+ for name in unet.attn_processors.keys():
523
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
524
+ if name.startswith("mid_block"):
525
+ hidden_size = unet.config.block_out_channels[-1]
526
+ elif name.startswith("up_blocks"):
527
+ block_id = int(name[len("up_blocks.")])
528
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
529
+ elif name.startswith("down_blocks"):
530
+ block_id = int(name[len("down_blocks.")])
531
+ hidden_size = unet.config.block_out_channels[block_id]
532
+
533
+ lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
534
+
535
+ unet.set_attn_processor(lora_attn_procs)
536
+ lora_layers = AttnProcsLayers(unet.attn_processors)
537
+
538
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
539
+ vae.to(accelerator.device, dtype=weight_dtype)
540
+ if not args.train_text_encoder:
541
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
542
+
543
+ if args.enable_xformers_memory_efficient_attention:
544
+ if is_xformers_available():
545
+ import xformers
546
+
547
+ xformers_version = version.parse(xformers.__version__)
548
+ if xformers_version == version.parse("0.0.16"):
549
+ logger.warning(
550
+ "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."
551
+ )
552
+ unet.enable_xformers_memory_efficient_attention()
553
+ else:
554
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
555
+
556
+ # Enable TF32 for faster training on Ampere GPUs,
557
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
558
+ if args.allow_tf32:
559
+ torch.backends.cuda.matmul.allow_tf32 = True
560
+
561
+ if args.scale_lr:
562
+ args.learning_rate = (
563
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
564
+ )
565
+
566
+ # Initialize the optimizer
567
+ if args.use_8bit_adam:
568
+ try:
569
+ import bitsandbytes as bnb
570
+ except ImportError:
571
+ raise ImportError(
572
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
573
+ )
574
+
575
+ optimizer_cls = bnb.optim.AdamW8bit
576
+ else:
577
+ optimizer_cls = torch.optim.AdamW
578
+
579
+ if args.use_peft:
580
+ # Optimizer creation
581
+ params_to_optimize = (
582
+ itertools.chain(unet.parameters(), text_encoder.parameters())
583
+ if args.train_text_encoder
584
+ else unet.parameters()
585
+ )
586
+ optimizer = optimizer_cls(
587
+ params_to_optimize,
588
+ lr=args.learning_rate,
589
+ betas=(args.adam_beta1, args.adam_beta2),
590
+ weight_decay=args.adam_weight_decay,
591
+ eps=args.adam_epsilon,
592
+ )
593
+ else:
594
+ optimizer = optimizer_cls(
595
+ lora_layers.parameters(),
596
+ lr=args.learning_rate,
597
+ betas=(args.adam_beta1, args.adam_beta2),
598
+ weight_decay=args.adam_weight_decay,
599
+ eps=args.adam_epsilon,
600
+ )
601
+
602
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
603
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
604
+
605
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
606
+ # download the dataset.
607
+ if args.dataset_name is not None:
608
+ # Downloading and loading a dataset from the hub.
609
+ dataset = load_dataset(
610
+ args.dataset_name,
611
+ args.dataset_config_name,
612
+ cache_dir=args.cache_dir,
613
+ )
614
+ else:
615
+ data_files = {}
616
+ if args.train_data_dir is not None:
617
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
618
+ dataset = load_dataset(
619
+ "imagefolder",
620
+ data_files=data_files,
621
+ cache_dir=args.cache_dir,
622
+ )
623
+ # See more about loading custom images at
624
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
625
+
626
+ # Preprocessing the datasets.
627
+ # We need to tokenize inputs and targets.
628
+ column_names = dataset["train"].column_names
629
+
630
+ # 6. Get the column names for input/target.
631
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
632
+ if args.image_column is None:
633
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
634
+ else:
635
+ image_column = args.image_column
636
+ if image_column not in column_names:
637
+ raise ValueError(
638
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
639
+ )
640
+ if args.caption_column is None:
641
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
642
+ else:
643
+ caption_column = args.caption_column
644
+ if caption_column not in column_names:
645
+ raise ValueError(
646
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
647
+ )
648
+
649
+ # Preprocessing the datasets.
650
+ # We need to tokenize input captions and transform the images.
651
+ def tokenize_captions(examples, is_train=True):
652
+ captions = []
653
+ for caption in examples[caption_column]:
654
+ if isinstance(caption, str):
655
+ captions.append(caption)
656
+ elif isinstance(caption, (list, np.ndarray)):
657
+ # take a random caption if there are multiple
658
+ captions.append(random.choice(caption) if is_train else caption[0])
659
+ else:
660
+ raise ValueError(
661
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
662
+ )
663
+ inputs = tokenizer(
664
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
665
+ )
666
+ return inputs.input_ids
667
+
668
+ # Preprocessing the datasets.
669
+ train_transforms = transforms.Compose(
670
+ [
671
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
672
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
673
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
674
+ transforms.ToTensor(),
675
+ transforms.Normalize([0.5], [0.5]),
676
+ ]
677
+ )
678
+
679
+ def preprocess_train(examples):
680
+ images = [image.convert("RGB") for image in examples[image_column]]
681
+ examples["pixel_values"] = [train_transforms(image) for image in images]
682
+ examples["input_ids"] = tokenize_captions(examples)
683
+ return examples
684
+
685
+ with accelerator.main_process_first():
686
+ if args.max_train_samples is not None:
687
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
688
+ # Set the training transforms
689
+ train_dataset = dataset["train"].with_transform(preprocess_train)
690
+
691
+ def collate_fn(examples):
692
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
693
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
694
+ input_ids = torch.stack([example["input_ids"] for example in examples])
695
+ return {"pixel_values": pixel_values, "input_ids": input_ids}
696
+
697
+ # DataLoaders creation:
698
+ train_dataloader = torch.utils.data.DataLoader(
699
+ train_dataset,
700
+ shuffle=True,
701
+ collate_fn=collate_fn,
702
+ batch_size=args.train_batch_size,
703
+ num_workers=args.dataloader_num_workers,
704
+ )
705
+
706
+ # Scheduler and math around the number of training steps.
707
+ overrode_max_train_steps = False
708
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
709
+ if args.max_train_steps is None:
710
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
711
+ overrode_max_train_steps = True
712
+
713
+ lr_scheduler = get_scheduler(
714
+ args.lr_scheduler,
715
+ optimizer=optimizer,
716
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
717
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
718
+ )
719
+
720
+ # Prepare everything with our `accelerator`.
721
+ if args.use_peft:
722
+ if args.train_text_encoder:
723
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
724
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
725
+ )
726
+ else:
727
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
728
+ unet, optimizer, train_dataloader, lr_scheduler
729
+ )
730
+ else:
731
+ lora_layers, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
732
+ lora_layers, optimizer, train_dataloader, lr_scheduler
733
+ )
734
+
735
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
736
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
737
+ if overrode_max_train_steps:
738
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
739
+ # Afterwards we recalculate our number of training epochs
740
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
741
+
742
+ # We need to initialize the trackers we use, and also store our configuration.
743
+ # The trackers initializes automatically on the main process.
744
+ if accelerator.is_main_process:
745
+ accelerator.init_trackers("text2image-fine-tune", config=vars(args))
746
+
747
+ # Train!
748
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
749
+
750
+ logger.info("***** Running training *****")
751
+ logger.info(f" Num examples = {len(train_dataset)}")
752
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
753
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
754
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
755
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
756
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
757
+ global_step = 0
758
+ first_epoch = 0
759
+
760
+ # Potentially load in the weights and states from a previous save
761
+ if args.resume_from_checkpoint:
762
+ if args.resume_from_checkpoint != "latest":
763
+ path = os.path.basename(args.resume_from_checkpoint)
764
+ else:
765
+ # Get the most recent checkpoint
766
+ dirs = os.listdir(args.output_dir)
767
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
768
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
769
+ path = dirs[-1] if len(dirs) > 0 else None
770
+
771
+ if path is None:
772
+ accelerator.print(
773
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
774
+ )
775
+ args.resume_from_checkpoint = None
776
+ else:
777
+ accelerator.print(f"Resuming from checkpoint {path}")
778
+ accelerator.load_state(os.path.join(args.output_dir, path))
779
+ global_step = int(path.split("-")[1])
780
+
781
+ resume_global_step = global_step * args.gradient_accumulation_steps
782
+ first_epoch = global_step // num_update_steps_per_epoch
783
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
784
+
785
+ # Only show the progress bar once on each machine.
786
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
787
+ progress_bar.set_description("Steps")
788
+
789
+ for epoch in range(first_epoch, args.num_train_epochs):
790
+ unet.train()
791
+ if args.train_text_encoder:
792
+ text_encoder.train()
793
+ train_loss = 0.0
794
+ for step, batch in enumerate(train_dataloader):
795
+ # Skip steps until we reach the resumed step
796
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
797
+ if step % args.gradient_accumulation_steps == 0:
798
+ progress_bar.update(1)
799
+ continue
800
+
801
+ with accelerator.accumulate(unet):
802
+ # Convert images to latent space
803
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
804
+ latents = latents * vae.config.scaling_factor
805
+
806
+ # Sample noise that we'll add to the latents
807
+ noise = torch.randn_like(latents)
808
+ bsz = latents.shape[0]
809
+ # Sample a random timestep for each image
810
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
811
+ timesteps = timesteps.long()
812
+
813
+ # Add noise to the latents according to the noise magnitude at each timestep
814
+ # (this is the forward diffusion process)
815
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
816
+
817
+ # Get the text embedding for conditioning
818
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
819
+
820
+ # Get the target for loss depending on the prediction type
821
+ if noise_scheduler.config.prediction_type == "epsilon":
822
+ target = noise
823
+ elif noise_scheduler.config.prediction_type == "v_prediction":
824
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
825
+ else:
826
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
827
+
828
+ # Predict the noise residual and compute loss
829
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
830
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
831
+
832
+ # Gather the losses across all processes for logging (if we use distributed training).
833
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
834
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
835
+
836
+ # Backpropagate
837
+ accelerator.backward(loss)
838
+ if accelerator.sync_gradients:
839
+ if args.use_peft:
840
+ params_to_clip = (
841
+ itertools.chain(unet.parameters(), text_encoder.parameters())
842
+ if args.train_text_encoder
843
+ else unet.parameters()
844
+ )
845
+ else:
846
+ params_to_clip = lora_layers.parameters()
847
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
848
+ optimizer.step()
849
+ lr_scheduler.step()
850
+ optimizer.zero_grad()
851
+
852
+ # Checks if the accelerator has performed an optimization step behind the scenes
853
+ if accelerator.sync_gradients:
854
+ progress_bar.update(1)
855
+ global_step += 1
856
+ accelerator.log({"train_loss": train_loss}, step=global_step)
857
+ train_loss = 0.0
858
+
859
+ if global_step % args.checkpointing_steps == 0:
860
+ if accelerator.is_main_process:
861
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
862
+ accelerator.save_state(save_path)
863
+ logger.info(f"Saved state to {save_path}")
864
+
865
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
866
+ progress_bar.set_postfix(**logs)
867
+
868
+ if global_step >= args.max_train_steps:
869
+ break
870
+
871
+ if accelerator.is_main_process:
872
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
873
+ logger.info(
874
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
875
+ f" {args.validation_prompt}."
876
+ )
877
+ # create pipeline
878
+ pipeline = DiffusionPipeline.from_pretrained(
879
+ args.pretrained_model_name_or_path,
880
+ unet=accelerator.unwrap_model(unet),
881
+ text_encoder=accelerator.unwrap_model(text_encoder),
882
+ revision=args.revision,
883
+ torch_dtype=weight_dtype,
884
+ )
885
+ pipeline = pipeline.to(accelerator.device)
886
+ pipeline.set_progress_bar_config(disable=True)
887
+
888
+ # run inference
889
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
890
+ images = []
891
+ for _ in range(args.num_validation_images):
892
+ images.append(
893
+ pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0]
894
+ )
895
+
896
+ if accelerator.is_main_process:
897
+ for tracker in accelerator.trackers:
898
+ if tracker.name == "tensorboard":
899
+ np_images = np.stack([np.asarray(img) for img in images])
900
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
901
+ if tracker.name == "wandb":
902
+ tracker.log(
903
+ {
904
+ "validation": [
905
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
906
+ for i, image in enumerate(images)
907
+ ]
908
+ }
909
+ )
910
+
911
+ del pipeline
912
+ torch.cuda.empty_cache()
913
+
914
+ # Save the lora layers
915
+ accelerator.wait_for_everyone()
916
+ if accelerator.is_main_process:
917
+ if args.use_peft:
918
+ lora_config = {}
919
+ unwarpped_unet = accelerator.unwrap_model(unet)
920
+ state_dict = get_peft_model_state_dict(unwarpped_unet, state_dict=accelerator.get_state_dict(unet))
921
+ lora_config["peft_config"] = unwarpped_unet.get_peft_config_as_dict(inference=True)
922
+ if args.train_text_encoder:
923
+ unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
924
+ text_encoder_state_dict = get_peft_model_state_dict(
925
+ unwarpped_text_encoder, state_dict=accelerator.get_state_dict(text_encoder)
926
+ )
927
+ text_encoder_state_dict = {f"text_encoder_{k}": v for k, v in text_encoder_state_dict.items()}
928
+ state_dict.update(text_encoder_state_dict)
929
+ lora_config["text_encoder_peft_config"] = unwarpped_text_encoder.get_peft_config_as_dict(
930
+ inference=True
931
+ )
932
+
933
+ accelerator.save(state_dict, os.path.join(args.output_dir, f"{global_step}_lora.pt"))
934
+ with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "w") as f:
935
+ json.dump(lora_config, f)
936
+ else:
937
+ unet = unet.to(torch.float32)
938
+ unet.save_attn_procs(args.output_dir)
939
+
940
+ if args.push_to_hub:
941
+ save_model_card(
942
+ repo_id,
943
+ images=images,
944
+ base_model=args.pretrained_model_name_or_path,
945
+ dataset_name=args.dataset_name,
946
+ repo_folder=args.output_dir,
947
+ )
948
+ upload_folder(
949
+ repo_id=repo_id,
950
+ folder_path=args.output_dir,
951
+ commit_message="End of training",
952
+ ignore_patterns=["step_*", "epoch_*"],
953
+ )
954
+
955
+ # Final inference
956
+ # Load previous pipeline
957
+ pipeline = DiffusionPipeline.from_pretrained(
958
+ args.pretrained_model_name_or_path, revision=args.revision, torch_dtype=weight_dtype
959
+ )
960
+
961
+ if args.use_peft:
962
+
963
+ def load_and_set_lora_ckpt(pipe, ckpt_dir, global_step, device, dtype):
964
+ with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "r") as f:
965
+ lora_config = json.load(f)
966
+ print(lora_config)
967
+
968
+ checkpoint = os.path.join(args.output_dir, f"{global_step}_lora.pt")
969
+ lora_checkpoint_sd = torch.load(checkpoint)
970
+ unet_lora_ds = {k: v for k, v in lora_checkpoint_sd.items() if "text_encoder_" not in k}
971
+ text_encoder_lora_ds = {
972
+ k.replace("text_encoder_", ""): v for k, v in lora_checkpoint_sd.items() if "text_encoder_" in k
973
+ }
974
+
975
+ unet_config = LoraConfig(**lora_config["peft_config"])
976
+ pipe.unet = LoraModel(unet_config, pipe.unet)
977
+ set_peft_model_state_dict(pipe.unet, unet_lora_ds)
978
+
979
+ if "text_encoder_peft_config" in lora_config:
980
+ text_encoder_config = LoraConfig(**lora_config["text_encoder_peft_config"])
981
+ pipe.text_encoder = LoraModel(text_encoder_config, pipe.text_encoder)
982
+ set_peft_model_state_dict(pipe.text_encoder, text_encoder_lora_ds)
983
+
984
+ if dtype in (torch.float16, torch.bfloat16):
985
+ pipe.unet.half()
986
+ pipe.text_encoder.half()
987
+
988
+ pipe.to(device)
989
+ return pipe
990
+
991
+ pipeline = load_and_set_lora_ckpt(pipeline, args.output_dir, global_step, accelerator.device, weight_dtype)
992
+
993
+ else:
994
+ pipeline = pipeline.to(accelerator.device)
995
+ # load attention processors
996
+ pipeline.unet.load_attn_procs(args.output_dir)
997
+
998
+ # run inference
999
+ if args.seed is not None:
1000
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
1001
+ else:
1002
+ generator = None
1003
+ images = []
1004
+ for _ in range(args.num_validation_images):
1005
+ images.append(pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0])
1006
+
1007
+ if accelerator.is_main_process:
1008
+ for tracker in accelerator.trackers:
1009
+ if tracker.name == "tensorboard":
1010
+ np_images = np.stack([np.asarray(img) for img in images])
1011
+ tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC")
1012
+ if tracker.name == "wandb":
1013
+ tracker.log(
1014
+ {
1015
+ "test": [
1016
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1017
+ for i, image in enumerate(images)
1018
+ ]
1019
+ }
1020
+ )
1021
+
1022
+ accelerator.end_training()
1023
+
1024
+
1025
+ if __name__ == "__main__":
1026
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/README.md ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi Subject DreamBooth training
2
+
3
+ [DreamBooth](https://huggingface.co/papers/2208.12242) is a method to personalize text2image models like stable diffusion given just a few(3~5) images of a subject.
4
+ This `train_multi_subject_dreambooth.py` script shows how to implement the training procedure for one or more subjects and adapt it for stable diffusion. Note that this code is based off of the `examples/dreambooth/train_dreambooth.py` script as of 01/06/2022.
5
+
6
+ This script was added by @kopsahlong, and is not actively maintained. However, if you come across anything that could use fixing, feel free to open an issue and tag @kopsahlong.
7
+
8
+ ## Running locally with PyTorch
9
+ ### Installing the dependencies
10
+
11
+ Before running the script, make sure to install the library's training dependencies:
12
+
13
+ To start, 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 -e .
18
+ ```
19
+
20
+ Then cd into the folder `diffusers/examples/research_projects/multi_subject_dreambooth` and run the following:
21
+ ```bash
22
+ pip install -r requirements.txt
23
+ ```
24
+
25
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
26
+
27
+ ```bash
28
+ accelerate config
29
+ ```
30
+
31
+ Or for a default accelerate configuration without answering questions about your environment
32
+
33
+ ```bash
34
+ accelerate config default
35
+ ```
36
+
37
+ Or if your environment doesn't support an interactive shell e.g. a notebook
38
+
39
+ ```python
40
+ from accelerate.utils import write_basic_config
41
+ write_basic_config()
42
+ ```
43
+
44
+ ### Multi Subject Training Example
45
+ In order to have your model learn multiple concepts at once, we simply add in the additional data directories and prompts to our `instance_data_dir` and `instance_prompt` (as well as `class_data_dir` and `class_prompt` if `--with_prior_preservation` is specified) as one comma separated string.
46
+
47
+ See an example with 2 subjects below, which learns a model for one dog subject and one human subject:
48
+
49
+ ```bash
50
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
51
+ export OUTPUT_DIR="path-to-save-model"
52
+
53
+ # Subject 1
54
+ export INSTANCE_DIR_1="path-to-instance-images-concept-1"
55
+ export INSTANCE_PROMPT_1="a photo of a sks dog"
56
+ export CLASS_DIR_1="path-to-class-images-dog"
57
+ export CLASS_PROMPT_1="a photo of a dog"
58
+
59
+ # Subject 2
60
+ export INSTANCE_DIR_2="path-to-instance-images-concept-2"
61
+ export INSTANCE_PROMPT_2="a photo of a t@y person"
62
+ export CLASS_DIR_2="path-to-class-images-person"
63
+ export CLASS_PROMPT_2="a photo of a person"
64
+
65
+ accelerate launch train_multi_subject_dreambooth.py \
66
+ --pretrained_model_name_or_path=$MODEL_NAME \
67
+ --instance_data_dir="$INSTANCE_DIR_1,$INSTANCE_DIR_2" \
68
+ --output_dir=$OUTPUT_DIR \
69
+ --train_text_encoder \
70
+ --instance_prompt="$INSTANCE_PROMPT_1,$INSTANCE_PROMPT_2" \
71
+ --with_prior_preservation \
72
+ --prior_loss_weight=1.0 \
73
+ --class_data_dir="$CLASS_DIR_1,$CLASS_DIR_2" \
74
+ --class_prompt="$CLASS_PROMPT_1,$CLASS_PROMPT_2"\
75
+ --num_class_images=50 \
76
+ --resolution=512 \
77
+ --train_batch_size=1 \
78
+ --gradient_accumulation_steps=1 \
79
+ --learning_rate=1e-6 \
80
+ --lr_scheduler="constant" \
81
+ --lr_warmup_steps=0 \
82
+ --max_train_steps=1500
83
+ ```
84
+
85
+ This example shows training for 2 subjects, but please note that the model can be trained on any number of new concepts. This can be done by continuing to add in the corresponding directories and prompts to the corresponding comma separated string.
86
+
87
+ Note also that in this script, `sks` and `t@y` were used as tokens to learn the new subjects ([this thread](https://github.com/XavierXiao/Dreambooth-Stable-Diffusion/issues/71) inspired the use of `t@y` as our second identifier). However, there may be better rare tokens to experiment with, and results also seemed to be good when more intuitive words are used.
88
+
89
+ **Important**: New parameters are added to the script, making possible to validate the progress of the training by
90
+ generating images at specified steps. Taking also into account that a comma separated list in a text field for a prompt
91
+ it's never a good idea (simply because it is very common in prompts to have them as part of a regular text) we
92
+ introduce the `concept_list` parameter: allowing to specify a json-like file where you can define the different
93
+ configuration for each subject that you want to train.
94
+
95
+ An example of how to generate the file:
96
+ ```python
97
+ import json
98
+
99
+ # here we are using parameters for prior-preservation and validation as well.
100
+ concepts_list = [
101
+ {
102
+ "instance_prompt": "drawing of a t@y meme",
103
+ "class_prompt": "drawing of a meme",
104
+ "instance_data_dir": "/some_folder/meme_toy",
105
+ "class_data_dir": "/data/meme",
106
+ "validation_prompt": "drawing of a t@y meme about football in Uruguay",
107
+ "validation_negative_prompt": "black and white"
108
+ },
109
+ {
110
+ "instance_prompt": "drawing of a sks sir",
111
+ "class_prompt": "drawing of a sir",
112
+ "instance_data_dir": "/some_other_folder/sir_sks",
113
+ "class_data_dir": "/data/sir",
114
+ "validation_prompt": "drawing of a sks sir with the Uruguayan sun in his chest",
115
+ "validation_negative_prompt": "an old man",
116
+ "validation_guidance_scale": 20,
117
+ "validation_number_images": 3,
118
+ "validation_inference_steps": 10
119
+ }
120
+ ]
121
+
122
+ with open("concepts_list.json", "w") as f:
123
+ json.dump(concepts_list, f, indent=4)
124
+ ```
125
+ And then just point to the file when executing the script:
126
+
127
+ ```bash
128
+ # exports...
129
+ accelerate launch train_multi_subject_dreambooth.py \
130
+ # more parameters...
131
+ --concepts_list="concepts_list.json"
132
+ ```
133
+
134
+ You can use the helper from the script to get a better sense of each parameter.
135
+
136
+ ### Inference
137
+
138
+ Once you have trained a model using above command, the inference can be done simply using the `StableDiffusionPipeline`. Make sure to include the `identifier`(e.g. sks in above example) in your prompt.
139
+
140
+ ```python
141
+ from diffusers import StableDiffusionPipeline
142
+ import torch
143
+
144
+ model_id = "path-to-your-trained-model"
145
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
146
+
147
+ prompt = "A photo of a t@y person petting an sks dog"
148
+ image = pipe(prompt, num_inference_steps=200, guidance_scale=7.5).images[0]
149
+
150
+ image.save("person-petting-dog.png")
151
+ ```
152
+
153
+ ### Inference from a training checkpoint
154
+
155
+ You can also perform inference from one of the checkpoints saved during the training process, if you used the `--checkpointing_steps` argument. Please, refer to [the documentation](https://huggingface.co/docs/diffusers/main/en/training/dreambooth#performing-inference-using-a-saved-checkpoint) to see how to do it.
156
+
157
+ ## Additional Dreambooth documentation
158
+ Because the `train_multi_subject_dreambooth.py` script here was forked from an original version of `train_dreambooth.py` in the `examples/dreambooth` folder, I've included the original applicable training documentation for single subject examples below.
159
+
160
+ This should explain how to play with training variables such as prior preservation, fine tuning the text encoder, etc. which is still applicable to our multi subject training code. Note also that the examples below, which are single subject examples, also work with `train_multi_subject_dreambooth.py`, as this script supports 1 (or more) subjects.
161
+
162
+ ### Single subject dog toy example
163
+
164
+ Let's get our dataset. Download images from [here](https://drive.google.com/drive/folders/1BO_dyz-p65qhBRRMRA4TbZ8qW4rB99JZ) and save them in a directory. This will be our training data.
165
+
166
+ And launch the training using
167
+
168
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
169
+
170
+ ```bash
171
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
172
+ export INSTANCE_DIR="path-to-instance-images"
173
+ export OUTPUT_DIR="path-to-save-model"
174
+
175
+ accelerate launch train_dreambooth.py \
176
+ --pretrained_model_name_or_path=$MODEL_NAME \
177
+ --instance_data_dir=$INSTANCE_DIR \
178
+ --output_dir=$OUTPUT_DIR \
179
+ --instance_prompt="a photo of sks dog" \
180
+ --resolution=512 \
181
+ --train_batch_size=1 \
182
+ --gradient_accumulation_steps=1 \
183
+ --learning_rate=5e-6 \
184
+ --lr_scheduler="constant" \
185
+ --lr_warmup_steps=0 \
186
+ --max_train_steps=400
187
+ ```
188
+
189
+ ### Training with prior-preservation loss
190
+
191
+ Prior-preservation is used to avoid overfitting and language-drift. Refer to the paper to learn more about it. For prior-preservation we first generate images using the model with a class prompt and then use those during training along with our data.
192
+ According to the paper, it's recommended to generate `num_epochs * num_samples` images for prior-preservation. 200-300 works well for most cases. The `num_class_images` flag sets the number of images to generate with the class prompt. You can place existing images in `class_data_dir`, and the training script will generate any additional images so that `num_class_images` are present in `class_data_dir` during training time.
193
+
194
+ ```bash
195
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
196
+ export INSTANCE_DIR="path-to-instance-images"
197
+ export CLASS_DIR="path-to-class-images"
198
+ export OUTPUT_DIR="path-to-save-model"
199
+
200
+ accelerate launch train_dreambooth.py \
201
+ --pretrained_model_name_or_path=$MODEL_NAME \
202
+ --instance_data_dir=$INSTANCE_DIR \
203
+ --class_data_dir=$CLASS_DIR \
204
+ --output_dir=$OUTPUT_DIR \
205
+ --with_prior_preservation --prior_loss_weight=1.0 \
206
+ --instance_prompt="a photo of sks dog" \
207
+ --class_prompt="a photo of dog" \
208
+ --resolution=512 \
209
+ --train_batch_size=1 \
210
+ --gradient_accumulation_steps=1 \
211
+ --learning_rate=5e-6 \
212
+ --lr_scheduler="constant" \
213
+ --lr_warmup_steps=0 \
214
+ --num_class_images=200 \
215
+ --max_train_steps=800
216
+ ```
217
+
218
+
219
+ ### Training on a 16GB GPU:
220
+
221
+ With the help of gradient checkpointing and the 8-bit optimizer from bitsandbytes it's possible to run train dreambooth on a 16GB GPU.
222
+
223
+ To install `bitandbytes` please refer to this [readme](https://github.com/TimDettmers/bitsandbytes#requirements--installation).
224
+
225
+ ```bash
226
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
227
+ export INSTANCE_DIR="path-to-instance-images"
228
+ export CLASS_DIR="path-to-class-images"
229
+ export OUTPUT_DIR="path-to-save-model"
230
+
231
+ accelerate launch train_dreambooth.py \
232
+ --pretrained_model_name_or_path=$MODEL_NAME \
233
+ --instance_data_dir=$INSTANCE_DIR \
234
+ --class_data_dir=$CLASS_DIR \
235
+ --output_dir=$OUTPUT_DIR \
236
+ --with_prior_preservation --prior_loss_weight=1.0 \
237
+ --instance_prompt="a photo of sks dog" \
238
+ --class_prompt="a photo of dog" \
239
+ --resolution=512 \
240
+ --train_batch_size=1 \
241
+ --gradient_accumulation_steps=2 --gradient_checkpointing \
242
+ --use_8bit_adam \
243
+ --learning_rate=5e-6 \
244
+ --lr_scheduler="constant" \
245
+ --lr_warmup_steps=0 \
246
+ --num_class_images=200 \
247
+ --max_train_steps=800
248
+ ```
249
+
250
+ ### Training on a 8 GB GPU:
251
+
252
+ By using [DeepSpeed](https://www.deepspeed.ai/) it's possible to offload some
253
+ tensors from VRAM to either CPU or NVME allowing to train with less VRAM.
254
+
255
+ DeepSpeed needs to be enabled with `accelerate config`. During configuration
256
+ answer yes to "Do you want to use DeepSpeed?". With DeepSpeed stage 2, fp16
257
+ mixed precision and offloading both parameters and optimizer state to cpu it's
258
+ possible to train on under 8 GB VRAM with a drawback of requiring significantly
259
+ more RAM (about 25 GB). See [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more DeepSpeed configuration options.
260
+
261
+ Changing the default Adam optimizer to DeepSpeed's special version of Adam
262
+ `deepspeed.ops.adam.DeepSpeedCPUAdam` gives a substantial speedup but enabling
263
+ it requires CUDA toolchain with the same version as pytorch. 8-bit optimizer
264
+ does not seem to be compatible with DeepSpeed at the moment.
265
+
266
+ ```bash
267
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
268
+ export INSTANCE_DIR="path-to-instance-images"
269
+ export CLASS_DIR="path-to-class-images"
270
+ export OUTPUT_DIR="path-to-save-model"
271
+
272
+ accelerate launch --mixed_precision="fp16" train_dreambooth.py \
273
+ --pretrained_model_name_or_path=$MODEL_NAME \
274
+ --instance_data_dir=$INSTANCE_DIR \
275
+ --class_data_dir=$CLASS_DIR \
276
+ --output_dir=$OUTPUT_DIR \
277
+ --with_prior_preservation --prior_loss_weight=1.0 \
278
+ --instance_prompt="a photo of sks dog" \
279
+ --class_prompt="a photo of dog" \
280
+ --resolution=512 \
281
+ --train_batch_size=1 \
282
+ --sample_batch_size=1 \
283
+ --gradient_accumulation_steps=1 --gradient_checkpointing \
284
+ --learning_rate=5e-6 \
285
+ --lr_scheduler="constant" \
286
+ --lr_warmup_steps=0 \
287
+ --num_class_images=200 \
288
+ --max_train_steps=800
289
+ ```
290
+
291
+ ### Fine-tune text encoder with the UNet.
292
+
293
+ The script also allows to fine-tune the `text_encoder` along with the `unet`. It's been observed experimentally that fine-tuning `text_encoder` gives much better results especially on faces.
294
+ Pass the `--train_text_encoder` argument to the script to enable training `text_encoder`.
295
+
296
+ ___Note: Training text encoder requires more memory, with this option the training won't fit on 16GB GPU. It needs at least 24GB VRAM.___
297
+
298
+ ```bash
299
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
300
+ export INSTANCE_DIR="path-to-instance-images"
301
+ export CLASS_DIR="path-to-class-images"
302
+ export OUTPUT_DIR="path-to-save-model"
303
+
304
+ accelerate launch train_dreambooth.py \
305
+ --pretrained_model_name_or_path=$MODEL_NAME \
306
+ --train_text_encoder \
307
+ --instance_data_dir=$INSTANCE_DIR \
308
+ --class_data_dir=$CLASS_DIR \
309
+ --output_dir=$OUTPUT_DIR \
310
+ --with_prior_preservation --prior_loss_weight=1.0 \
311
+ --instance_prompt="a photo of sks dog" \
312
+ --class_prompt="a photo of dog" \
313
+ --resolution=512 \
314
+ --train_batch_size=1 \
315
+ --use_8bit_adam \
316
+ --gradient_checkpointing \
317
+ --learning_rate=2e-6 \
318
+ --lr_scheduler="constant" \
319
+ --lr_warmup_steps=0 \
320
+ --num_class_images=200 \
321
+ --max_train_steps=800
322
+ ```
323
+
324
+ ### Using DreamBooth for other pipelines than Stable Diffusion
325
+
326
+ Altdiffusion also supports dreambooth now, the running command is basically the same as above, all you need to do is replace the `MODEL_NAME` like this:
327
+ One can now simply change the `pretrained_model_name_or_path` to another architecture such as [`AltDiffusion`](https://huggingface.co/docs/diffusers/api/pipelines/alt_diffusion).
328
+
329
+ ```
330
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4" --> export MODEL_NAME="BAAI/AltDiffusion-m9"
331
+ or
332
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4" --> export MODEL_NAME="BAAI/AltDiffusion"
333
+ ```
334
+
335
+ ### Training with xformers:
336
+ 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.
337
+
338
+ You can also use Dreambooth to train the specialized in-painting model. See [the script in the research folder for details](https://github.com/huggingface/diffusers/tree/main/examples/research_projects/dreambooth_inpaint).
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/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-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import json
4
+ import logging
5
+ import math
6
+ import uuid
7
+ import warnings
8
+ from os import environ, listdir, makedirs
9
+ from os.path import basename, join
10
+ from pathlib import Path
11
+ from typing import List
12
+
13
+ import datasets
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn.functional as F
17
+ import torch.utils.checkpoint
18
+ import transformers
19
+ from accelerate import Accelerator
20
+ from accelerate.logging import get_logger
21
+ from accelerate.utils import ProjectConfiguration, set_seed
22
+ from huggingface_hub import create_repo, upload_folder
23
+ from huggingface_hub.utils import insecure_hashlib
24
+ from PIL import Image
25
+ from torch import dtype
26
+ from torch.nn import Module
27
+ from torch.utils.data import Dataset
28
+ from torchvision import transforms
29
+ from tqdm.auto import tqdm
30
+ from transformers import AutoTokenizer, PretrainedConfig
31
+
32
+ import diffusers
33
+ from diffusers import (
34
+ AutoencoderKL,
35
+ DDPMScheduler,
36
+ DiffusionPipeline,
37
+ DPMSolverMultistepScheduler,
38
+ UNet2DConditionModel,
39
+ )
40
+ from diffusers.optimization import get_scheduler
41
+ from diffusers.utils import check_min_version, is_wandb_available
42
+ from diffusers.utils.import_utils import is_xformers_available
43
+
44
+
45
+ if is_wandb_available():
46
+ import wandb
47
+
48
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
49
+ check_min_version("0.13.0.dev0")
50
+
51
+ logger = get_logger(__name__)
52
+
53
+
54
+ def log_validation_images_to_tracker(
55
+ images: List[np.array], label: str, validation_prompt: str, accelerator: Accelerator, epoch: int
56
+ ):
57
+ logger.info(f"Logging images to tracker for validation prompt: {validation_prompt}.")
58
+
59
+ for tracker in accelerator.trackers:
60
+ if tracker.name == "tensorboard":
61
+ np_images = np.stack([np.asarray(img) for img in images])
62
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
63
+ if tracker.name == "wandb":
64
+ tracker.log(
65
+ {
66
+ "validation": [
67
+ wandb.Image(image, caption=f"{label}_{epoch}_{i}: {validation_prompt}")
68
+ for i, image in enumerate(images)
69
+ ]
70
+ }
71
+ )
72
+
73
+
74
+ # TODO: Add `prompt_embeds` and `negative_prompt_embeds` parameters to the function when `pre_compute_text_embeddings`
75
+ # argument is implemented.
76
+ def generate_validation_images(
77
+ text_encoder: Module,
78
+ tokenizer: Module,
79
+ unet: Module,
80
+ vae: Module,
81
+ arguments: argparse.Namespace,
82
+ accelerator: Accelerator,
83
+ weight_dtype: dtype,
84
+ ):
85
+ logger.info("Running validation images.")
86
+
87
+ pipeline_args = {}
88
+
89
+ if text_encoder is not None:
90
+ pipeline_args["text_encoder"] = accelerator.unwrap_model(text_encoder)
91
+
92
+ if vae is not None:
93
+ pipeline_args["vae"] = vae
94
+
95
+ # create pipeline (note: unet and vae are loaded again in float32)
96
+ pipeline = DiffusionPipeline.from_pretrained(
97
+ arguments.pretrained_model_name_or_path,
98
+ tokenizer=tokenizer,
99
+ unet=accelerator.unwrap_model(unet),
100
+ revision=arguments.revision,
101
+ torch_dtype=weight_dtype,
102
+ **pipeline_args,
103
+ )
104
+
105
+ # We train on the simplified learning objective. If we were previously predicting a variance, we need the
106
+ # scheduler to ignore it
107
+ scheduler_args = {}
108
+
109
+ if "variance_type" in pipeline.scheduler.config:
110
+ variance_type = pipeline.scheduler.config.variance_type
111
+
112
+ if variance_type in ["learned", "learned_range"]:
113
+ variance_type = "fixed_small"
114
+
115
+ scheduler_args["variance_type"] = variance_type
116
+
117
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, **scheduler_args)
118
+ pipeline = pipeline.to(accelerator.device)
119
+ pipeline.set_progress_bar_config(disable=True)
120
+
121
+ generator = (
122
+ None if arguments.seed is None else torch.Generator(device=accelerator.device).manual_seed(arguments.seed)
123
+ )
124
+
125
+ images_sets = []
126
+ for vp, nvi, vnp, vis, vgs in zip(
127
+ arguments.validation_prompt,
128
+ arguments.validation_number_images,
129
+ arguments.validation_negative_prompt,
130
+ arguments.validation_inference_steps,
131
+ arguments.validation_guidance_scale,
132
+ ):
133
+ images = []
134
+ if vp is not None:
135
+ logger.info(
136
+ f"Generating {nvi} images with prompt: '{vp}', negative prompt: '{vnp}', inference steps: {vis}, "
137
+ f"guidance scale: {vgs}."
138
+ )
139
+
140
+ pipeline_args = {"prompt": vp, "negative_prompt": vnp, "num_inference_steps": vis, "guidance_scale": vgs}
141
+
142
+ # run inference
143
+ # TODO: it would be good to measure whether it's faster to run inference on all images at once, one at a
144
+ # time or in small batches
145
+ for _ in range(nvi):
146
+ with torch.autocast("cuda"):
147
+ image = pipeline(**pipeline_args, num_images_per_prompt=1, generator=generator).images[0]
148
+ images.append(image)
149
+
150
+ images_sets.append(images)
151
+
152
+ del pipeline
153
+ if torch.cuda.is_available():
154
+ torch.cuda.empty_cache()
155
+
156
+ return images_sets
157
+
158
+
159
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
160
+ text_encoder_config = PretrainedConfig.from_pretrained(
161
+ pretrained_model_name_or_path,
162
+ subfolder="text_encoder",
163
+ revision=revision,
164
+ )
165
+ model_class = text_encoder_config.architectures[0]
166
+
167
+ if model_class == "CLIPTextModel":
168
+ from transformers import CLIPTextModel
169
+
170
+ return CLIPTextModel
171
+ elif model_class == "RobertaSeriesModelWithTransformation":
172
+ from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
173
+
174
+ return RobertaSeriesModelWithTransformation
175
+ else:
176
+ raise ValueError(f"{model_class} is not supported.")
177
+
178
+
179
+ def parse_args(input_args=None):
180
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
181
+ parser.add_argument(
182
+ "--pretrained_model_name_or_path",
183
+ type=str,
184
+ default=None,
185
+ required=True,
186
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
187
+ )
188
+ parser.add_argument(
189
+ "--revision",
190
+ type=str,
191
+ default=None,
192
+ required=False,
193
+ help="Revision of pretrained model identifier from huggingface.co/models.",
194
+ )
195
+ parser.add_argument(
196
+ "--tokenizer_name",
197
+ type=str,
198
+ default=None,
199
+ help="Pretrained tokenizer name or path if not the same as model_name",
200
+ )
201
+ parser.add_argument(
202
+ "--instance_data_dir",
203
+ type=str,
204
+ default=None,
205
+ required=False,
206
+ help="A folder containing the training data of instance images.",
207
+ )
208
+ parser.add_argument(
209
+ "--class_data_dir",
210
+ type=str,
211
+ default=None,
212
+ required=False,
213
+ help="A folder containing the training data of class images.",
214
+ )
215
+ parser.add_argument(
216
+ "--instance_prompt",
217
+ type=str,
218
+ default=None,
219
+ required=False,
220
+ help="The prompt with identifier specifying the instance",
221
+ )
222
+ parser.add_argument(
223
+ "--class_prompt",
224
+ type=str,
225
+ default=None,
226
+ help="The prompt to specify images in the same class as provided instance images.",
227
+ )
228
+ parser.add_argument(
229
+ "--with_prior_preservation",
230
+ default=False,
231
+ action="store_true",
232
+ help="Flag to add prior preservation loss.",
233
+ )
234
+ parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
235
+ parser.add_argument(
236
+ "--num_class_images",
237
+ type=int,
238
+ default=100,
239
+ help=(
240
+ "Minimal class images for prior preservation loss. If there are not enough images already present in"
241
+ " class_data_dir, additional images will be sampled with class_prompt."
242
+ ),
243
+ )
244
+ parser.add_argument(
245
+ "--output_dir",
246
+ type=str,
247
+ default="text-inversion-model",
248
+ help="The output directory where the model predictions and checkpoints will be written.",
249
+ )
250
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
251
+ parser.add_argument(
252
+ "--resolution",
253
+ type=int,
254
+ default=512,
255
+ help=(
256
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
257
+ " resolution"
258
+ ),
259
+ )
260
+ parser.add_argument(
261
+ "--center_crop",
262
+ default=False,
263
+ action="store_true",
264
+ help=(
265
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
266
+ " cropped. The images will be resized to the resolution first before cropping."
267
+ ),
268
+ )
269
+ parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
270
+ parser.add_argument(
271
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
272
+ )
273
+ parser.add_argument(
274
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
275
+ )
276
+ parser.add_argument("--num_train_epochs", type=int, default=1)
277
+ parser.add_argument(
278
+ "--max_train_steps",
279
+ type=int,
280
+ default=None,
281
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
282
+ )
283
+ parser.add_argument(
284
+ "--checkpointing_steps",
285
+ type=int,
286
+ default=500,
287
+ help=(
288
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
289
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
290
+ " training using `--resume_from_checkpoint`."
291
+ ),
292
+ )
293
+ parser.add_argument(
294
+ "--checkpoints_total_limit",
295
+ type=int,
296
+ default=None,
297
+ help=(
298
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
299
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
300
+ " for more docs"
301
+ ),
302
+ )
303
+ parser.add_argument(
304
+ "--resume_from_checkpoint",
305
+ type=str,
306
+ default=None,
307
+ help=(
308
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
309
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
310
+ ),
311
+ )
312
+ parser.add_argument(
313
+ "--gradient_accumulation_steps",
314
+ type=int,
315
+ default=1,
316
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
317
+ )
318
+ parser.add_argument(
319
+ "--gradient_checkpointing",
320
+ action="store_true",
321
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
322
+ )
323
+ parser.add_argument(
324
+ "--learning_rate",
325
+ type=float,
326
+ default=5e-6,
327
+ help="Initial learning rate (after the potential warmup period) to use.",
328
+ )
329
+ parser.add_argument(
330
+ "--scale_lr",
331
+ action="store_true",
332
+ default=False,
333
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
334
+ )
335
+ parser.add_argument(
336
+ "--lr_scheduler",
337
+ type=str,
338
+ default="constant",
339
+ help=(
340
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
341
+ ' "constant", "constant_with_warmup"]'
342
+ ),
343
+ )
344
+ parser.add_argument(
345
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
346
+ )
347
+ parser.add_argument(
348
+ "--lr_num_cycles",
349
+ type=int,
350
+ default=1,
351
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
352
+ )
353
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
354
+ parser.add_argument(
355
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
356
+ )
357
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
358
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
359
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
360
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
361
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
362
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
363
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
364
+ parser.add_argument(
365
+ "--hub_model_id",
366
+ type=str,
367
+ default=None,
368
+ help="The name of the repository to keep in sync with the local `output_dir`.",
369
+ )
370
+ parser.add_argument(
371
+ "--logging_dir",
372
+ type=str,
373
+ default="logs",
374
+ help=(
375
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
376
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
377
+ ),
378
+ )
379
+ parser.add_argument(
380
+ "--allow_tf32",
381
+ action="store_true",
382
+ help=(
383
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
384
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
385
+ ),
386
+ )
387
+ parser.add_argument(
388
+ "--report_to",
389
+ type=str,
390
+ default="tensorboard",
391
+ help=(
392
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
393
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
394
+ ),
395
+ )
396
+ parser.add_argument(
397
+ "--validation_steps",
398
+ type=int,
399
+ default=None,
400
+ help=(
401
+ "Run validation every X steps. Validation consists of running the prompt(s) `validation_prompt` "
402
+ "multiple times (`validation_number_images`) and logging the images."
403
+ ),
404
+ )
405
+ parser.add_argument(
406
+ "--validation_prompt",
407
+ type=str,
408
+ default=None,
409
+ help="A prompt that is used during validation to verify that the model is learning. You can use commas to "
410
+ "define multiple negative prompts. This parameter can be defined also within the file given by "
411
+ "`concepts_list` parameter in the respective subject.",
412
+ )
413
+ parser.add_argument(
414
+ "--validation_number_images",
415
+ type=int,
416
+ default=4,
417
+ help="Number of images that should be generated during validation with the validation parameters given. This "
418
+ "can be defined within the file given by `concepts_list` parameter in the respective subject.",
419
+ )
420
+ parser.add_argument(
421
+ "--validation_negative_prompt",
422
+ type=str,
423
+ default=None,
424
+ help="A negative prompt that is used during validation to verify that the model is learning. You can use commas"
425
+ " to define multiple negative prompts, each one corresponding to a validation prompt. This parameter can "
426
+ "be defined also within the file given by `concepts_list` parameter in the respective subject.",
427
+ )
428
+ parser.add_argument(
429
+ "--validation_inference_steps",
430
+ type=int,
431
+ default=25,
432
+ help="Number of inference steps (denoising steps) to run during validation. This can be defined within the "
433
+ "file given by `concepts_list` parameter in the respective subject.",
434
+ )
435
+ parser.add_argument(
436
+ "--validation_guidance_scale",
437
+ type=float,
438
+ default=7.5,
439
+ help="To control how much the image generation process follows the text prompt. This can be defined within the "
440
+ "file given by `concepts_list` parameter in the respective subject.",
441
+ )
442
+ parser.add_argument(
443
+ "--mixed_precision",
444
+ type=str,
445
+ default=None,
446
+ choices=["no", "fp16", "bf16"],
447
+ help=(
448
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
449
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
450
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
451
+ ),
452
+ )
453
+ parser.add_argument(
454
+ "--prior_generation_precision",
455
+ type=str,
456
+ default=None,
457
+ choices=["no", "fp32", "fp16", "bf16"],
458
+ help=(
459
+ "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
460
+ " 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
461
+ ),
462
+ )
463
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
464
+ parser.add_argument(
465
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
466
+ )
467
+ parser.add_argument(
468
+ "--set_grads_to_none",
469
+ action="store_true",
470
+ help=(
471
+ "Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
472
+ " behaviors, so disable this argument if it causes any problems. More info:"
473
+ " https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
474
+ ),
475
+ )
476
+ parser.add_argument(
477
+ "--concepts_list",
478
+ type=str,
479
+ default=None,
480
+ help="Path to json file containing a list of multiple concepts, will overwrite parameters like instance_prompt,"
481
+ " class_prompt, etc.",
482
+ )
483
+
484
+ if input_args:
485
+ args = parser.parse_args(input_args)
486
+ else:
487
+ args = parser.parse_args()
488
+
489
+ if not args.concepts_list and (not args.instance_data_dir or not args.instance_prompt):
490
+ raise ValueError(
491
+ "You must specify either instance parameters (data directory, prompt, etc.) or use "
492
+ "the `concept_list` parameter and specify them within the file."
493
+ )
494
+
495
+ if args.concepts_list:
496
+ if args.instance_prompt:
497
+ raise ValueError("If you are using `concepts_list` parameter, define the instance prompt within the file.")
498
+ if args.instance_data_dir:
499
+ raise ValueError(
500
+ "If you are using `concepts_list` parameter, define the instance data directory within the file."
501
+ )
502
+ if args.validation_steps and (args.validation_prompt or args.validation_negative_prompt):
503
+ raise ValueError(
504
+ "If you are using `concepts_list` parameter, define validation parameters for "
505
+ "each subject within the file:\n - `validation_prompt`."
506
+ "\n - `validation_negative_prompt`.\n - `validation_guidance_scale`."
507
+ "\n - `validation_number_images`.\n - `validation_prompt`."
508
+ "\n - `validation_inference_steps`.\nThe `validation_steps` parameter is the only one "
509
+ "that needs to be defined outside the file."
510
+ )
511
+
512
+ env_local_rank = int(environ.get("LOCAL_RANK", -1))
513
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
514
+ args.local_rank = env_local_rank
515
+
516
+ if args.with_prior_preservation:
517
+ if not args.concepts_list:
518
+ if not args.class_data_dir:
519
+ raise ValueError("You must specify a data directory for class images.")
520
+ if not args.class_prompt:
521
+ raise ValueError("You must specify prompt for class images.")
522
+ else:
523
+ if args.class_data_dir:
524
+ raise ValueError(
525
+ "If you are using `concepts_list` parameter, define the class data directory within the file."
526
+ )
527
+ if args.class_prompt:
528
+ raise ValueError(
529
+ "If you are using `concepts_list` parameter, define the class prompt within the file."
530
+ )
531
+ else:
532
+ # logger is not available yet
533
+ if not args.class_data_dir:
534
+ warnings.warn(
535
+ "Ignoring `class_data_dir` parameter, you need to use it together with `with_prior_preservation`."
536
+ )
537
+ if not args.class_prompt:
538
+ warnings.warn(
539
+ "Ignoring `class_prompt` parameter, you need to use it together with `with_prior_preservation`."
540
+ )
541
+
542
+ return args
543
+
544
+
545
+ class DreamBoothDataset(Dataset):
546
+ """
547
+ A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
548
+ It pre-processes the images and then tokenizes prompts.
549
+ """
550
+
551
+ def __init__(
552
+ self,
553
+ instance_data_root,
554
+ instance_prompt,
555
+ tokenizer,
556
+ class_data_root=None,
557
+ class_prompt=None,
558
+ size=512,
559
+ center_crop=False,
560
+ ):
561
+ self.size = size
562
+ self.center_crop = center_crop
563
+ self.tokenizer = tokenizer
564
+
565
+ self.instance_data_root = []
566
+ self.instance_images_path = []
567
+ self.num_instance_images = []
568
+ self.instance_prompt = []
569
+ self.class_data_root = [] if class_data_root is not None else None
570
+ self.class_images_path = []
571
+ self.num_class_images = []
572
+ self.class_prompt = []
573
+ self._length = 0
574
+
575
+ for i in range(len(instance_data_root)):
576
+ self.instance_data_root.append(Path(instance_data_root[i]))
577
+ if not self.instance_data_root[i].exists():
578
+ raise ValueError("Instance images root doesn't exists.")
579
+
580
+ self.instance_images_path.append(list(Path(instance_data_root[i]).iterdir()))
581
+ self.num_instance_images.append(len(self.instance_images_path[i]))
582
+ self.instance_prompt.append(instance_prompt[i])
583
+ self._length += self.num_instance_images[i]
584
+
585
+ if class_data_root is not None:
586
+ self.class_data_root.append(Path(class_data_root[i]))
587
+ self.class_data_root[i].mkdir(parents=True, exist_ok=True)
588
+ self.class_images_path.append(list(self.class_data_root[i].iterdir()))
589
+ self.num_class_images.append(len(self.class_images_path))
590
+ if self.num_class_images[i] > self.num_instance_images[i]:
591
+ self._length -= self.num_instance_images[i]
592
+ self._length += self.num_class_images[i]
593
+ self.class_prompt.append(class_prompt[i])
594
+
595
+ self.image_transforms = transforms.Compose(
596
+ [
597
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
598
+ transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
599
+ transforms.ToTensor(),
600
+ transforms.Normalize([0.5], [0.5]),
601
+ ]
602
+ )
603
+
604
+ def __len__(self):
605
+ return self._length
606
+
607
+ def __getitem__(self, index):
608
+ example = {}
609
+ for i in range(len(self.instance_images_path)):
610
+ instance_image = Image.open(self.instance_images_path[i][index % self.num_instance_images[i]])
611
+ if not instance_image.mode == "RGB":
612
+ instance_image = instance_image.convert("RGB")
613
+ example[f"instance_images_{i}"] = self.image_transforms(instance_image)
614
+ example[f"instance_prompt_ids_{i}"] = self.tokenizer(
615
+ self.instance_prompt[i],
616
+ truncation=True,
617
+ padding="max_length",
618
+ max_length=self.tokenizer.model_max_length,
619
+ return_tensors="pt",
620
+ ).input_ids
621
+
622
+ if self.class_data_root:
623
+ for i in range(len(self.class_data_root)):
624
+ class_image = Image.open(self.class_images_path[i][index % self.num_class_images[i]])
625
+ if not class_image.mode == "RGB":
626
+ class_image = class_image.convert("RGB")
627
+ example[f"class_images_{i}"] = self.image_transforms(class_image)
628
+ example[f"class_prompt_ids_{i}"] = self.tokenizer(
629
+ self.class_prompt[i],
630
+ truncation=True,
631
+ padding="max_length",
632
+ max_length=self.tokenizer.model_max_length,
633
+ return_tensors="pt",
634
+ ).input_ids
635
+
636
+ return example
637
+
638
+
639
+ def collate_fn(num_instances, examples, with_prior_preservation=False):
640
+ input_ids = []
641
+ pixel_values = []
642
+
643
+ for i in range(num_instances):
644
+ input_ids += [example[f"instance_prompt_ids_{i}"] for example in examples]
645
+ pixel_values += [example[f"instance_images_{i}"] for example in examples]
646
+
647
+ # Concat class and instance examples for prior preservation.
648
+ # We do this to avoid doing two forward passes.
649
+ if with_prior_preservation:
650
+ for i in range(num_instances):
651
+ input_ids += [example[f"class_prompt_ids_{i}"] for example in examples]
652
+ pixel_values += [example[f"class_images_{i}"] for example in examples]
653
+
654
+ pixel_values = torch.stack(pixel_values)
655
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
656
+
657
+ input_ids = torch.cat(input_ids, dim=0)
658
+
659
+ batch = {
660
+ "input_ids": input_ids,
661
+ "pixel_values": pixel_values,
662
+ }
663
+ return batch
664
+
665
+
666
+ class PromptDataset(Dataset):
667
+ """A simple dataset to prepare the prompts to generate class images on multiple GPUs."""
668
+
669
+ def __init__(self, prompt, num_samples):
670
+ self.prompt = prompt
671
+ self.num_samples = num_samples
672
+
673
+ def __len__(self):
674
+ return self.num_samples
675
+
676
+ def __getitem__(self, index):
677
+ example = {}
678
+ example["prompt"] = self.prompt
679
+ example["index"] = index
680
+ return example
681
+
682
+
683
+ def main(args):
684
+ if args.report_to == "wandb" and args.hub_token is not None:
685
+ raise ValueError(
686
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
687
+ " Please use `hf auth login` to authenticate with the Hub."
688
+ )
689
+
690
+ logging_dir = Path(args.output_dir, args.logging_dir)
691
+ accelerator_project_config = ProjectConfiguration(
692
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
693
+ )
694
+ accelerator = Accelerator(
695
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
696
+ mixed_precision=args.mixed_precision,
697
+ log_with=args.report_to,
698
+ project_config=accelerator_project_config,
699
+ )
700
+
701
+ # Disable AMP for MPS.
702
+ if torch.backends.mps.is_available():
703
+ accelerator.native_amp = False
704
+
705
+ if args.report_to == "wandb":
706
+ if not is_wandb_available():
707
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
708
+
709
+ # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
710
+ # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
711
+ # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
712
+ if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
713
+ raise ValueError(
714
+ "Gradient accumulation is not supported when training the text encoder in distributed training. "
715
+ "Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
716
+ )
717
+
718
+ instance_data_dir = []
719
+ instance_prompt = []
720
+ class_data_dir = [] if args.with_prior_preservation else None
721
+ class_prompt = [] if args.with_prior_preservation else None
722
+ if args.concepts_list:
723
+ with open(args.concepts_list, "r") as f:
724
+ concepts_list = json.load(f)
725
+
726
+ if args.validation_steps:
727
+ args.validation_prompt = []
728
+ args.validation_number_images = []
729
+ args.validation_negative_prompt = []
730
+ args.validation_inference_steps = []
731
+ args.validation_guidance_scale = []
732
+
733
+ for concept in concepts_list:
734
+ instance_data_dir.append(concept["instance_data_dir"])
735
+ instance_prompt.append(concept["instance_prompt"])
736
+
737
+ if args.with_prior_preservation:
738
+ try:
739
+ class_data_dir.append(concept["class_data_dir"])
740
+ class_prompt.append(concept["class_prompt"])
741
+ except KeyError:
742
+ raise KeyError(
743
+ "`class_data_dir` or `class_prompt` not found in concepts_list while using "
744
+ "`with_prior_preservation`."
745
+ )
746
+ else:
747
+ if "class_data_dir" in concept:
748
+ warnings.warn(
749
+ "Ignoring `class_data_dir` key, to use it you need to enable `with_prior_preservation`."
750
+ )
751
+ if "class_prompt" in concept:
752
+ warnings.warn(
753
+ "Ignoring `class_prompt` key, to use it you need to enable `with_prior_preservation`."
754
+ )
755
+
756
+ if args.validation_steps:
757
+ args.validation_prompt.append(concept.get("validation_prompt", None))
758
+ args.validation_number_images.append(concept.get("validation_number_images", 4))
759
+ args.validation_negative_prompt.append(concept.get("validation_negative_prompt", None))
760
+ args.validation_inference_steps.append(concept.get("validation_inference_steps", 25))
761
+ args.validation_guidance_scale.append(concept.get("validation_guidance_scale", 7.5))
762
+ else:
763
+ # Parse instance and class inputs, and double check that lengths match
764
+ instance_data_dir = args.instance_data_dir.split(",")
765
+ instance_prompt = args.instance_prompt.split(",")
766
+ assert all(x == len(instance_data_dir) for x in [len(instance_data_dir), len(instance_prompt)]), (
767
+ "Instance data dir and prompt inputs are not of the same length."
768
+ )
769
+
770
+ if args.with_prior_preservation:
771
+ class_data_dir = args.class_data_dir.split(",")
772
+ class_prompt = args.class_prompt.split(",")
773
+ assert all(
774
+ x == len(instance_data_dir)
775
+ for x in [len(instance_data_dir), len(instance_prompt), len(class_data_dir), len(class_prompt)]
776
+ ), "Instance & class data dir or prompt inputs are not of the same length."
777
+
778
+ if args.validation_steps:
779
+ validation_prompts = args.validation_prompt.split(",")
780
+ num_of_validation_prompts = len(validation_prompts)
781
+ args.validation_prompt = validation_prompts
782
+ args.validation_number_images = [args.validation_number_images] * num_of_validation_prompts
783
+
784
+ negative_validation_prompts = [None] * num_of_validation_prompts
785
+ if args.validation_negative_prompt:
786
+ negative_validation_prompts = args.validation_negative_prompt.split(",")
787
+ while len(negative_validation_prompts) < num_of_validation_prompts:
788
+ negative_validation_prompts.append(None)
789
+ args.validation_negative_prompt = negative_validation_prompts
790
+
791
+ assert num_of_validation_prompts == len(negative_validation_prompts), (
792
+ "The length of negative prompts for validation is greater than the number of validation prompts."
793
+ )
794
+ args.validation_inference_steps = [args.validation_inference_steps] * num_of_validation_prompts
795
+ args.validation_guidance_scale = [args.validation_guidance_scale] * num_of_validation_prompts
796
+
797
+ # Make one log on every process with the configuration for debugging.
798
+ logging.basicConfig(
799
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
800
+ datefmt="%m/%d/%Y %H:%M:%S",
801
+ level=logging.INFO,
802
+ )
803
+ logger.info(accelerator.state, main_process_only=False)
804
+ if accelerator.is_local_main_process:
805
+ datasets.utils.logging.set_verbosity_warning()
806
+ transformers.utils.logging.set_verbosity_warning()
807
+ diffusers.utils.logging.set_verbosity_info()
808
+ else:
809
+ datasets.utils.logging.set_verbosity_error()
810
+ transformers.utils.logging.set_verbosity_error()
811
+ diffusers.utils.logging.set_verbosity_error()
812
+
813
+ # If passed along, set the training seed now.
814
+ if args.seed is not None:
815
+ set_seed(args.seed)
816
+
817
+ # Generate class images if prior preservation is enabled.
818
+ if args.with_prior_preservation:
819
+ for i in range(len(class_data_dir)):
820
+ class_images_dir = Path(class_data_dir[i])
821
+ if not class_images_dir.exists():
822
+ class_images_dir.mkdir(parents=True)
823
+ cur_class_images = len(list(class_images_dir.iterdir()))
824
+
825
+ if cur_class_images < args.num_class_images:
826
+ torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32
827
+ if args.prior_generation_precision == "fp32":
828
+ torch_dtype = torch.float32
829
+ elif args.prior_generation_precision == "fp16":
830
+ torch_dtype = torch.float16
831
+ elif args.prior_generation_precision == "bf16":
832
+ torch_dtype = torch.bfloat16
833
+ pipeline = DiffusionPipeline.from_pretrained(
834
+ args.pretrained_model_name_or_path,
835
+ torch_dtype=torch_dtype,
836
+ safety_checker=None,
837
+ revision=args.revision,
838
+ )
839
+ pipeline.set_progress_bar_config(disable=True)
840
+
841
+ num_new_images = args.num_class_images - cur_class_images
842
+ logger.info(f"Number of class images to sample: {num_new_images}.")
843
+
844
+ sample_dataset = PromptDataset(class_prompt[i], num_new_images)
845
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
846
+
847
+ sample_dataloader = accelerator.prepare(sample_dataloader)
848
+ pipeline.to(accelerator.device)
849
+
850
+ for example in tqdm(
851
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
852
+ ):
853
+ images = pipeline(example["prompt"]).images
854
+
855
+ for ii, image in enumerate(images):
856
+ hash_image = insecure_hashlib.sha1(image.tobytes()).hexdigest()
857
+ image_filename = (
858
+ class_images_dir / f"{example['index'][ii] + cur_class_images}-{hash_image}.jpg"
859
+ )
860
+ image.save(image_filename)
861
+
862
+ # Clean up the memory deleting one-time-use variables.
863
+ del pipeline
864
+ del sample_dataloader
865
+ del sample_dataset
866
+ if torch.cuda.is_available():
867
+ torch.cuda.empty_cache()
868
+
869
+ # Handle the repository creation
870
+ if accelerator.is_main_process:
871
+ if args.output_dir is not None:
872
+ makedirs(args.output_dir, exist_ok=True)
873
+
874
+ if args.push_to_hub:
875
+ repo_id = create_repo(
876
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
877
+ ).repo_id
878
+
879
+ # Load the tokenizer
880
+ tokenizer = None
881
+ if args.tokenizer_name:
882
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
883
+ elif args.pretrained_model_name_or_path:
884
+ tokenizer = AutoTokenizer.from_pretrained(
885
+ args.pretrained_model_name_or_path,
886
+ subfolder="tokenizer",
887
+ revision=args.revision,
888
+ use_fast=False,
889
+ )
890
+
891
+ # import correct text encoder class
892
+ text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
893
+
894
+ # Load scheduler and models
895
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
896
+ text_encoder = text_encoder_cls.from_pretrained(
897
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
898
+ )
899
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
900
+ unet = UNet2DConditionModel.from_pretrained(
901
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
902
+ )
903
+
904
+ vae.requires_grad_(False)
905
+ if not args.train_text_encoder:
906
+ text_encoder.requires_grad_(False)
907
+
908
+ if args.enable_xformers_memory_efficient_attention:
909
+ if is_xformers_available():
910
+ unet.enable_xformers_memory_efficient_attention()
911
+ else:
912
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
913
+
914
+ if args.gradient_checkpointing:
915
+ unet.enable_gradient_checkpointing()
916
+ if args.train_text_encoder:
917
+ text_encoder.gradient_checkpointing_enable()
918
+
919
+ # Enable TF32 for faster training on Ampere GPUs,
920
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
921
+ if args.allow_tf32:
922
+ torch.backends.cuda.matmul.allow_tf32 = True
923
+
924
+ if args.scale_lr:
925
+ args.learning_rate = (
926
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
927
+ )
928
+
929
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
930
+ if args.use_8bit_adam:
931
+ try:
932
+ import bitsandbytes as bnb
933
+ except ImportError:
934
+ raise ImportError(
935
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
936
+ )
937
+
938
+ optimizer_class = bnb.optim.AdamW8bit
939
+ else:
940
+ optimizer_class = torch.optim.AdamW
941
+
942
+ # Optimizer creation
943
+ params_to_optimize = (
944
+ itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
945
+ )
946
+ optimizer = optimizer_class(
947
+ params_to_optimize,
948
+ lr=args.learning_rate,
949
+ betas=(args.adam_beta1, args.adam_beta2),
950
+ weight_decay=args.adam_weight_decay,
951
+ eps=args.adam_epsilon,
952
+ )
953
+
954
+ # Dataset and DataLoaders creation:
955
+ train_dataset = DreamBoothDataset(
956
+ instance_data_root=instance_data_dir,
957
+ instance_prompt=instance_prompt,
958
+ class_data_root=class_data_dir,
959
+ class_prompt=class_prompt,
960
+ tokenizer=tokenizer,
961
+ size=args.resolution,
962
+ center_crop=args.center_crop,
963
+ )
964
+
965
+ train_dataloader = torch.utils.data.DataLoader(
966
+ train_dataset,
967
+ batch_size=args.train_batch_size,
968
+ shuffle=True,
969
+ collate_fn=lambda examples: collate_fn(len(instance_data_dir), examples, args.with_prior_preservation),
970
+ num_workers=1,
971
+ )
972
+
973
+ # Scheduler and math around the number of training steps.
974
+ overrode_max_train_steps = False
975
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
976
+ if args.max_train_steps is None:
977
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
978
+ overrode_max_train_steps = True
979
+
980
+ lr_scheduler = get_scheduler(
981
+ args.lr_scheduler,
982
+ optimizer=optimizer,
983
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
984
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
985
+ num_cycles=args.lr_num_cycles,
986
+ power=args.lr_power,
987
+ )
988
+
989
+ # Prepare everything with our `accelerator`.
990
+ if args.train_text_encoder:
991
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
992
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
993
+ )
994
+ else:
995
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
996
+ unet, optimizer, train_dataloader, lr_scheduler
997
+ )
998
+
999
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
1000
+ # as these models are only used for inference, keeping weights in full precision is not required.
1001
+ weight_dtype = torch.float32
1002
+ if accelerator.mixed_precision == "fp16":
1003
+ weight_dtype = torch.float16
1004
+ elif accelerator.mixed_precision == "bf16":
1005
+ weight_dtype = torch.bfloat16
1006
+
1007
+ # Move vae and text_encoder to device and cast to weight_dtype
1008
+ vae.to(accelerator.device, dtype=weight_dtype)
1009
+ if not args.train_text_encoder:
1010
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
1011
+
1012
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1013
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1014
+ if overrode_max_train_steps:
1015
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1016
+ # Afterwards we recalculate our number of training epochs
1017
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1018
+
1019
+ # We need to initialize the trackers we use, and also store our configuration.
1020
+ # The trackers initialize automatically on the main process.
1021
+ if accelerator.is_main_process:
1022
+ accelerator.init_trackers("dreambooth", config=vars(args))
1023
+
1024
+ # Train!
1025
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1026
+
1027
+ logger.info("***** Running training *****")
1028
+ logger.info(f" Num examples = {len(train_dataset)}")
1029
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
1030
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1031
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1032
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1033
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1034
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1035
+ global_step = 0
1036
+ first_epoch = 0
1037
+
1038
+ # Potentially load in the weights and states from a previous save
1039
+ if args.resume_from_checkpoint:
1040
+ if args.resume_from_checkpoint != "latest":
1041
+ path = basename(args.resume_from_checkpoint)
1042
+ else:
1043
+ # Get the mos recent checkpoint
1044
+ dirs = listdir(args.output_dir)
1045
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1046
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1047
+ path = dirs[-1] if len(dirs) > 0 else None
1048
+
1049
+ if path is None:
1050
+ accelerator.print(
1051
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1052
+ )
1053
+ args.resume_from_checkpoint = None
1054
+ else:
1055
+ accelerator.print(f"Resuming from checkpoint {path}")
1056
+ accelerator.load_state(join(args.output_dir, path))
1057
+ global_step = int(path.split("-")[1])
1058
+
1059
+ resume_global_step = global_step * args.gradient_accumulation_steps
1060
+ first_epoch = global_step // num_update_steps_per_epoch
1061
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
1062
+
1063
+ # Only show the progress bar once on each machine.
1064
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
1065
+ progress_bar.set_description("Steps")
1066
+
1067
+ for epoch in range(first_epoch, args.num_train_epochs):
1068
+ unet.train()
1069
+ if args.train_text_encoder:
1070
+ text_encoder.train()
1071
+ for step, batch in enumerate(train_dataloader):
1072
+ # Skip steps until we reach the resumed step
1073
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
1074
+ if step % args.gradient_accumulation_steps == 0:
1075
+ progress_bar.update(1)
1076
+ continue
1077
+
1078
+ with accelerator.accumulate(unet):
1079
+ # Convert images to latent space
1080
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
1081
+ latents = latents * vae.config.scaling_factor
1082
+
1083
+ # Sample noise that we'll add to the latents
1084
+ noise = torch.randn_like(latents)
1085
+ bsz = latents.shape[0]
1086
+ # Sample a random timestep for each image
1087
+ time_steps = torch.randint(
1088
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
1089
+ )
1090
+ time_steps = time_steps.long()
1091
+
1092
+ # Add noise to the latents according to the noise magnitude at each timestep
1093
+ # (this is the forward diffusion process)
1094
+ noisy_latents = noise_scheduler.add_noise(latents, noise, time_steps)
1095
+
1096
+ # Get the text embedding for conditioning
1097
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
1098
+
1099
+ # Predict the noise residual
1100
+ model_pred = unet(noisy_latents, time_steps, encoder_hidden_states).sample
1101
+
1102
+ # Get the target for loss depending on the prediction type
1103
+ if noise_scheduler.config.prediction_type == "epsilon":
1104
+ target = noise
1105
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1106
+ target = noise_scheduler.get_velocity(latents, noise, time_steps)
1107
+ else:
1108
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1109
+
1110
+ if args.with_prior_preservation:
1111
+ # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
1112
+ model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
1113
+ target, target_prior = torch.chunk(target, 2, dim=0)
1114
+
1115
+ # Compute instance loss
1116
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1117
+
1118
+ # Compute prior loss
1119
+ prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
1120
+
1121
+ # Add the prior loss to the instance loss.
1122
+ loss = loss + args.prior_loss_weight * prior_loss
1123
+ else:
1124
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1125
+
1126
+ accelerator.backward(loss)
1127
+ if accelerator.sync_gradients:
1128
+ params_to_clip = (
1129
+ itertools.chain(unet.parameters(), text_encoder.parameters())
1130
+ if args.train_text_encoder
1131
+ else unet.parameters()
1132
+ )
1133
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1134
+ optimizer.step()
1135
+ lr_scheduler.step()
1136
+ optimizer.zero_grad(set_to_none=args.set_grads_to_none)
1137
+
1138
+ # Checks if the accelerator has performed an optimization step behind the scenes
1139
+ if accelerator.sync_gradients:
1140
+ progress_bar.update(1)
1141
+ global_step += 1
1142
+
1143
+ if accelerator.is_main_process:
1144
+ if global_step % args.checkpointing_steps == 0:
1145
+ save_path = join(args.output_dir, f"checkpoint-{global_step}")
1146
+ accelerator.save_state(save_path)
1147
+ logger.info(f"Saved state to {save_path}")
1148
+
1149
+ if (
1150
+ args.validation_steps
1151
+ and any(args.validation_prompt)
1152
+ and global_step % args.validation_steps == 0
1153
+ ):
1154
+ images_set = generate_validation_images(
1155
+ text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype
1156
+ )
1157
+ for images, validation_prompt in zip(images_set, args.validation_prompt):
1158
+ if len(images) > 0:
1159
+ label = str(uuid.uuid1())[:8] # generate an id for different set of images
1160
+ log_validation_images_to_tracker(
1161
+ images, label, validation_prompt, accelerator, global_step
1162
+ )
1163
+
1164
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1165
+ progress_bar.set_postfix(**logs)
1166
+ accelerator.log(logs, step=global_step)
1167
+
1168
+ if global_step >= args.max_train_steps:
1169
+ break
1170
+
1171
+ # Create the pipeline using the trained modules and save it.
1172
+ accelerator.wait_for_everyone()
1173
+ if accelerator.is_main_process:
1174
+ pipeline = DiffusionPipeline.from_pretrained(
1175
+ args.pretrained_model_name_or_path,
1176
+ unet=accelerator.unwrap_model(unet),
1177
+ text_encoder=accelerator.unwrap_model(text_encoder),
1178
+ revision=args.revision,
1179
+ )
1180
+ pipeline.save_pretrained(args.output_dir)
1181
+
1182
+ if args.push_to_hub:
1183
+ upload_folder(
1184
+ repo_id=repo_id,
1185
+ folder_path=args.output_dir,
1186
+ commit_message="End of training",
1187
+ ignore_patterns=["step_*", "epoch_*"],
1188
+ )
1189
+
1190
+ accelerator.end_training()
1191
+
1192
+
1193
+ if __name__ == "__main__":
1194
+ args = parse_args()
1195
+ main(args)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Multi Subject Dreambooth for Inpainting Models
2
+
3
+ Please note that this project is not actively maintained. However, you can open an issue and tag @gzguevara.
4
+
5
+ [DreamBooth](https://huggingface.co/papers/2208.12242) is a method to personalize text2image models like stable diffusion given just a few(3~5) images of a subject. This project consists of **two parts**. Training Stable Diffusion for inpainting requires prompt-image-mask pairs. The Unet of inpainiting models have 5 additional input channels (4 for the encoded masked-image and 1 for the mask itself).
6
+
7
+ **The first part**, the `multi_inpaint_dataset.ipynb` notebook, demonstrates how make a 🤗 dataset of prompt-image-mask pairs. You can, however, skip the first part and move straight to the second part with the example datasets in this project. ([cat toy dataset masked](https://huggingface.co/datasets/gzguevara/cat_toy_masked), [mr. potato head dataset masked](https://huggingface.co/datasets/gzguevara/mr_potato_head_masked))
8
+
9
+ **The second part**, the `train_multi_subject_inpainting.py` training script, demonstrates how to implement a training procedure for one or more subjects and adapt it for stable diffusion for inpainting.
10
+
11
+ ## 1. Data Collection: Make Prompt-Image-Mask Pairs
12
+
13
+ Earlier training scripts have provided approaches like random masking for the training images. This project provides a notebook for more precise mask setting.
14
+
15
+ The notebook can be found here: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1JNEASI_B7pLW1srxhgln6nM0HoGAQT32?usp=sharing)
16
+
17
+ The `multi_inpaint_dataset.ipynb` notebook, takes training & validation images, on which the user draws masks and provides prompts to make a prompt-image-mask pairs. This ensures that during training, the loss is computed on the area masking the object of interest, rather than on random areas. Moreover, the `multi_inpaint_dataset.ipynb` notebook allows you to build a validation dataset with corresponding masks for monitoring the training process. Example below:
18
+
19
+ ![train_val_pairs](https://drive.google.com/uc?id=1PzwH8E3icl_ubVmA19G0HZGLImFX3x5I)
20
+
21
+ You can build multiple datasets for every subject and upload them to the 🤗 hub. Later, when launching the training script you can indicate the paths of the datasets, on which you would like to finetune Stable Diffusion for inpaining.
22
+
23
+ ## 2. Train Multi Subject Dreambooth for Inpainting
24
+
25
+ ### 2.1. Setting The Training Configuration
26
+
27
+ Before launching the training script, make sure to select the inpainting the target model, the output directory and the 🤗 datasets.
28
+
29
+ ```bash
30
+ export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-inpainting"
31
+ export OUTPUT_DIR="path-to-save-model"
32
+
33
+ export DATASET_1="gzguevara/mr_potato_head_masked"
34
+ export DATASET_2="gzguevara/cat_toy_masked"
35
+ ... # Further paths to 🤗 datasets
36
+ ```
37
+
38
+ ### 2.2. Launching The Training Script
39
+
40
+ ```bash
41
+ accelerate launch train_multi_subject_dreambooth_inpaint.py \
42
+ --pretrained_model_name_or_path=$MODEL_NAME \
43
+ --instance_data_dir $DATASET_1 $DATASET_2 \
44
+ --output_dir=$OUTPUT_DIR \
45
+ --resolution=512 \
46
+ --train_batch_size=1 \
47
+ --gradient_accumulation_steps=2 \
48
+ --learning_rate=3e-6 \
49
+ --max_train_steps=500 \
50
+ --report_to_wandb
51
+ ```
52
+
53
+ ### 2.3. Fine-tune text encoder with the UNet.
54
+
55
+ The script also allows to fine-tune the `text_encoder` along with the `unet`. It's been observed experimentally that fine-tuning `text_encoder` gives much better results especially on faces.
56
+ Pass the `--train_text_encoder` argument to the script to enable training `text_encoder`.
57
+
58
+ ___Note: Training text encoder requires more memory, with this option the training won't fit on 16GB GPU. It needs at least 24GB VRAM.___
59
+
60
+ ```bash
61
+ accelerate launch train_multi_subject_dreambooth_inpaint.py \
62
+ --pretrained_model_name_or_path=$MODEL_NAME \
63
+ --instance_data_dir $DATASET_1 $DATASET_2 \
64
+ --output_dir=$OUTPUT_DIR \
65
+ --resolution=512 \
66
+ --train_batch_size=1 \
67
+ --gradient_accumulation_steps=2 \
68
+ --learning_rate=2e-6 \
69
+ --max_train_steps=500 \
70
+ --report_to_wandb \
71
+ --train_text_encoder
72
+ ```
73
+
74
+ ## 3. Results
75
+
76
+ A [![Weights & Biases](https://img.shields.io/badge/Weights%20&%20Biases-Report-blue)](https://wandb.ai/gzguevara/uncategorized/reports/Multi-Subject-Dreambooth-for-Inpainting--Vmlldzo2MzY5NDQ4?accessToken=y0nya2d7baguhbryxaikbfr1203amvn1jsmyl07vk122mrs7tnph037u1nqgse8t) is provided showing the training progress by every 50 steps. Note, the reported weights & biases run was performed on a A100 GPU with the following stetting:
77
+
78
+ ```bash
79
+ accelerate launch train_multi_subject_dreambooth_inpaint.py \
80
+ --pretrained_model_name_or_path=$MODEL_NAME \
81
+ --instance_data_dir $DATASET_1 $DATASET_2 \
82
+ --output_dir=$OUTPUT_DIR \
83
+ --resolution=512 \
84
+ --train_batch_size=10 \
85
+ --gradient_accumulation_steps=1 \
86
+ --learning_rate=1e-6 \
87
+ --max_train_steps=500 \
88
+ --report_to_wandb \
89
+ --train_text_encoder
90
+ ```
91
+ Here you can see the target objects on my desk and next to my plant:
92
+
93
+ ![Results](https://drive.google.com/uc?id=1kQisOiiF5cj4rOYjdq8SCZenNsUP2aK0)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ datasets>=2.16.0
5
+ wandb>=0.16.1
6
+ ftfy
7
+ tensorboard
8
+ Jinja2
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/train_multi_subject_dreambooth_inpainting.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import copy
3
+ import itertools
4
+ import logging
5
+ import math
6
+ import os
7
+ import random
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ import torch.utils.checkpoint
14
+ from accelerate import Accelerator
15
+ from accelerate.logging import get_logger
16
+ from accelerate.utils import ProjectConfiguration, set_seed
17
+ from datasets import concatenate_datasets, load_dataset
18
+ from PIL import Image
19
+ from torch.utils.data import Dataset
20
+ from torchvision import transforms
21
+ from tqdm.auto import tqdm
22
+ from transformers import CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers import (
25
+ AutoencoderKL,
26
+ DDPMScheduler,
27
+ StableDiffusionInpaintPipeline,
28
+ UNet2DConditionModel,
29
+ )
30
+ from diffusers.optimization import get_scheduler
31
+ from diffusers.utils import check_min_version, is_wandb_available
32
+
33
+
34
+ if is_wandb_available():
35
+ import wandb
36
+
37
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
38
+ check_min_version("0.13.0.dev0")
39
+
40
+ logger = get_logger(__name__)
41
+
42
+
43
+ def parse_args():
44
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
45
+ parser.add_argument(
46
+ "--pretrained_model_name_or_path",
47
+ type=str,
48
+ default=None,
49
+ required=True,
50
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
51
+ )
52
+ parser.add_argument("--instance_data_dir", nargs="+", help="Instance data directories")
53
+ parser.add_argument(
54
+ "--output_dir",
55
+ type=str,
56
+ default="text-inversion-model",
57
+ help="The output directory where the model predictions and checkpoints will be written.",
58
+ )
59
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
60
+ parser.add_argument(
61
+ "--resolution",
62
+ type=int,
63
+ default=512,
64
+ help=(
65
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
66
+ " resolution"
67
+ ),
68
+ )
69
+ parser.add_argument(
70
+ "--train_text_encoder", default=False, action="store_true", help="Whether to train the text encoder"
71
+ )
72
+ parser.add_argument(
73
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
74
+ )
75
+ parser.add_argument(
76
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
77
+ )
78
+ parser.add_argument(
79
+ "--max_train_steps",
80
+ type=int,
81
+ default=None,
82
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
83
+ )
84
+ parser.add_argument(
85
+ "--gradient_accumulation_steps",
86
+ type=int,
87
+ default=1,
88
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
89
+ )
90
+ parser.add_argument(
91
+ "--learning_rate",
92
+ type=float,
93
+ default=5e-6,
94
+ help="Initial learning rate (after the potential warmup period) to use.",
95
+ )
96
+ parser.add_argument(
97
+ "--scale_lr",
98
+ action="store_true",
99
+ default=False,
100
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
101
+ )
102
+ parser.add_argument(
103
+ "--lr_scheduler",
104
+ type=str,
105
+ default="constant",
106
+ help=(
107
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
108
+ ' "constant", "constant_with_warmup"]'
109
+ ),
110
+ )
111
+ parser.add_argument(
112
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
113
+ )
114
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
115
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
116
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
117
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
118
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
119
+ parser.add_argument(
120
+ "--logging_dir",
121
+ type=str,
122
+ default="logs",
123
+ help=(
124
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
125
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
126
+ ),
127
+ )
128
+ parser.add_argument(
129
+ "--mixed_precision",
130
+ type=str,
131
+ default="no",
132
+ choices=["no", "fp16", "bf16"],
133
+ help=(
134
+ "Whether to use mixed precision. Choose"
135
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
136
+ "and an Nvidia Ampere GPU."
137
+ ),
138
+ )
139
+ parser.add_argument(
140
+ "--checkpointing_steps",
141
+ type=int,
142
+ default=1000,
143
+ help=(
144
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
145
+ " checkpoints in case they are better than the last checkpoint and are suitable for resuming training"
146
+ " using `--resume_from_checkpoint`."
147
+ ),
148
+ )
149
+ parser.add_argument(
150
+ "--checkpointing_from",
151
+ type=int,
152
+ default=1000,
153
+ help=("Start to checkpoint from step"),
154
+ )
155
+ parser.add_argument(
156
+ "--validation_steps",
157
+ type=int,
158
+ default=50,
159
+ help=(
160
+ "Run validation every X steps. Validation consists of running the prompt"
161
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
162
+ " and logging the images."
163
+ ),
164
+ )
165
+ parser.add_argument(
166
+ "--validation_from",
167
+ type=int,
168
+ default=0,
169
+ help=("Start to validate from step"),
170
+ )
171
+ parser.add_argument(
172
+ "--checkpoints_total_limit",
173
+ type=int,
174
+ default=None,
175
+ help=(
176
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
177
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
178
+ " for more docs"
179
+ ),
180
+ )
181
+ parser.add_argument(
182
+ "--resume_from_checkpoint",
183
+ type=str,
184
+ default=None,
185
+ help=(
186
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
187
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
188
+ ),
189
+ )
190
+ parser.add_argument(
191
+ "--validation_project_name",
192
+ type=str,
193
+ default=None,
194
+ help="The w&b name.",
195
+ )
196
+ parser.add_argument(
197
+ "--report_to_wandb", default=False, action="store_true", help="Whether to report to weights and biases"
198
+ )
199
+
200
+ args = parser.parse_args()
201
+
202
+ return args
203
+
204
+
205
+ def prepare_mask_and_masked_image(image, mask):
206
+ image = np.array(image.convert("RGB"))
207
+ image = image[None].transpose(0, 3, 1, 2)
208
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
209
+
210
+ mask = np.array(mask.convert("L"))
211
+ mask = mask.astype(np.float32) / 255.0
212
+ mask = mask[None, None]
213
+ mask[mask < 0.5] = 0
214
+ mask[mask >= 0.5] = 1
215
+ mask = torch.from_numpy(mask)
216
+
217
+ masked_image = image * (mask < 0.5)
218
+
219
+ return mask, masked_image
220
+
221
+
222
+ class DreamBoothDataset(Dataset):
223
+ def __init__(
224
+ self,
225
+ tokenizer,
226
+ datasets_paths,
227
+ ):
228
+ self.tokenizer = tokenizer
229
+ self.datasets_paths = (datasets_paths,)
230
+ self.datasets = [load_dataset(dataset_path) for dataset_path in self.datasets_paths[0]]
231
+ self.train_data = concatenate_datasets([dataset["train"] for dataset in self.datasets])
232
+ self.test_data = concatenate_datasets([dataset["test"] for dataset in self.datasets])
233
+
234
+ self.image_normalize = transforms.Compose(
235
+ [
236
+ transforms.ToTensor(),
237
+ transforms.Normalize([0.5], [0.5]),
238
+ ]
239
+ )
240
+
241
+ def set_image(self, img, switch):
242
+ if img.mode not in ["RGB", "L"]:
243
+ img = img.convert("RGB")
244
+
245
+ if switch:
246
+ img = img.transpose(Image.FLIP_LEFT_RIGHT)
247
+
248
+ img = img.resize((512, 512), Image.BILINEAR)
249
+
250
+ return img
251
+
252
+ def __len__(self):
253
+ return len(self.train_data)
254
+
255
+ def __getitem__(self, index):
256
+ # Lettings
257
+ example = {}
258
+ img_idx = index % len(self.train_data)
259
+ switch = random.choice([True, False])
260
+
261
+ # Load image
262
+ image = self.set_image(self.train_data[img_idx]["image"], switch)
263
+
264
+ # Normalize image
265
+ image_norm = self.image_normalize(image)
266
+
267
+ # Tokenise prompt
268
+ tokenized_prompt = self.tokenizer(
269
+ self.train_data[img_idx]["prompt"],
270
+ padding="do_not_pad",
271
+ truncation=True,
272
+ max_length=self.tokenizer.model_max_length,
273
+ ).input_ids
274
+
275
+ # Load masks for image
276
+ masks = [
277
+ self.set_image(self.train_data[img_idx][key], switch) for key in self.train_data[img_idx] if "mask" in key
278
+ ]
279
+
280
+ # Build example
281
+ example["PIL_image"] = image
282
+ example["instance_image"] = image_norm
283
+ example["instance_prompt_id"] = tokenized_prompt
284
+ example["instance_masks"] = masks
285
+
286
+ return example
287
+
288
+
289
+ def weighted_mask(masks):
290
+ # Convert each mask to a NumPy array and ensure it's binary
291
+ mask_arrays = [np.array(mask) / 255 for mask in masks] # Normalizing to 0-1 range
292
+
293
+ # Generate random weights and apply them to each mask
294
+ weights = [random.random() for _ in masks]
295
+ weights = [weight / sum(weights) for weight in weights]
296
+ weighted_masks = [mask * weight for mask, weight in zip(mask_arrays, weights)]
297
+
298
+ # Sum the weighted masks
299
+ summed_mask = np.sum(weighted_masks, axis=0)
300
+
301
+ # Apply a threshold to create the final mask
302
+ threshold = 0.5 # This threshold can be adjusted
303
+ result_mask = summed_mask >= threshold
304
+
305
+ # Convert the result back to a PIL image
306
+ return Image.fromarray(result_mask.astype(np.uint8) * 255)
307
+
308
+
309
+ def collate_fn(examples, tokenizer):
310
+ input_ids = [example["instance_prompt_id"] for example in examples]
311
+ pixel_values = [example["instance_image"] for example in examples]
312
+
313
+ masks, masked_images = [], []
314
+
315
+ for example in examples:
316
+ # generate a random mask
317
+ mask = weighted_mask(example["instance_masks"])
318
+
319
+ # prepare mask and masked image
320
+ mask, masked_image = prepare_mask_and_masked_image(example["PIL_image"], mask)
321
+
322
+ masks.append(mask)
323
+ masked_images.append(masked_image)
324
+
325
+ pixel_values = torch.stack(pixel_values).to(memory_format=torch.contiguous_format).float()
326
+ masks = torch.stack(masks)
327
+ masked_images = torch.stack(masked_images)
328
+ input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids
329
+
330
+ batch = {"input_ids": input_ids, "pixel_values": pixel_values, "masks": masks, "masked_images": masked_images}
331
+
332
+ return batch
333
+
334
+
335
+ def log_validation(pipeline, text_encoder, unet, val_pairs, accelerator):
336
+ # update pipeline (note: unet and vae are loaded again in float32)
337
+ pipeline.text_encoder = accelerator.unwrap_model(text_encoder)
338
+ pipeline.unet = accelerator.unwrap_model(unet)
339
+
340
+ with torch.autocast("cuda"):
341
+ val_results = [{"data_or_path": pipeline(**pair).images[0], "caption": pair["prompt"]} for pair in val_pairs]
342
+
343
+ torch.cuda.empty_cache()
344
+
345
+ wandb.log({"validation": [wandb.Image(**val_result) for val_result in val_results]})
346
+
347
+
348
+ def checkpoint(args, global_step, accelerator):
349
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
350
+ accelerator.save_state(save_path)
351
+ logger.info(f"Saved state to {save_path}")
352
+
353
+
354
+ def main():
355
+ args = parse_args()
356
+
357
+ project_config = ProjectConfiguration(
358
+ total_limit=args.checkpoints_total_limit,
359
+ project_dir=args.output_dir,
360
+ logging_dir=Path(args.output_dir, args.logging_dir),
361
+ )
362
+
363
+ accelerator = Accelerator(
364
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
365
+ mixed_precision=args.mixed_precision,
366
+ project_config=project_config,
367
+ log_with="wandb" if args.report_to_wandb else None,
368
+ )
369
+
370
+ if args.report_to_wandb and not is_wandb_available():
371
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
372
+
373
+ if args.seed is not None:
374
+ set_seed(args.seed)
375
+
376
+ # Make one log on every process with the configuration for debugging.
377
+ logging.basicConfig(
378
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
379
+ datefmt="%m/%d/%Y %H:%M:%S",
380
+ level=logging.INFO,
381
+ )
382
+ logger.info(accelerator.state, main_process_only=False)
383
+
384
+ # Load the tokenizer & models and create wrapper for stable diffusion
385
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
386
+ text_encoder = CLIPTextModel.from_pretrained(
387
+ args.pretrained_model_name_or_path, subfolder="text_encoder"
388
+ ).requires_grad_(args.train_text_encoder)
389
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae").requires_grad_(False)
390
+ unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
391
+
392
+ if args.scale_lr:
393
+ args.learning_rate = (
394
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
395
+ )
396
+
397
+ optimizer = torch.optim.AdamW(
398
+ params=itertools.chain(unet.parameters(), text_encoder.parameters())
399
+ if args.train_text_encoder
400
+ else unet.parameters(),
401
+ lr=args.learning_rate,
402
+ betas=(args.adam_beta1, args.adam_beta2),
403
+ weight_decay=args.adam_weight_decay,
404
+ eps=args.adam_epsilon,
405
+ )
406
+
407
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
408
+
409
+ train_dataset = DreamBoothDataset(
410
+ tokenizer=tokenizer,
411
+ datasets_paths=args.instance_data_dir,
412
+ )
413
+
414
+ train_dataloader = torch.utils.data.DataLoader(
415
+ train_dataset,
416
+ batch_size=args.train_batch_size,
417
+ shuffle=True,
418
+ collate_fn=lambda examples: collate_fn(examples, tokenizer),
419
+ )
420
+
421
+ # Scheduler and math around the number of training steps.
422
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
423
+
424
+ lr_scheduler = get_scheduler(
425
+ args.lr_scheduler,
426
+ optimizer=optimizer,
427
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
428
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
429
+ )
430
+
431
+ if args.train_text_encoder:
432
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
433
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
434
+ )
435
+ else:
436
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
437
+ unet, optimizer, train_dataloader, lr_scheduler
438
+ )
439
+
440
+ accelerator.register_for_checkpointing(lr_scheduler)
441
+
442
+ if args.mixed_precision == "fp16":
443
+ weight_dtype = torch.float16
444
+ elif args.mixed_precision == "bf16":
445
+ weight_dtype = torch.bfloat16
446
+ else:
447
+ weight_dtype = torch.float32
448
+
449
+ # Move text_encode and vae to gpu.
450
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
451
+ # as these models are only used for inference, keeping weights in full precision is not required.
452
+ vae.to(accelerator.device, dtype=weight_dtype)
453
+ if not args.train_text_encoder:
454
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
455
+
456
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
457
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
458
+
459
+ # Afterwards we calculate our number of training epochs
460
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
461
+
462
+ # We need to initialize the trackers we use, and also store our configuration.
463
+ # The trackers initializes automatically on the main process.
464
+ if accelerator.is_main_process:
465
+ tracker_config = vars(copy.deepcopy(args))
466
+ accelerator.init_trackers(args.validation_project_name, config=tracker_config)
467
+
468
+ # create validation pipeline (note: unet and vae are loaded again in float32)
469
+ val_pipeline = StableDiffusionInpaintPipeline.from_pretrained(
470
+ args.pretrained_model_name_or_path,
471
+ tokenizer=tokenizer,
472
+ text_encoder=text_encoder,
473
+ unet=unet,
474
+ vae=vae,
475
+ torch_dtype=weight_dtype,
476
+ safety_checker=None,
477
+ )
478
+ val_pipeline.set_progress_bar_config(disable=True)
479
+
480
+ # prepare validation dataset
481
+ val_pairs = [
482
+ {
483
+ "image": example["image"],
484
+ "mask_image": mask,
485
+ "prompt": example["prompt"],
486
+ }
487
+ for example in train_dataset.test_data
488
+ for mask in [example[key] for key in example if "mask" in key]
489
+ ]
490
+
491
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
492
+ def save_model_hook(models, weights, output_dir):
493
+ if accelerator.is_main_process:
494
+ for model in models:
495
+ sub_dir = "unet" if isinstance(model, type(accelerator.unwrap_model(unet))) else "text_encoder"
496
+ model.save_pretrained(os.path.join(output_dir, sub_dir))
497
+
498
+ # make sure to pop weight so that corresponding model is not saved again
499
+ weights.pop()
500
+
501
+ accelerator.register_save_state_pre_hook(save_model_hook)
502
+
503
+ print()
504
+
505
+ # Train!
506
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
507
+
508
+ logger.info("***** Running training *****")
509
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
510
+ logger.info(f" Num Epochs = {num_train_epochs}")
511
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
512
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
513
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
514
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
515
+
516
+ global_step = 0
517
+ first_epoch = 0
518
+
519
+ if args.resume_from_checkpoint:
520
+ if args.resume_from_checkpoint != "latest":
521
+ path = os.path.basename(args.resume_from_checkpoint)
522
+ else:
523
+ # Get the most recent checkpoint
524
+ dirs = os.listdir(args.output_dir)
525
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
526
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
527
+ path = dirs[-1] if len(dirs) > 0 else None
528
+
529
+ if path is None:
530
+ accelerator.print(
531
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
532
+ )
533
+ args.resume_from_checkpoint = None
534
+ else:
535
+ accelerator.print(f"Resuming from checkpoint {path}")
536
+ accelerator.load_state(os.path.join(args.output_dir, path))
537
+ global_step = int(path.split("-")[1])
538
+
539
+ resume_global_step = global_step * args.gradient_accumulation_steps
540
+ first_epoch = global_step // num_update_steps_per_epoch
541
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
542
+
543
+ # Only show the progress bar once on each machine.
544
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
545
+ progress_bar.set_description("Steps")
546
+
547
+ for epoch in range(first_epoch, num_train_epochs):
548
+ unet.train()
549
+ for step, batch in enumerate(train_dataloader):
550
+ # Skip steps until we reach the resumed step
551
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
552
+ if step % args.gradient_accumulation_steps == 0:
553
+ progress_bar.update(1)
554
+ continue
555
+
556
+ with accelerator.accumulate(unet):
557
+ # Convert images to latent space
558
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
559
+ latents = latents * vae.config.scaling_factor
560
+
561
+ # Convert masked images to latent space
562
+ masked_latents = vae.encode(
563
+ batch["masked_images"].reshape(batch["pixel_values"].shape).to(dtype=weight_dtype)
564
+ ).latent_dist.sample()
565
+ masked_latents = masked_latents * vae.config.scaling_factor
566
+
567
+ masks = batch["masks"]
568
+ # resize the mask to latents shape as we concatenate the mask to the latents
569
+ mask = torch.stack(
570
+ [
571
+ torch.nn.functional.interpolate(mask, size=(args.resolution // 8, args.resolution // 8))
572
+ for mask in masks
573
+ ]
574
+ )
575
+ mask = mask.reshape(-1, 1, args.resolution // 8, args.resolution // 8)
576
+
577
+ # Sample noise that we'll add to the latents
578
+ noise = torch.randn_like(latents)
579
+ bsz = latents.shape[0]
580
+ # Sample a random timestep for each image
581
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
582
+ timesteps = timesteps.long()
583
+
584
+ # Add noise to the latents according to the noise magnitude at each timestep
585
+ # (this is the forward diffusion process)
586
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
587
+
588
+ # concatenate the noised latents with the mask and the masked latents
589
+ latent_model_input = torch.cat([noisy_latents, mask, masked_latents], dim=1)
590
+
591
+ # Get the text embedding for conditioning
592
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
593
+
594
+ # Predict the noise residual
595
+ noise_pred = unet(latent_model_input, timesteps, encoder_hidden_states).sample
596
+
597
+ # Get the target for loss depending on the prediction type
598
+ if noise_scheduler.config.prediction_type == "epsilon":
599
+ target = noise
600
+ elif noise_scheduler.config.prediction_type == "v_prediction":
601
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
602
+ else:
603
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
604
+
605
+ loss = F.mse_loss(noise_pred.float(), target.float(), reduction="mean")
606
+
607
+ accelerator.backward(loss)
608
+ if accelerator.sync_gradients:
609
+ params_to_clip = (
610
+ itertools.chain(unet.parameters(), text_encoder.parameters())
611
+ if args.train_text_encoder
612
+ else unet.parameters()
613
+ )
614
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
615
+
616
+ optimizer.step()
617
+ lr_scheduler.step()
618
+ optimizer.zero_grad()
619
+
620
+ # Checks if the accelerator has performed an optimization step behind the scenes
621
+ if accelerator.sync_gradients:
622
+ progress_bar.update(1)
623
+ global_step += 1
624
+
625
+ if accelerator.is_main_process:
626
+ if (
627
+ global_step % args.validation_steps == 0
628
+ and global_step >= args.validation_from
629
+ and args.report_to_wandb
630
+ ):
631
+ log_validation(
632
+ val_pipeline,
633
+ text_encoder,
634
+ unet,
635
+ val_pairs,
636
+ accelerator,
637
+ )
638
+
639
+ if global_step % args.checkpointing_steps == 0 and global_step >= args.checkpointing_from:
640
+ checkpoint(
641
+ args,
642
+ global_step,
643
+ accelerator,
644
+ )
645
+
646
+ # Step logging
647
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
648
+ progress_bar.set_postfix(**logs)
649
+ accelerator.log(logs, step=global_step)
650
+
651
+ if global_step >= args.max_train_steps:
652
+ break
653
+
654
+ accelerator.wait_for_everyone()
655
+
656
+ # Terminate training
657
+ accelerator.end_training()
658
+
659
+
660
+ if __name__ == "__main__":
661
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## [Deprecated] Multi Token Textual Inversion
2
+
3
+ **IMPORTART: This research project is deprecated. Multi Token Textual Inversion is now supported natively in [the official textual inversion example](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion#running-locally-with-pytorch).**
4
+
5
+ The author of this project is [Isamu Isozaki](https://github.com/isamu-isozaki) - please make sure to tag the author for issue and PRs as well as @patrickvonplaten.
6
+
7
+ We add multi token support to textual inversion. I added
8
+ 1. num_vec_per_token for the number of used to reference that token
9
+ 2. progressive_tokens for progressively training the token from 1 token to 2 token etc
10
+ 3. progressive_tokens_max_steps for the max number of steps until we start full training
11
+ 4. vector_shuffle to shuffle vectors
12
+
13
+ Feel free to add these options to your training! In practice num_vec_per_token around 10+vector shuffle works great!
14
+
15
+ ## Textual Inversion fine-tuning example
16
+
17
+ [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.
18
+ The `textual_inversion.py` script shows how to implement the training procedure and adapt it for stable diffusion.
19
+
20
+ ## Running on Colab
21
+
22
+ Colab for training
23
+ [![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)
24
+
25
+ Colab for inference
26
+ [![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)
27
+
28
+ ## Running locally with PyTorch
29
+ ### Installing the dependencies
30
+
31
+ Before running the scripts, make sure to install the library's training dependencies:
32
+
33
+ **Important**
34
+
35
+ 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:
36
+ ```bash
37
+ git clone https://github.com/huggingface/diffusers
38
+ cd diffusers
39
+ pip install .
40
+ ```
41
+
42
+ Then cd in the example folder and run
43
+ ```bash
44
+ pip install -r requirements.txt
45
+ ```
46
+
47
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
48
+
49
+ ```bash
50
+ accelerate config
51
+ ```
52
+
53
+
54
+ ### Cat toy example
55
+
56
+ You need to accept the model license before downloading or using the weights. In this example we'll use model version `v1-5`, so you'll need to visit [its card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5), read the license and tick the checkbox if you agree.
57
+
58
+ 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).
59
+
60
+ Run the following command to authenticate your token
61
+
62
+ ```bash
63
+ hf auth login
64
+ ```
65
+
66
+ If you have already cloned the repo, then you won't need to go through these steps.
67
+
68
+ <br>
69
+
70
+ Now let's get our dataset.Download 3-4 images from [here](https://drive.google.com/drive/folders/1fmJMs25nxS_rSNqS5hTcRdLem_YQXbq5) and save them in a directory. This will be our training data.
71
+
72
+ And launch the training using
73
+
74
+ **___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
75
+
76
+ ```bash
77
+ export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
78
+ export DATA_DIR="path-to-dir-containing-images"
79
+
80
+ accelerate launch textual_inversion.py \
81
+ --pretrained_model_name_or_path=$MODEL_NAME \
82
+ --train_data_dir=$DATA_DIR \
83
+ --learnable_property="object" \
84
+ --placeholder_token="<cat-toy>" --initializer_token="toy" \
85
+ --resolution=512 \
86
+ --train_batch_size=1 \
87
+ --gradient_accumulation_steps=4 \
88
+ --max_train_steps=3000 \
89
+ --learning_rate=5.0e-04 --scale_lr \
90
+ --lr_scheduler="constant" \
91
+ --lr_warmup_steps=0 \
92
+ --output_dir="textual_inversion_cat"
93
+ ```
94
+
95
+ A full training run takes ~1 hour on one V100 GPU.
96
+
97
+ ### Inference
98
+
99
+ 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.
100
+
101
+ ```python
102
+ from diffusers import StableDiffusionPipeline
103
+
104
+ model_id = "path-to-your-trained-model"
105
+ pipe = StableDiffusionPipeline.from_pretrained(model_id,torch_dtype=torch.float16).to("cuda")
106
+
107
+ prompt = "A <cat-toy> backpack"
108
+
109
+ image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]
110
+
111
+ image.save("cat-backpack.png")
112
+ ```
113
+
114
+
115
+ ## Training with Flax/JAX
116
+
117
+ 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.
118
+
119
+ Before running the scripts, make sure to install the library's training dependencies:
120
+
121
+ ```bash
122
+ pip install -U -r requirements_flax.txt
123
+ ```
124
+
125
+ ```bash
126
+ export MODEL_NAME="duongna/stable-diffusion-v1-4-flax"
127
+ export DATA_DIR="path-to-dir-containing-images"
128
+
129
+ python textual_inversion_flax.py \
130
+ --pretrained_model_name_or_path=$MODEL_NAME \
131
+ --train_data_dir=$DATA_DIR \
132
+ --learnable_property="object" \
133
+ --placeholder_token="<cat-toy>" --initializer_token="toy" \
134
+ --resolution=512 \
135
+ --train_batch_size=1 \
136
+ --max_train_steps=3000 \
137
+ --learning_rate=5.0e-04 --scale_lr \
138
+ --output_dir="textual_inversion_cat"
139
+ ```
140
+ It should be at least 70% faster than the PyTorch script with the same configuration.
141
+
142
+ ### Training with xformers:
143
+ 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-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/multi_token_clip.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The main idea for this code is to provide a way for users to not need to bother with the hassle of multiple tokens for a concept by typing
3
+ a photo of <concept>_0 <concept>_1 ... and so on
4
+ and instead just do
5
+ a photo of <concept>
6
+ which gets translated to the above. This needs to work for both inference and training.
7
+ For inference,
8
+ the tokenizer encodes the text. So, we would want logic for our tokenizer to replace the placeholder token with
9
+ it's underlying vectors
10
+ For training,
11
+ we would want to abstract away some logic like
12
+ 1. Adding tokens
13
+ 2. Updating gradient mask
14
+ 3. Saving embeddings
15
+ to our Util class here.
16
+ so
17
+ TODO:
18
+ 1. have tokenizer keep track of concept, multiconcept pairs and replace during encode call x
19
+ 2. have mechanism for adding tokens x
20
+ 3. have mech for saving emebeddings x
21
+ 4. get mask to update x
22
+ 5. Loading tokens from embedding x
23
+ 6. Integrate to training x
24
+ 7. Test
25
+ """
26
+
27
+ import copy
28
+ import random
29
+
30
+ from transformers import CLIPTokenizer
31
+
32
+
33
+ class MultiTokenCLIPTokenizer(CLIPTokenizer):
34
+ def __init__(self, *args, **kwargs):
35
+ super().__init__(*args, **kwargs)
36
+ self.token_map = {}
37
+
38
+ def try_adding_tokens(self, placeholder_token, *args, **kwargs):
39
+ num_added_tokens = super().add_tokens(placeholder_token, *args, **kwargs)
40
+ if num_added_tokens == 0:
41
+ raise ValueError(
42
+ f"The tokenizer already contains the token {placeholder_token}. Please pass a different"
43
+ " `placeholder_token` that is not already in the tokenizer."
44
+ )
45
+
46
+ def add_placeholder_tokens(self, placeholder_token, *args, num_vec_per_token=1, **kwargs):
47
+ output = []
48
+ if num_vec_per_token == 1:
49
+ self.try_adding_tokens(placeholder_token, *args, **kwargs)
50
+ output.append(placeholder_token)
51
+ else:
52
+ output = []
53
+ for i in range(num_vec_per_token):
54
+ ith_token = placeholder_token + f"_{i}"
55
+ self.try_adding_tokens(ith_token, *args, **kwargs)
56
+ output.append(ith_token)
57
+ # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
58
+ for token in self.token_map:
59
+ if token in placeholder_token:
60
+ raise ValueError(
61
+ f"The tokenizer already has placeholder token {token} that can get confused with"
62
+ f" {placeholder_token}keep placeholder tokens independent"
63
+ )
64
+ self.token_map[placeholder_token] = output
65
+
66
+ def replace_placeholder_tokens_in_text(self, text, vector_shuffle=False, prop_tokens_to_load=1.0):
67
+ """
68
+ Here, we replace the placeholder tokens in text recorded in token_map so that the text_encoder
69
+ can encode them
70
+ vector_shuffle was inspired by https://github.com/rinongal/textual_inversion/pull/119
71
+ where shuffling tokens were found to force the model to learn the concepts more descriptively.
72
+ """
73
+ if isinstance(text, list):
74
+ output = []
75
+ for i in range(len(text)):
76
+ output.append(self.replace_placeholder_tokens_in_text(text[i], vector_shuffle=vector_shuffle))
77
+ return output
78
+ for placeholder_token in self.token_map:
79
+ if placeholder_token in text:
80
+ tokens = self.token_map[placeholder_token]
81
+ tokens = tokens[: 1 + int(len(tokens) * prop_tokens_to_load)]
82
+ if vector_shuffle:
83
+ tokens = copy.copy(tokens)
84
+ random.shuffle(tokens)
85
+ text = text.replace(placeholder_token, " ".join(tokens))
86
+ return text
87
+
88
+ def __call__(self, text, *args, vector_shuffle=False, prop_tokens_to_load=1.0, **kwargs):
89
+ return super().__call__(
90
+ self.replace_placeholder_tokens_in_text(
91
+ text, vector_shuffle=vector_shuffle, prop_tokens_to_load=prop_tokens_to_load
92
+ ),
93
+ *args,
94
+ **kwargs,
95
+ )
96
+
97
+ def encode(self, text, *args, vector_shuffle=False, prop_tokens_to_load=1.0, **kwargs):
98
+ return super().encode(
99
+ self.replace_placeholder_tokens_in_text(
100
+ text, vector_shuffle=vector_shuffle, prop_tokens_to_load=prop_tokens_to_load
101
+ ),
102
+ *args,
103
+ **kwargs,
104
+ )
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_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-83a0918520ec/tests/source/examples/research_projects/multi_token_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-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion.py ADDED
@@ -0,0 +1,938 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 numpy as np
25
+ import PIL
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ import transformers
30
+ from accelerate import Accelerator
31
+ from accelerate.logging import get_logger
32
+ from accelerate.utils import ProjectConfiguration, set_seed
33
+ from huggingface_hub import create_repo, upload_folder
34
+ from multi_token_clip import MultiTokenCLIPTokenizer
35
+
36
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
37
+ from packaging import version
38
+ from PIL import Image
39
+ from torch.utils.data import Dataset
40
+ from torchvision import transforms
41
+ from tqdm.auto import tqdm
42
+ from transformers import CLIPTextModel
43
+
44
+ import diffusers
45
+ from diffusers import (
46
+ AutoencoderKL,
47
+ DDPMScheduler,
48
+ DiffusionPipeline,
49
+ DPMSolverMultistepScheduler,
50
+ StableDiffusionPipeline,
51
+ UNet2DConditionModel,
52
+ )
53
+ from diffusers.optimization import get_scheduler
54
+ from diffusers.utils import check_min_version, is_wandb_available
55
+ from diffusers.utils.import_utils import is_xformers_available
56
+
57
+
58
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
59
+ PIL_INTERPOLATION = {
60
+ "linear": PIL.Image.Resampling.BILINEAR,
61
+ "bilinear": PIL.Image.Resampling.BILINEAR,
62
+ "bicubic": PIL.Image.Resampling.BICUBIC,
63
+ "lanczos": PIL.Image.Resampling.LANCZOS,
64
+ "nearest": PIL.Image.Resampling.NEAREST,
65
+ }
66
+ else:
67
+ PIL_INTERPOLATION = {
68
+ "linear": PIL.Image.LINEAR,
69
+ "bilinear": PIL.Image.BILINEAR,
70
+ "bicubic": PIL.Image.BICUBIC,
71
+ "lanczos": PIL.Image.LANCZOS,
72
+ "nearest": PIL.Image.NEAREST,
73
+ }
74
+ # ------------------------------------------------------------------------------
75
+
76
+
77
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
78
+ check_min_version("0.14.0.dev0")
79
+
80
+ logger = get_logger(__name__)
81
+
82
+
83
+ def add_tokens(tokenizer, text_encoder, placeholder_token, num_vec_per_token=1, initializer_token=None):
84
+ """
85
+ Add tokens to the tokenizer and set the initial value of token embeddings
86
+ """
87
+ tokenizer.add_placeholder_tokens(placeholder_token, num_vec_per_token=num_vec_per_token)
88
+ text_encoder.resize_token_embeddings(len(tokenizer))
89
+ token_embeds = text_encoder.get_input_embeddings().weight.data
90
+ placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
91
+ if initializer_token:
92
+ token_ids = tokenizer.encode(initializer_token, add_special_tokens=False)
93
+ for i, placeholder_token_id in enumerate(placeholder_token_ids):
94
+ token_embeds[placeholder_token_id] = token_embeds[token_ids[i * len(token_ids) // num_vec_per_token]]
95
+ else:
96
+ for i, placeholder_token_id in enumerate(placeholder_token_ids):
97
+ token_embeds[placeholder_token_id] = torch.randn_like(token_embeds[placeholder_token_id])
98
+ return placeholder_token
99
+
100
+
101
+ def save_progress(tokenizer, text_encoder, accelerator, save_path):
102
+ for placeholder_token in tokenizer.token_map:
103
+ placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
104
+ learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_ids]
105
+ if len(placeholder_token_ids) == 1:
106
+ learned_embeds = learned_embeds[None]
107
+ learned_embeds_dict = {placeholder_token: learned_embeds.detach().cpu()}
108
+ torch.save(learned_embeds_dict, save_path)
109
+
110
+
111
+ def load_multitoken_tokenizer(tokenizer, text_encoder, learned_embeds_dict):
112
+ for placeholder_token in learned_embeds_dict:
113
+ placeholder_embeds = learned_embeds_dict[placeholder_token]
114
+ num_vec_per_token = placeholder_embeds.shape[0]
115
+ placeholder_embeds = placeholder_embeds.to(dtype=text_encoder.dtype)
116
+ add_tokens(tokenizer, text_encoder, placeholder_token, num_vec_per_token=num_vec_per_token)
117
+ placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
118
+ token_embeds = text_encoder.get_input_embeddings().weight.data
119
+ for i, placeholder_token_id in enumerate(placeholder_token_ids):
120
+ token_embeds[placeholder_token_id] = placeholder_embeds[i]
121
+
122
+
123
+ def load_multitoken_tokenizer_from_automatic(tokenizer, text_encoder, automatic_dict, placeholder_token):
124
+ """
125
+ Automatic1111's tokens have format
126
+ {'string_to_token': {'*': 265}, 'string_to_param': {'*': tensor([[ 0.0833, 0.0030, 0.0057, ..., -0.0264, -0.0616, -0.0529],
127
+ [ 0.0058, -0.0190, -0.0584, ..., -0.0025, -0.0945, -0.0490],
128
+ [ 0.0916, 0.0025, 0.0365, ..., -0.0685, -0.0124, 0.0728],
129
+ [ 0.0812, -0.0199, -0.0100, ..., -0.0581, -0.0780, 0.0254]],
130
+ requires_grad=True)}, 'name': 'FloralMarble-400', 'step': 399, 'sd_checkpoint': '4bdfc29c', 'sd_checkpoint_name': 'SD2.1-768'}
131
+ """
132
+ learned_embeds_dict = {}
133
+ learned_embeds_dict[placeholder_token] = automatic_dict["string_to_param"]["*"]
134
+ load_multitoken_tokenizer(tokenizer, text_encoder, learned_embeds_dict)
135
+
136
+
137
+ def get_mask(tokenizer, accelerator):
138
+ # Get the mask of the weights that won't change
139
+ mask = torch.ones(len(tokenizer)).to(accelerator.device, dtype=torch.bool)
140
+ for placeholder_token in tokenizer.token_map:
141
+ placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
142
+ for i in range(len(placeholder_token_ids)):
143
+ mask = mask & (torch.arange(len(tokenizer)) != placeholder_token_ids[i]).to(accelerator.device)
144
+ return mask
145
+
146
+
147
+ def parse_args():
148
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
149
+ parser.add_argument(
150
+ "--progressive_tokens_max_steps",
151
+ type=int,
152
+ default=2000,
153
+ help="The number of steps until all tokens will be used.",
154
+ )
155
+ parser.add_argument(
156
+ "--progressive_tokens",
157
+ action="store_true",
158
+ help="Progressively train the tokens. For example, first train for 1 token, then 2 tokens and so on.",
159
+ )
160
+ parser.add_argument("--vector_shuffle", action="store_true", help="Shuffling tokens durint training")
161
+ parser.add_argument(
162
+ "--num_vec_per_token",
163
+ type=int,
164
+ default=1,
165
+ help=(
166
+ "The number of vectors used to represent the placeholder token. The higher the number, the better the"
167
+ " result at the cost of editability. This can be fixed by prompt editing."
168
+ ),
169
+ )
170
+ parser.add_argument(
171
+ "--save_steps",
172
+ type=int,
173
+ default=500,
174
+ help="Save learned_embeds.bin every X updates steps.",
175
+ )
176
+ parser.add_argument(
177
+ "--only_save_embeds",
178
+ action="store_true",
179
+ default=False,
180
+ help="Save only the embeddings for the new concept.",
181
+ )
182
+ parser.add_argument(
183
+ "--pretrained_model_name_or_path",
184
+ type=str,
185
+ default=None,
186
+ required=True,
187
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
188
+ )
189
+ parser.add_argument(
190
+ "--revision",
191
+ type=str,
192
+ default=None,
193
+ required=False,
194
+ help="Revision of pretrained model identifier from huggingface.co/models.",
195
+ )
196
+ parser.add_argument(
197
+ "--tokenizer_name",
198
+ type=str,
199
+ default=None,
200
+ help="Pretrained tokenizer name or path if not the same as model_name",
201
+ )
202
+ parser.add_argument(
203
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
204
+ )
205
+ parser.add_argument(
206
+ "--placeholder_token",
207
+ type=str,
208
+ default=None,
209
+ required=True,
210
+ help="A token to use as a placeholder for the concept.",
211
+ )
212
+ parser.add_argument(
213
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
214
+ )
215
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
216
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
217
+ parser.add_argument(
218
+ "--output_dir",
219
+ type=str,
220
+ default="text-inversion-model",
221
+ help="The output directory where the model predictions and checkpoints will be written.",
222
+ )
223
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
224
+ parser.add_argument(
225
+ "--resolution",
226
+ type=int,
227
+ default=512,
228
+ help=(
229
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
230
+ " resolution"
231
+ ),
232
+ )
233
+ parser.add_argument(
234
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
235
+ )
236
+ parser.add_argument(
237
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
238
+ )
239
+ parser.add_argument("--num_train_epochs", type=int, default=100)
240
+ parser.add_argument(
241
+ "--max_train_steps",
242
+ type=int,
243
+ default=5000,
244
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
245
+ )
246
+ parser.add_argument(
247
+ "--gradient_accumulation_steps",
248
+ type=int,
249
+ default=1,
250
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
251
+ )
252
+ parser.add_argument(
253
+ "--gradient_checkpointing",
254
+ action="store_true",
255
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
256
+ )
257
+ parser.add_argument(
258
+ "--learning_rate",
259
+ type=float,
260
+ default=1e-4,
261
+ help="Initial learning rate (after the potential warmup period) to use.",
262
+ )
263
+ parser.add_argument(
264
+ "--scale_lr",
265
+ action="store_true",
266
+ default=False,
267
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
268
+ )
269
+ parser.add_argument(
270
+ "--lr_scheduler",
271
+ type=str,
272
+ default="constant",
273
+ help=(
274
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
275
+ ' "constant", "constant_with_warmup"]'
276
+ ),
277
+ )
278
+ parser.add_argument(
279
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
280
+ )
281
+ parser.add_argument(
282
+ "--dataloader_num_workers",
283
+ type=int,
284
+ default=0,
285
+ help=(
286
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
287
+ ),
288
+ )
289
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
290
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
291
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
292
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
293
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
294
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
295
+ parser.add_argument(
296
+ "--hub_model_id",
297
+ type=str,
298
+ default=None,
299
+ help="The name of the repository to keep in sync with the local `output_dir`.",
300
+ )
301
+ parser.add_argument(
302
+ "--logging_dir",
303
+ type=str,
304
+ default="logs",
305
+ help=(
306
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
307
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
308
+ ),
309
+ )
310
+ parser.add_argument(
311
+ "--mixed_precision",
312
+ type=str,
313
+ default="no",
314
+ choices=["no", "fp16", "bf16"],
315
+ help=(
316
+ "Whether to use mixed precision. Choose"
317
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
318
+ "and an Nvidia Ampere GPU."
319
+ ),
320
+ )
321
+ parser.add_argument(
322
+ "--allow_tf32",
323
+ action="store_true",
324
+ help=(
325
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
326
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
327
+ ),
328
+ )
329
+ parser.add_argument(
330
+ "--report_to",
331
+ type=str,
332
+ default="tensorboard",
333
+ help=(
334
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
335
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
336
+ ),
337
+ )
338
+ parser.add_argument(
339
+ "--validation_prompt",
340
+ type=str,
341
+ default=None,
342
+ help="A prompt that is used during validation to verify that the model is learning.",
343
+ )
344
+ parser.add_argument(
345
+ "--num_validation_images",
346
+ type=int,
347
+ default=4,
348
+ help="Number of images that should be generated during validation with `validation_prompt`.",
349
+ )
350
+ parser.add_argument(
351
+ "--validation_epochs",
352
+ type=int,
353
+ default=50,
354
+ help=(
355
+ "Run validation every X epochs. Validation consists of running the prompt"
356
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
357
+ " and logging the images."
358
+ ),
359
+ )
360
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
361
+ parser.add_argument(
362
+ "--checkpointing_steps",
363
+ type=int,
364
+ default=500,
365
+ help=(
366
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
367
+ " training using `--resume_from_checkpoint`."
368
+ ),
369
+ )
370
+ parser.add_argument(
371
+ "--checkpoints_total_limit",
372
+ type=int,
373
+ default=None,
374
+ help=(
375
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
376
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
377
+ " for more docs"
378
+ ),
379
+ )
380
+ parser.add_argument(
381
+ "--resume_from_checkpoint",
382
+ type=str,
383
+ default=None,
384
+ help=(
385
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
386
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
387
+ ),
388
+ )
389
+ parser.add_argument(
390
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
391
+ )
392
+
393
+ args = parser.parse_args()
394
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
395
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
396
+ args.local_rank = env_local_rank
397
+
398
+ if args.train_data_dir is None:
399
+ raise ValueError("You must specify a train data directory.")
400
+
401
+ return args
402
+
403
+
404
+ imagenet_templates_small = [
405
+ "a photo of a {}",
406
+ "a rendering of a {}",
407
+ "a cropped photo of the {}",
408
+ "the photo of a {}",
409
+ "a photo of a clean {}",
410
+ "a photo of a dirty {}",
411
+ "a dark photo of the {}",
412
+ "a photo of my {}",
413
+ "a photo of the cool {}",
414
+ "a close-up photo of a {}",
415
+ "a bright photo of the {}",
416
+ "a cropped photo of a {}",
417
+ "a photo of the {}",
418
+ "a good photo of the {}",
419
+ "a photo of one {}",
420
+ "a close-up photo of the {}",
421
+ "a rendition of the {}",
422
+ "a photo of the clean {}",
423
+ "a rendition of a {}",
424
+ "a photo of a nice {}",
425
+ "a good photo of a {}",
426
+ "a photo of the nice {}",
427
+ "a photo of the small {}",
428
+ "a photo of the weird {}",
429
+ "a photo of the large {}",
430
+ "a photo of a cool {}",
431
+ "a photo of a small {}",
432
+ ]
433
+
434
+ imagenet_style_templates_small = [
435
+ "a painting in the style of {}",
436
+ "a rendering in the style of {}",
437
+ "a cropped painting in the style of {}",
438
+ "the painting in the style of {}",
439
+ "a clean painting in the style of {}",
440
+ "a dirty painting in the style of {}",
441
+ "a dark painting in the style of {}",
442
+ "a picture in the style of {}",
443
+ "a cool painting in the style of {}",
444
+ "a close-up painting in the style of {}",
445
+ "a bright painting in the style of {}",
446
+ "a cropped painting in the style of {}",
447
+ "a good painting in the style of {}",
448
+ "a close-up painting in the style of {}",
449
+ "a rendition in the style of {}",
450
+ "a nice painting in the style of {}",
451
+ "a small painting in the style of {}",
452
+ "a weird painting in the style of {}",
453
+ "a large painting in the style of {}",
454
+ ]
455
+
456
+
457
+ class TextualInversionDataset(Dataset):
458
+ def __init__(
459
+ self,
460
+ data_root,
461
+ tokenizer,
462
+ learnable_property="object", # [object, style]
463
+ size=512,
464
+ repeats=100,
465
+ interpolation="bicubic",
466
+ flip_p=0.5,
467
+ set="train",
468
+ placeholder_token="*",
469
+ center_crop=False,
470
+ vector_shuffle=False,
471
+ progressive_tokens=False,
472
+ ):
473
+ self.data_root = data_root
474
+ self.tokenizer = tokenizer
475
+ self.learnable_property = learnable_property
476
+ self.size = size
477
+ self.placeholder_token = placeholder_token
478
+ self.center_crop = center_crop
479
+ self.flip_p = flip_p
480
+ self.vector_shuffle = vector_shuffle
481
+ self.progressive_tokens = progressive_tokens
482
+ self.prop_tokens_to_load = 0
483
+
484
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
485
+
486
+ self.num_images = len(self.image_paths)
487
+ self._length = self.num_images
488
+
489
+ if set == "train":
490
+ self._length = self.num_images * repeats
491
+
492
+ self.interpolation = {
493
+ "linear": PIL_INTERPOLATION["linear"],
494
+ "bilinear": PIL_INTERPOLATION["bilinear"],
495
+ "bicubic": PIL_INTERPOLATION["bicubic"],
496
+ "lanczos": PIL_INTERPOLATION["lanczos"],
497
+ }[interpolation]
498
+
499
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
500
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
501
+
502
+ def __len__(self):
503
+ return self._length
504
+
505
+ def __getitem__(self, i):
506
+ example = {}
507
+ image = Image.open(self.image_paths[i % self.num_images])
508
+
509
+ if not image.mode == "RGB":
510
+ image = image.convert("RGB")
511
+
512
+ placeholder_string = self.placeholder_token
513
+ text = random.choice(self.templates).format(placeholder_string)
514
+
515
+ example["input_ids"] = self.tokenizer.encode(
516
+ text,
517
+ padding="max_length",
518
+ truncation=True,
519
+ max_length=self.tokenizer.model_max_length,
520
+ return_tensors="pt",
521
+ vector_shuffle=self.vector_shuffle,
522
+ prop_tokens_to_load=self.prop_tokens_to_load if self.progressive_tokens else 1.0,
523
+ )[0]
524
+
525
+ # default to score-sde preprocessing
526
+ img = np.array(image).astype(np.uint8)
527
+
528
+ if self.center_crop:
529
+ crop = min(img.shape[0], img.shape[1])
530
+ (
531
+ h,
532
+ w,
533
+ ) = (
534
+ img.shape[0],
535
+ img.shape[1],
536
+ )
537
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
538
+
539
+ image = Image.fromarray(img)
540
+ image = image.resize((self.size, self.size), resample=self.interpolation)
541
+
542
+ image = self.flip_transform(image)
543
+ image = np.array(image).astype(np.uint8)
544
+ image = (image / 127.5 - 1.0).astype(np.float32)
545
+
546
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
547
+ return example
548
+
549
+
550
+ def main():
551
+ args = parse_args()
552
+ if args.report_to == "wandb" and args.hub_token is not None:
553
+ raise ValueError(
554
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
555
+ " Please use `hf auth login` to authenticate with the Hub."
556
+ )
557
+
558
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
559
+ accelerator_project_config = ProjectConfiguration(
560
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
561
+ )
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
+ # Disable AMP for MPS.
571
+ if torch.backends.mps.is_available():
572
+ accelerator.native_amp = False
573
+
574
+ if args.report_to == "wandb":
575
+ if not is_wandb_available():
576
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
577
+ import wandb
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
+ transformers.utils.logging.set_verbosity_warning()
588
+ diffusers.utils.logging.set_verbosity_info()
589
+ else:
590
+ transformers.utils.logging.set_verbosity_error()
591
+ diffusers.utils.logging.set_verbosity_error()
592
+
593
+ # If passed along, set the training seed now.
594
+ if args.seed is not None:
595
+ set_seed(args.seed)
596
+
597
+ # Handle the repository creation
598
+ if accelerator.is_main_process:
599
+ if args.output_dir is not None:
600
+ os.makedirs(args.output_dir, exist_ok=True)
601
+
602
+ if args.push_to_hub:
603
+ repo_id = create_repo(
604
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
605
+ ).repo_id
606
+
607
+ # Load tokenizer
608
+ if args.tokenizer_name:
609
+ tokenizer = MultiTokenCLIPTokenizer.from_pretrained(args.tokenizer_name)
610
+ elif args.pretrained_model_name_or_path:
611
+ tokenizer = MultiTokenCLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
612
+
613
+ # Load scheduler and models
614
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
615
+ text_encoder = CLIPTextModel.from_pretrained(
616
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
617
+ )
618
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
619
+ unet = UNet2DConditionModel.from_pretrained(
620
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
621
+ )
622
+ if is_xformers_available():
623
+ try:
624
+ unet.enable_xformers_memory_efficient_attention()
625
+ except Exception as e:
626
+ logger.warning(
627
+ "Could not enable memory efficient attention. Make sure xformers is installed"
628
+ f" correctly and a GPU is available: {e}"
629
+ )
630
+ add_tokens(tokenizer, text_encoder, args.placeholder_token, args.num_vec_per_token, args.initializer_token)
631
+
632
+ # Freeze vae and unet
633
+ vae.requires_grad_(False)
634
+ unet.requires_grad_(False)
635
+ # Freeze all parameters except for the token embeddings in text encoder
636
+ text_encoder.text_model.encoder.requires_grad_(False)
637
+ text_encoder.text_model.final_layer_norm.requires_grad_(False)
638
+ text_encoder.text_model.embeddings.position_embedding.requires_grad_(False)
639
+
640
+ if args.gradient_checkpointing:
641
+ # Keep unet in train mode if we are using gradient checkpointing to save memory.
642
+ # The dropout cannot be != 0 so it doesn't matter if we are in eval or train mode.
643
+ unet.train()
644
+ text_encoder.gradient_checkpointing_enable()
645
+ unet.enable_gradient_checkpointing()
646
+
647
+ if args.enable_xformers_memory_efficient_attention:
648
+ if is_xformers_available():
649
+ import xformers
650
+
651
+ xformers_version = version.parse(xformers.__version__)
652
+ if xformers_version == version.parse("0.0.16"):
653
+ logger.warning(
654
+ "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."
655
+ )
656
+ unet.enable_xformers_memory_efficient_attention()
657
+ else:
658
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
659
+
660
+ # Enable TF32 for faster training on Ampere GPUs,
661
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
662
+ if args.allow_tf32:
663
+ torch.backends.cuda.matmul.allow_tf32 = True
664
+
665
+ if args.scale_lr:
666
+ args.learning_rate = (
667
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
668
+ )
669
+
670
+ # Initialize the optimizer
671
+ optimizer = torch.optim.AdamW(
672
+ text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
673
+ lr=args.learning_rate,
674
+ betas=(args.adam_beta1, args.adam_beta2),
675
+ weight_decay=args.adam_weight_decay,
676
+ eps=args.adam_epsilon,
677
+ )
678
+
679
+ # Dataset and DataLoaders creation:
680
+ train_dataset = TextualInversionDataset(
681
+ data_root=args.train_data_dir,
682
+ tokenizer=tokenizer,
683
+ size=args.resolution,
684
+ placeholder_token=args.placeholder_token,
685
+ repeats=args.repeats,
686
+ learnable_property=args.learnable_property,
687
+ center_crop=args.center_crop,
688
+ set="train",
689
+ )
690
+ train_dataloader = torch.utils.data.DataLoader(
691
+ train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
692
+ )
693
+
694
+ # Scheduler and math around the number of training steps.
695
+ overrode_max_train_steps = False
696
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
697
+ if args.max_train_steps is None:
698
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
699
+ overrode_max_train_steps = True
700
+
701
+ lr_scheduler = get_scheduler(
702
+ args.lr_scheduler,
703
+ optimizer=optimizer,
704
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
705
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
706
+ )
707
+
708
+ # Prepare everything with our `accelerator`.
709
+ text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
710
+ text_encoder, optimizer, train_dataloader, lr_scheduler
711
+ )
712
+
713
+ # For mixed precision training we cast the unet and vae weights to half-precision
714
+ # as these models are only used for inference, keeping weights in full precision is not required.
715
+ weight_dtype = torch.float32
716
+ if accelerator.mixed_precision == "fp16":
717
+ weight_dtype = torch.float16
718
+ elif accelerator.mixed_precision == "bf16":
719
+ weight_dtype = torch.bfloat16
720
+
721
+ # Move vae and unet to device and cast to weight_dtype
722
+ unet.to(accelerator.device, dtype=weight_dtype)
723
+ vae.to(accelerator.device, dtype=weight_dtype)
724
+
725
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
726
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
727
+ if overrode_max_train_steps:
728
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
729
+ # Afterwards we recalculate our number of training epochs
730
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
731
+
732
+ # We need to initialize the trackers we use, and also store our configuration.
733
+ # The trackers initializes automatically on the main process.
734
+ if accelerator.is_main_process:
735
+ accelerator.init_trackers("textual_inversion", config=vars(args))
736
+
737
+ # Train!
738
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
739
+
740
+ logger.info("***** Running training *****")
741
+ logger.info(f" Num examples = {len(train_dataset)}")
742
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
743
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
744
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
745
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
746
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
747
+ global_step = 0
748
+ first_epoch = 0
749
+
750
+ # Potentially load in the weights and states from a previous save
751
+ if args.resume_from_checkpoint:
752
+ if args.resume_from_checkpoint != "latest":
753
+ path = os.path.basename(args.resume_from_checkpoint)
754
+ else:
755
+ # Get the most recent checkpoint
756
+ dirs = os.listdir(args.output_dir)
757
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
758
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
759
+ path = dirs[-1] if len(dirs) > 0 else None
760
+
761
+ if path is None:
762
+ accelerator.print(
763
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
764
+ )
765
+ args.resume_from_checkpoint = None
766
+ else:
767
+ accelerator.print(f"Resuming from checkpoint {path}")
768
+ accelerator.load_state(os.path.join(args.output_dir, path))
769
+ global_step = int(path.split("-")[1])
770
+
771
+ resume_global_step = global_step * args.gradient_accumulation_steps
772
+ first_epoch = global_step // num_update_steps_per_epoch
773
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
774
+
775
+ # Only show the progress bar once on each machine.
776
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
777
+ progress_bar.set_description("Steps")
778
+
779
+ # keep original embeddings as reference
780
+ orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone()
781
+
782
+ for epoch in range(first_epoch, args.num_train_epochs):
783
+ text_encoder.train()
784
+ for step, batch in enumerate(train_dataloader):
785
+ # Skip steps until we reach the resumed step
786
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
787
+ if step % args.gradient_accumulation_steps == 0:
788
+ progress_bar.update(1)
789
+ continue
790
+ if args.progressive_tokens:
791
+ train_dataset.prop_tokens_to_load = float(global_step) / args.progressive_tokens_max_steps
792
+
793
+ with accelerator.accumulate(text_encoder):
794
+ # Convert images to latent space
795
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()
796
+ latents = latents * vae.config.scaling_factor
797
+
798
+ # Sample noise that we'll add to the latents
799
+ noise = torch.randn_like(latents)
800
+ bsz = latents.shape[0]
801
+ # Sample a random timestep for each image
802
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
803
+ timesteps = timesteps.long()
804
+
805
+ # Add noise to the latents according to the noise magnitude at each timestep
806
+ # (this is the forward diffusion process)
807
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
808
+
809
+ # Get the text embedding for conditioning
810
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype)
811
+
812
+ # Predict the noise residual
813
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
814
+
815
+ # Get the target for loss depending on the prediction type
816
+ if noise_scheduler.config.prediction_type == "epsilon":
817
+ target = noise
818
+ elif noise_scheduler.config.prediction_type == "v_prediction":
819
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
820
+ else:
821
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
822
+
823
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
824
+
825
+ accelerator.backward(loss)
826
+
827
+ optimizer.step()
828
+ lr_scheduler.step()
829
+ optimizer.zero_grad()
830
+
831
+ # Let's make sure we don't update any embedding weights besides the newly added token
832
+ index_no_updates = get_mask(tokenizer, accelerator)
833
+ with torch.no_grad():
834
+ accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[index_no_updates] = (
835
+ orig_embeds_params[index_no_updates]
836
+ )
837
+
838
+ # Checks if the accelerator has performed an optimization step behind the scenes
839
+ if accelerator.sync_gradients:
840
+ progress_bar.update(1)
841
+ global_step += 1
842
+ if global_step % args.save_steps == 0:
843
+ save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
844
+ save_progress(tokenizer, text_encoder, accelerator, save_path)
845
+
846
+ if global_step % args.checkpointing_steps == 0:
847
+ if accelerator.is_main_process:
848
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
849
+ accelerator.save_state(save_path)
850
+ logger.info(f"Saved state to {save_path}")
851
+
852
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
853
+ progress_bar.set_postfix(**logs)
854
+ accelerator.log(logs, step=global_step)
855
+
856
+ if global_step >= args.max_train_steps:
857
+ break
858
+
859
+ if accelerator.is_main_process and args.validation_prompt is not None and epoch % args.validation_epochs == 0:
860
+ logger.info(
861
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
862
+ f" {args.validation_prompt}."
863
+ )
864
+ # create pipeline (note: unet and vae are loaded again in float32)
865
+ pipeline = DiffusionPipeline.from_pretrained(
866
+ args.pretrained_model_name_or_path,
867
+ text_encoder=accelerator.unwrap_model(text_encoder),
868
+ tokenizer=tokenizer,
869
+ unet=unet,
870
+ vae=vae,
871
+ revision=args.revision,
872
+ torch_dtype=weight_dtype,
873
+ )
874
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
875
+ pipeline = pipeline.to(accelerator.device)
876
+ pipeline.set_progress_bar_config(disable=True)
877
+
878
+ # run inference
879
+ generator = (
880
+ None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)
881
+ )
882
+ images = []
883
+ for _ in range(args.num_validation_images):
884
+ with torch.autocast("cuda"):
885
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
886
+ images.append(image)
887
+
888
+ for tracker in accelerator.trackers:
889
+ if tracker.name == "tensorboard":
890
+ np_images = np.stack([np.asarray(img) for img in images])
891
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
892
+ if tracker.name == "wandb":
893
+ tracker.log(
894
+ {
895
+ "validation": [
896
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
897
+ for i, image in enumerate(images)
898
+ ]
899
+ }
900
+ )
901
+
902
+ del pipeline
903
+ torch.cuda.empty_cache()
904
+
905
+ # Create the pipeline using using the trained modules and save it.
906
+ accelerator.wait_for_everyone()
907
+ if accelerator.is_main_process:
908
+ if args.push_to_hub and args.only_save_embeds:
909
+ logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
910
+ save_full_model = True
911
+ else:
912
+ save_full_model = not args.only_save_embeds
913
+ if save_full_model:
914
+ pipeline = StableDiffusionPipeline.from_pretrained(
915
+ args.pretrained_model_name_or_path,
916
+ text_encoder=accelerator.unwrap_model(text_encoder),
917
+ vae=vae,
918
+ unet=unet,
919
+ tokenizer=tokenizer,
920
+ )
921
+ pipeline.save_pretrained(args.output_dir)
922
+ # Save the newly trained embeddings
923
+ save_path = os.path.join(args.output_dir, "learned_embeds.bin")
924
+ save_progress(tokenizer, text_encoder, accelerator, save_path)
925
+
926
+ if args.push_to_hub:
927
+ upload_folder(
928
+ repo_id=repo_id,
929
+ folder_path=args.output_dir,
930
+ commit_message="End of training",
931
+ ignore_patterns=["step_*", "epoch_*"],
932
+ )
933
+
934
+ accelerator.end_training()
935
+
936
+
937
+ if __name__ == "__main__":
938
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion_flax.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.14.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
+ "--learning_rate",
125
+ type=float,
126
+ default=1e-4,
127
+ help="Initial learning rate (after the potential warmup period) to use.",
128
+ )
129
+ parser.add_argument(
130
+ "--scale_lr",
131
+ action="store_true",
132
+ default=True,
133
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
134
+ )
135
+ parser.add_argument(
136
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
137
+ )
138
+ parser.add_argument(
139
+ "--lr_scheduler",
140
+ type=str,
141
+ default="constant",
142
+ help=(
143
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
144
+ ' "constant", "constant_with_warmup"]'
145
+ ),
146
+ )
147
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
148
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
149
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
150
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
151
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
152
+ parser.add_argument(
153
+ "--use_auth_token",
154
+ action="store_true",
155
+ help=(
156
+ "Will use the token generated when running `hf auth login` (necessary to use this script with"
157
+ " private models)."
158
+ ),
159
+ )
160
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
161
+ parser.add_argument(
162
+ "--hub_model_id",
163
+ type=str,
164
+ default=None,
165
+ help="The name of the repository to keep in sync with the local `output_dir`.",
166
+ )
167
+ parser.add_argument(
168
+ "--logging_dir",
169
+ type=str,
170
+ default="logs",
171
+ help=(
172
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
173
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
174
+ ),
175
+ )
176
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
177
+
178
+ args = parser.parse_args()
179
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
180
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
181
+ args.local_rank = env_local_rank
182
+
183
+ if args.train_data_dir is None:
184
+ raise ValueError("You must specify a train data directory.")
185
+
186
+ return args
187
+
188
+
189
+ imagenet_templates_small = [
190
+ "a photo of a {}",
191
+ "a rendering of a {}",
192
+ "a cropped photo of the {}",
193
+ "the photo of a {}",
194
+ "a photo of a clean {}",
195
+ "a photo of a dirty {}",
196
+ "a dark photo of the {}",
197
+ "a photo of my {}",
198
+ "a photo of the cool {}",
199
+ "a close-up photo of a {}",
200
+ "a bright photo of the {}",
201
+ "a cropped photo of a {}",
202
+ "a photo of the {}",
203
+ "a good photo of the {}",
204
+ "a photo of one {}",
205
+ "a close-up photo of the {}",
206
+ "a rendition of the {}",
207
+ "a photo of the clean {}",
208
+ "a rendition of a {}",
209
+ "a photo of a nice {}",
210
+ "a good photo of a {}",
211
+ "a photo of the nice {}",
212
+ "a photo of the small {}",
213
+ "a photo of the weird {}",
214
+ "a photo of the large {}",
215
+ "a photo of a cool {}",
216
+ "a photo of a small {}",
217
+ ]
218
+
219
+ imagenet_style_templates_small = [
220
+ "a painting in the style of {}",
221
+ "a rendering in the style of {}",
222
+ "a cropped painting in the style of {}",
223
+ "the painting in the style of {}",
224
+ "a clean painting in the style of {}",
225
+ "a dirty painting in the style of {}",
226
+ "a dark painting in the style of {}",
227
+ "a picture in the style of {}",
228
+ "a cool painting in the style of {}",
229
+ "a close-up painting in the style of {}",
230
+ "a bright painting in the style of {}",
231
+ "a cropped painting in the style of {}",
232
+ "a good painting in the style of {}",
233
+ "a close-up painting in the style of {}",
234
+ "a rendition in the style of {}",
235
+ "a nice painting in the style of {}",
236
+ "a small painting in the style of {}",
237
+ "a weird painting in the style of {}",
238
+ "a large painting in the style of {}",
239
+ ]
240
+
241
+
242
+ class TextualInversionDataset(Dataset):
243
+ def __init__(
244
+ self,
245
+ data_root,
246
+ tokenizer,
247
+ learnable_property="object", # [object, style]
248
+ size=512,
249
+ repeats=100,
250
+ interpolation="bicubic",
251
+ flip_p=0.5,
252
+ set="train",
253
+ placeholder_token="*",
254
+ center_crop=False,
255
+ ):
256
+ self.data_root = data_root
257
+ self.tokenizer = tokenizer
258
+ self.learnable_property = learnable_property
259
+ self.size = size
260
+ self.placeholder_token = placeholder_token
261
+ self.center_crop = center_crop
262
+ self.flip_p = flip_p
263
+
264
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
265
+
266
+ self.num_images = len(self.image_paths)
267
+ self._length = self.num_images
268
+
269
+ if set == "train":
270
+ self._length = self.num_images * repeats
271
+
272
+ self.interpolation = {
273
+ "linear": PIL_INTERPOLATION["linear"],
274
+ "bilinear": PIL_INTERPOLATION["bilinear"],
275
+ "bicubic": PIL_INTERPOLATION["bicubic"],
276
+ "lanczos": PIL_INTERPOLATION["lanczos"],
277
+ }[interpolation]
278
+
279
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
280
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
281
+
282
+ def __len__(self):
283
+ return self._length
284
+
285
+ def __getitem__(self, i):
286
+ example = {}
287
+ image = Image.open(self.image_paths[i % self.num_images])
288
+
289
+ if not image.mode == "RGB":
290
+ image = image.convert("RGB")
291
+
292
+ placeholder_string = self.placeholder_token
293
+ text = random.choice(self.templates).format(placeholder_string)
294
+
295
+ example["input_ids"] = self.tokenizer(
296
+ text,
297
+ padding="max_length",
298
+ truncation=True,
299
+ max_length=self.tokenizer.model_max_length,
300
+ return_tensors="pt",
301
+ ).input_ids[0]
302
+
303
+ # default to score-sde preprocessing
304
+ img = np.array(image).astype(np.uint8)
305
+
306
+ if self.center_crop:
307
+ crop = min(img.shape[0], img.shape[1])
308
+ (
309
+ h,
310
+ w,
311
+ ) = (
312
+ img.shape[0],
313
+ img.shape[1],
314
+ )
315
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
316
+
317
+ image = Image.fromarray(img)
318
+ image = image.resize((self.size, self.size), resample=self.interpolation)
319
+
320
+ image = self.flip_transform(image)
321
+ image = np.array(image).astype(np.uint8)
322
+ image = (image / 127.5 - 1.0).astype(np.float32)
323
+
324
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
325
+ return example
326
+
327
+
328
+ def resize_token_embeddings(model, new_num_tokens, initializer_token_id, placeholder_token_id, rng):
329
+ if model.config.vocab_size == new_num_tokens or new_num_tokens is None:
330
+ return
331
+ model.config.vocab_size = new_num_tokens
332
+
333
+ params = model.params
334
+ old_embeddings = params["text_model"]["embeddings"]["token_embedding"]["embedding"]
335
+ old_num_tokens, emb_dim = old_embeddings.shape
336
+
337
+ initializer = jax.nn.initializers.normal()
338
+
339
+ new_embeddings = initializer(rng, (new_num_tokens, emb_dim))
340
+ new_embeddings = new_embeddings.at[:old_num_tokens].set(old_embeddings)
341
+ new_embeddings = new_embeddings.at[placeholder_token_id].set(new_embeddings[initializer_token_id])
342
+ params["text_model"]["embeddings"]["token_embedding"]["embedding"] = new_embeddings
343
+
344
+ model.params = params
345
+ return model
346
+
347
+
348
+ def get_params_to_save(params):
349
+ return jax.device_get(jax.tree_util.tree_map(lambda x: x[0], params))
350
+
351
+
352
+ def main():
353
+ args = parse_args()
354
+
355
+ if args.seed is not None:
356
+ set_seed(args.seed)
357
+
358
+ if jax.process_index() == 0:
359
+ if args.output_dir is not None:
360
+ os.makedirs(args.output_dir, exist_ok=True)
361
+
362
+ if args.push_to_hub:
363
+ repo_id = create_repo(
364
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
365
+ ).repo_id
366
+
367
+ # Make one log on every process with the configuration for debugging.
368
+ logging.basicConfig(
369
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
370
+ datefmt="%m/%d/%Y %H:%M:%S",
371
+ level=logging.INFO,
372
+ )
373
+ # Setup logging, we only want one process per machine to log things on the screen.
374
+ logger.setLevel(logging.INFO if jax.process_index() == 0 else logging.ERROR)
375
+ if jax.process_index() == 0:
376
+ transformers.utils.logging.set_verbosity_info()
377
+ else:
378
+ transformers.utils.logging.set_verbosity_error()
379
+
380
+ # Load the tokenizer and add the placeholder token as a additional special token
381
+ if args.tokenizer_name:
382
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
383
+ elif args.pretrained_model_name_or_path:
384
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
385
+
386
+ # Add the placeholder token in tokenizer
387
+ num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
388
+ if num_added_tokens == 0:
389
+ raise ValueError(
390
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
391
+ " `placeholder_token` that is not already in the tokenizer."
392
+ )
393
+
394
+ # Convert the initializer_token, placeholder_token to ids
395
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
396
+ # Check if initializer_token is a single token or a sequence of tokens
397
+ if len(token_ids) > 1:
398
+ raise ValueError("The initializer token must be a single token.")
399
+
400
+ initializer_token_id = token_ids[0]
401
+ placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
402
+
403
+ # Load models and create wrapper for stable diffusion
404
+ text_encoder = FlaxCLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
405
+ vae, vae_params = FlaxAutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
406
+ unet, unet_params = FlaxUNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
407
+
408
+ # Create sampling rng
409
+ rng = jax.random.PRNGKey(args.seed)
410
+ rng, _ = jax.random.split(rng)
411
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
412
+ text_encoder = resize_token_embeddings(
413
+ text_encoder, len(tokenizer), initializer_token_id, placeholder_token_id, rng
414
+ )
415
+ original_token_embeds = text_encoder.params["text_model"]["embeddings"]["token_embedding"]["embedding"]
416
+
417
+ train_dataset = TextualInversionDataset(
418
+ data_root=args.train_data_dir,
419
+ tokenizer=tokenizer,
420
+ size=args.resolution,
421
+ placeholder_token=args.placeholder_token,
422
+ repeats=args.repeats,
423
+ learnable_property=args.learnable_property,
424
+ center_crop=args.center_crop,
425
+ set="train",
426
+ )
427
+
428
+ def collate_fn(examples):
429
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
430
+ input_ids = torch.stack([example["input_ids"] for example in examples])
431
+
432
+ batch = {"pixel_values": pixel_values, "input_ids": input_ids}
433
+ batch = {k: v.numpy() for k, v in batch.items()}
434
+
435
+ return batch
436
+
437
+ total_train_batch_size = args.train_batch_size * jax.local_device_count()
438
+ train_dataloader = torch.utils.data.DataLoader(
439
+ train_dataset, batch_size=total_train_batch_size, shuffle=True, drop_last=True, collate_fn=collate_fn
440
+ )
441
+
442
+ # Optimization
443
+ if args.scale_lr:
444
+ args.learning_rate = args.learning_rate * total_train_batch_size
445
+
446
+ constant_scheduler = optax.constant_schedule(args.learning_rate)
447
+
448
+ optimizer = optax.adamw(
449
+ learning_rate=constant_scheduler,
450
+ b1=args.adam_beta1,
451
+ b2=args.adam_beta2,
452
+ eps=args.adam_epsilon,
453
+ weight_decay=args.adam_weight_decay,
454
+ )
455
+
456
+ def create_mask(params, label_fn):
457
+ def _map(params, mask, label_fn):
458
+ for k in params:
459
+ if label_fn(k):
460
+ mask[k] = "token_embedding"
461
+ else:
462
+ if isinstance(params[k], dict):
463
+ mask[k] = {}
464
+ _map(params[k], mask[k], label_fn)
465
+ else:
466
+ mask[k] = "zero"
467
+
468
+ mask = {}
469
+ _map(params, mask, label_fn)
470
+ return mask
471
+
472
+ def zero_grads():
473
+ # from https://github.com/deepmind/optax/issues/159#issuecomment-896459491
474
+ def init_fn(_):
475
+ return ()
476
+
477
+ def update_fn(updates, state, params=None):
478
+ return jax.tree_util.tree_map(jnp.zeros_like, updates), ()
479
+
480
+ return optax.GradientTransformation(init_fn, update_fn)
481
+
482
+ # Zero out gradients of layers other than the token embedding layer
483
+ tx = optax.multi_transform(
484
+ {"token_embedding": optimizer, "zero": zero_grads()},
485
+ create_mask(text_encoder.params, lambda s: s == "token_embedding"),
486
+ )
487
+
488
+ state = train_state.TrainState.create(apply_fn=text_encoder.__call__, params=text_encoder.params, tx=tx)
489
+
490
+ noise_scheduler = FlaxDDPMScheduler(
491
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000
492
+ )
493
+ noise_scheduler_state = noise_scheduler.create_state()
494
+
495
+ # Initialize our training
496
+ train_rngs = jax.random.split(rng, jax.local_device_count())
497
+
498
+ # Define gradient train step fn
499
+ def train_step(state, vae_params, unet_params, batch, train_rng):
500
+ dropout_rng, sample_rng, new_train_rng = jax.random.split(train_rng, 3)
501
+
502
+ def compute_loss(params):
503
+ vae_outputs = vae.apply(
504
+ {"params": vae_params}, batch["pixel_values"], deterministic=True, method=vae.encode
505
+ )
506
+ latents = vae_outputs.latent_dist.sample(sample_rng)
507
+ # (NHWC) -> (NCHW)
508
+ latents = jnp.transpose(latents, (0, 3, 1, 2))
509
+ latents = latents * vae.config.scaling_factor
510
+
511
+ noise_rng, timestep_rng = jax.random.split(sample_rng)
512
+ noise = jax.random.normal(noise_rng, latents.shape)
513
+ bsz = latents.shape[0]
514
+ timesteps = jax.random.randint(
515
+ timestep_rng,
516
+ (bsz,),
517
+ 0,
518
+ noise_scheduler.config.num_train_timesteps,
519
+ )
520
+ noisy_latents = noise_scheduler.add_noise(noise_scheduler_state, latents, noise, timesteps)
521
+ encoder_hidden_states = state.apply_fn(
522
+ batch["input_ids"], params=params, dropout_rng=dropout_rng, train=True
523
+ )[0]
524
+ # Predict the noise residual and compute loss
525
+ model_pred = unet.apply(
526
+ {"params": unet_params}, noisy_latents, timesteps, encoder_hidden_states, train=False
527
+ ).sample
528
+
529
+ # Get the target for loss depending on the prediction type
530
+ if noise_scheduler.config.prediction_type == "epsilon":
531
+ target = noise
532
+ elif noise_scheduler.config.prediction_type == "v_prediction":
533
+ target = noise_scheduler.get_velocity(noise_scheduler_state, latents, noise, timesteps)
534
+ else:
535
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
536
+
537
+ loss = (target - model_pred) ** 2
538
+ loss = loss.mean()
539
+
540
+ return loss
541
+
542
+ grad_fn = jax.value_and_grad(compute_loss)
543
+ loss, grad = grad_fn(state.params)
544
+ grad = jax.lax.pmean(grad, "batch")
545
+ new_state = state.apply_gradients(grads=grad)
546
+
547
+ # Keep the token embeddings fixed except the newly added embeddings for the concept,
548
+ # as we only want to optimize the concept embeddings
549
+ token_embeds = original_token_embeds.at[placeholder_token_id].set(
550
+ new_state.params["text_model"]["embeddings"]["token_embedding"]["embedding"][placeholder_token_id]
551
+ )
552
+ new_state.params["text_model"]["embeddings"]["token_embedding"]["embedding"] = token_embeds
553
+
554
+ metrics = {"loss": loss}
555
+ metrics = jax.lax.pmean(metrics, axis_name="batch")
556
+ return new_state, metrics, new_train_rng
557
+
558
+ # Create parallel version of the train and eval step
559
+ p_train_step = jax.pmap(train_step, "batch", donate_argnums=(0,))
560
+
561
+ # Replicate the train state on each device
562
+ state = jax_utils.replicate(state)
563
+ vae_params = jax_utils.replicate(vae_params)
564
+ unet_params = jax_utils.replicate(unet_params)
565
+
566
+ # Train!
567
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader))
568
+
569
+ # Scheduler and math around the number of training steps.
570
+ if args.max_train_steps is None:
571
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
572
+
573
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
574
+
575
+ logger.info("***** Running training *****")
576
+ logger.info(f" Num examples = {len(train_dataset)}")
577
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
578
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
579
+ logger.info(f" Total train batch size (w. parallel & distributed) = {total_train_batch_size}")
580
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
581
+
582
+ global_step = 0
583
+
584
+ epochs = tqdm(range(args.num_train_epochs), desc=f"Epoch ... (1/{args.num_train_epochs})", position=0)
585
+ for epoch in epochs:
586
+ # ======================== Training ================================
587
+
588
+ train_metrics = []
589
+
590
+ steps_per_epoch = len(train_dataset) // total_train_batch_size
591
+ train_step_progress_bar = tqdm(total=steps_per_epoch, desc="Training...", position=1, leave=False)
592
+ # train
593
+ for batch in train_dataloader:
594
+ batch = shard(batch)
595
+ state, train_metric, train_rngs = p_train_step(state, vae_params, unet_params, batch, train_rngs)
596
+ train_metrics.append(train_metric)
597
+
598
+ train_step_progress_bar.update(1)
599
+ global_step += 1
600
+
601
+ if global_step >= args.max_train_steps:
602
+ break
603
+
604
+ train_metric = jax_utils.unreplicate(train_metric)
605
+
606
+ train_step_progress_bar.close()
607
+ epochs.write(f"Epoch... ({epoch + 1}/{args.num_train_epochs} | Loss: {train_metric['loss']})")
608
+
609
+ # Create the pipeline using using the trained modules and save it.
610
+ if jax.process_index() == 0:
611
+ scheduler = FlaxPNDMScheduler(
612
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", skip_prk_steps=True
613
+ )
614
+ safety_checker = FlaxStableDiffusionSafetyChecker.from_pretrained(
615
+ "CompVis/stable-diffusion-safety-checker", from_pt=True
616
+ )
617
+ pipeline = FlaxStableDiffusionPipeline(
618
+ text_encoder=text_encoder,
619
+ vae=vae,
620
+ unet=unet,
621
+ tokenizer=tokenizer,
622
+ scheduler=scheduler,
623
+ safety_checker=safety_checker,
624
+ feature_extractor=CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32"),
625
+ )
626
+
627
+ pipeline.save_pretrained(
628
+ args.output_dir,
629
+ params={
630
+ "text_encoder": get_params_to_save(state.params),
631
+ "vae": get_params_to_save(vae_params),
632
+ "unet": get_params_to_save(unet_params),
633
+ "safety_checker": safety_checker.params,
634
+ },
635
+ )
636
+
637
+ # Also save the newly trained embeddings
638
+ learned_embeds = get_params_to_save(state.params)["text_model"]["embeddings"]["token_embedding"]["embedding"][
639
+ placeholder_token_id
640
+ ]
641
+ learned_embeds_dict = {args.placeholder_token: learned_embeds}
642
+ jnp.save(os.path.join(args.output_dir, "learned_embeds.npy"), learned_embeds_dict)
643
+
644
+ if args.push_to_hub:
645
+ upload_folder(
646
+ repo_id=repo_id,
647
+ folder_path=args.output_dir,
648
+ commit_message="End of training",
649
+ ignore_patterns=["step_*", "epoch_*"],
650
+ )
651
+
652
+
653
+ if __name__ == "__main__":
654
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ## Diffusers examples with ONNXRuntime optimizations
2
+
3
+ **This research project is not actively maintained by the diffusers team. For any questions or comments, please contact Prathik Rao (prathikr), Sunghoon Choi (hanbitmyths), Ashwini Khade (askhade), or Peng Wang (pengwa) on github with any questions.**
4
+
5
+ This aims to provide diffusers examples with ONNXRuntime optimizations for training/fine-tuning unconditional image generation, text to image, and textual inversion. Please see individual directories for more details on how to run each task using ONNXRuntime.
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/README.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 hyperparamters 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
+ ### Naruto example
36
+
37
+ 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.
38
+
39
+ 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).
40
+
41
+ Run the following command to authenticate your token
42
+
43
+ ```bash
44
+ hf auth login
45
+ ```
46
+
47
+ If you have already cloned the repo, then you won't need to go through these steps.
48
+
49
+ <br>
50
+
51
+ ## Use ONNXRuntime to accelerate training
52
+ In order to leverage onnxruntime to accelerate training, please use train_text_to_image.py
53
+
54
+ The command to train a DDPM UNetCondition model on the Naruto dataset with onnxruntime:
55
+
56
+ ```bash
57
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
58
+ export dataset_name="lambdalabs/naruto-blip-captions"
59
+ accelerate launch --mixed_precision="fp16" train_text_to_image.py \
60
+ --pretrained_model_name_or_path=$MODEL_NAME \
61
+ --dataset_name=$dataset_name \
62
+ --use_ema \
63
+ --resolution=512 --center_crop --random_flip \
64
+ --train_batch_size=1 \
65
+ --gradient_accumulation_steps=4 \
66
+ --gradient_checkpointing \
67
+ --max_train_steps=15000 \
68
+ --learning_rate=1e-05 \
69
+ --max_grad_norm=1 \
70
+ --lr_scheduler="constant" --lr_warmup_steps=0 \
71
+ --output_dir="sd-naruto-model"
72
+ ```
73
+
74
+ Please contact Prathik Rao (prathikr), Sunghoon Choi (hanbitmyths), Ashwini Khade (askhade), or Peng Wang (pengwa) on github with any questions.
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.25.1
4
+ datasets
5
+ ftfy
6
+ tensorboard
7
+ modelcards
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/text_to_image/train_text_to_image.py ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 accelerate
25
+ import datasets
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ import transformers
31
+ from accelerate import Accelerator
32
+ from accelerate.logging import get_logger
33
+ from accelerate.state import AcceleratorState
34
+ from accelerate.utils import ProjectConfiguration, set_seed
35
+ from datasets import load_dataset
36
+ from huggingface_hub import create_repo, upload_folder
37
+ from onnxruntime.training.optim.fp16_optimizer import FP16_Optimizer as ORT_FP16_Optimizer
38
+ from onnxruntime.training.ortmodule import ORTModule
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_snr
49
+ from diffusers.utils import check_min_version, deprecate, is_wandb_available
50
+ from diffusers.utils.import_utils import is_xformers_available
51
+
52
+
53
+ if is_wandb_available():
54
+ import wandb
55
+
56
+
57
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
58
+ check_min_version("0.17.0.dev0")
59
+
60
+ logger = get_logger(__name__, log_level="INFO")
61
+
62
+ DATASET_NAME_MAPPING = {
63
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
64
+ }
65
+
66
+
67
+ def log_validation(vae, text_encoder, tokenizer, unet, args, accelerator, weight_dtype, epoch):
68
+ logger.info("Running validation... ")
69
+
70
+ pipeline = StableDiffusionPipeline.from_pretrained(
71
+ args.pretrained_model_name_or_path,
72
+ vae=accelerator.unwrap_model(vae),
73
+ text_encoder=accelerator.unwrap_model(text_encoder),
74
+ tokenizer=tokenizer,
75
+ unet=accelerator.unwrap_model(unet),
76
+ safety_checker=None,
77
+ revision=args.revision,
78
+ torch_dtype=weight_dtype,
79
+ )
80
+ pipeline = pipeline.to(accelerator.device)
81
+ pipeline.set_progress_bar_config(disable=True)
82
+
83
+ if args.enable_xformers_memory_efficient_attention:
84
+ pipeline.enable_xformers_memory_efficient_attention()
85
+
86
+ if args.seed is None:
87
+ generator = None
88
+ else:
89
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
90
+
91
+ images = []
92
+ for i in range(len(args.validation_prompts)):
93
+ with torch.autocast("cuda"):
94
+ image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0]
95
+
96
+ images.append(image)
97
+
98
+ for tracker in accelerator.trackers:
99
+ if tracker.name == "tensorboard":
100
+ np_images = np.stack([np.asarray(img) for img in images])
101
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
102
+ elif tracker.name == "wandb":
103
+ tracker.log(
104
+ {
105
+ "validation": [
106
+ wandb.Image(image, caption=f"{i}: {args.validation_prompts[i]}")
107
+ for i, image in enumerate(images)
108
+ ]
109
+ }
110
+ )
111
+ else:
112
+ logger.warning(f"image logging not implemented for {tracker.name}")
113
+
114
+ del pipeline
115
+ torch.cuda.empty_cache()
116
+
117
+
118
+ def parse_args():
119
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
120
+ parser.add_argument(
121
+ "--input_pertubation", type=float, default=0, help="The scale of input pretubation. Recommended 0.1."
122
+ )
123
+ parser.add_argument(
124
+ "--pretrained_model_name_or_path",
125
+ type=str,
126
+ default=None,
127
+ required=True,
128
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
129
+ )
130
+ parser.add_argument(
131
+ "--revision",
132
+ type=str,
133
+ default=None,
134
+ required=False,
135
+ help="Revision of pretrained model identifier from huggingface.co/models.",
136
+ )
137
+ parser.add_argument(
138
+ "--dataset_name",
139
+ type=str,
140
+ default=None,
141
+ help=(
142
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
143
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
144
+ " or to a folder containing files that 🤗 Datasets can understand."
145
+ ),
146
+ )
147
+ parser.add_argument(
148
+ "--dataset_config_name",
149
+ type=str,
150
+ default=None,
151
+ help="The config of the Dataset, leave as None if there's only one config.",
152
+ )
153
+ parser.add_argument(
154
+ "--train_data_dir",
155
+ type=str,
156
+ default=None,
157
+ help=(
158
+ "A folder containing the training data. Folder contents must follow the structure described in"
159
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
160
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
161
+ ),
162
+ )
163
+ parser.add_argument(
164
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
165
+ )
166
+ parser.add_argument(
167
+ "--caption_column",
168
+ type=str,
169
+ default="text",
170
+ help="The column of the dataset containing a caption or a list of captions.",
171
+ )
172
+ parser.add_argument(
173
+ "--max_train_samples",
174
+ type=int,
175
+ default=None,
176
+ help=(
177
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
178
+ "value if set."
179
+ ),
180
+ )
181
+ parser.add_argument(
182
+ "--validation_prompts",
183
+ type=str,
184
+ default=None,
185
+ nargs="+",
186
+ help=("A set of prompts evaluated every `--validation_epochs` and logged to `--report_to`."),
187
+ )
188
+ parser.add_argument(
189
+ "--output_dir",
190
+ type=str,
191
+ default="sd-model-finetuned",
192
+ help="The output directory where the model predictions and checkpoints will be written.",
193
+ )
194
+ parser.add_argument(
195
+ "--cache_dir",
196
+ type=str,
197
+ default=None,
198
+ help="The directory where the downloaded models and datasets will be stored.",
199
+ )
200
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
201
+ parser.add_argument(
202
+ "--resolution",
203
+ type=int,
204
+ default=512,
205
+ help=(
206
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
207
+ " resolution"
208
+ ),
209
+ )
210
+ parser.add_argument(
211
+ "--center_crop",
212
+ default=False,
213
+ action="store_true",
214
+ help=(
215
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
216
+ " cropped. The images will be resized to the resolution first before cropping."
217
+ ),
218
+ )
219
+ parser.add_argument(
220
+ "--random_flip",
221
+ action="store_true",
222
+ help="whether to randomly flip images horizontally",
223
+ )
224
+ parser.add_argument(
225
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
226
+ )
227
+ parser.add_argument("--num_train_epochs", type=int, default=100)
228
+ parser.add_argument(
229
+ "--max_train_steps",
230
+ type=int,
231
+ default=None,
232
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
233
+ )
234
+ parser.add_argument(
235
+ "--gradient_accumulation_steps",
236
+ type=int,
237
+ default=1,
238
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
239
+ )
240
+ parser.add_argument(
241
+ "--gradient_checkpointing",
242
+ action="store_true",
243
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
244
+ )
245
+ parser.add_argument(
246
+ "--learning_rate",
247
+ type=float,
248
+ default=1e-4,
249
+ help="Initial learning rate (after the potential warmup period) to use.",
250
+ )
251
+ parser.add_argument(
252
+ "--scale_lr",
253
+ action="store_true",
254
+ default=False,
255
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
256
+ )
257
+ parser.add_argument(
258
+ "--lr_scheduler",
259
+ type=str,
260
+ default="constant",
261
+ help=(
262
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
263
+ ' "constant", "constant_with_warmup"]'
264
+ ),
265
+ )
266
+ parser.add_argument(
267
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
268
+ )
269
+ parser.add_argument(
270
+ "--snr_gamma",
271
+ type=float,
272
+ default=None,
273
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
274
+ "More details here: https://huggingface.co/papers/2303.09556.",
275
+ )
276
+ parser.add_argument(
277
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
278
+ )
279
+ parser.add_argument(
280
+ "--allow_tf32",
281
+ action="store_true",
282
+ help=(
283
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
284
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
285
+ ),
286
+ )
287
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
288
+ parser.add_argument(
289
+ "--non_ema_revision",
290
+ type=str,
291
+ default=None,
292
+ required=False,
293
+ help=(
294
+ "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
295
+ " remote repository specified with --pretrained_model_name_or_path."
296
+ ),
297
+ )
298
+ parser.add_argument(
299
+ "--dataloader_num_workers",
300
+ type=int,
301
+ default=0,
302
+ help=(
303
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
304
+ ),
305
+ )
306
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
307
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
308
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
309
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
310
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
311
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
312
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
313
+ parser.add_argument(
314
+ "--hub_model_id",
315
+ type=str,
316
+ default=None,
317
+ help="The name of the repository to keep in sync with the local `output_dir`.",
318
+ )
319
+ parser.add_argument(
320
+ "--logging_dir",
321
+ type=str,
322
+ default="logs",
323
+ help=(
324
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
325
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
326
+ ),
327
+ )
328
+ parser.add_argument(
329
+ "--mixed_precision",
330
+ type=str,
331
+ default=None,
332
+ choices=["no", "fp16", "bf16"],
333
+ help=(
334
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
335
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
336
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
337
+ ),
338
+ )
339
+ parser.add_argument(
340
+ "--report_to",
341
+ type=str,
342
+ default="tensorboard",
343
+ help=(
344
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
345
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
346
+ ),
347
+ )
348
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
349
+ parser.add_argument(
350
+ "--checkpointing_steps",
351
+ type=int,
352
+ default=500,
353
+ help=(
354
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
355
+ " training using `--resume_from_checkpoint`."
356
+ ),
357
+ )
358
+ parser.add_argument(
359
+ "--checkpoints_total_limit",
360
+ type=int,
361
+ default=None,
362
+ help=(
363
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
364
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
365
+ " for more docs"
366
+ ),
367
+ )
368
+ parser.add_argument(
369
+ "--resume_from_checkpoint",
370
+ type=str,
371
+ default=None,
372
+ help=(
373
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
374
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
375
+ ),
376
+ )
377
+ parser.add_argument(
378
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
379
+ )
380
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
381
+ parser.add_argument(
382
+ "--validation_epochs",
383
+ type=int,
384
+ default=5,
385
+ help="Run validation every X epochs.",
386
+ )
387
+ parser.add_argument(
388
+ "--tracker_project_name",
389
+ type=str,
390
+ default="text2image-fine-tune",
391
+ help=(
392
+ "The `project_name` argument passed to Accelerator.init_trackers for"
393
+ " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
394
+ ),
395
+ )
396
+
397
+ args = parser.parse_args()
398
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
399
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
400
+ args.local_rank = env_local_rank
401
+
402
+ # Sanity checks
403
+ if args.dataset_name is None and args.train_data_dir is None:
404
+ raise ValueError("Need either a dataset name or a training folder.")
405
+
406
+ # default to using the same revision for the non-ema model if not specified
407
+ if args.non_ema_revision is None:
408
+ args.non_ema_revision = args.revision
409
+
410
+ return args
411
+
412
+
413
+ def main():
414
+ args = parse_args()
415
+
416
+ if args.report_to == "wandb" and args.hub_token is not None:
417
+ raise ValueError(
418
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
419
+ " Please use `hf auth login` to authenticate with the Hub."
420
+ )
421
+
422
+ if args.non_ema_revision is not None:
423
+ deprecate(
424
+ "non_ema_revision!=None",
425
+ "0.15.0",
426
+ message=(
427
+ "Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
428
+ " use `--variant=non_ema` instead."
429
+ ),
430
+ )
431
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
432
+ accelerator_project_config = ProjectConfiguration(
433
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
434
+ )
435
+
436
+ accelerator = Accelerator(
437
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
438
+ mixed_precision=args.mixed_precision,
439
+ log_with=args.report_to,
440
+ project_config=accelerator_project_config,
441
+ )
442
+
443
+ # Disable AMP for MPS.
444
+ if torch.backends.mps.is_available():
445
+ accelerator.native_amp = False
446
+
447
+ # Make one log on every process with the configuration for debugging.
448
+ logging.basicConfig(
449
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
450
+ datefmt="%m/%d/%Y %H:%M:%S",
451
+ level=logging.INFO,
452
+ )
453
+ logger.info(accelerator.state, main_process_only=False)
454
+ if accelerator.is_local_main_process:
455
+ datasets.utils.logging.set_verbosity_warning()
456
+ transformers.utils.logging.set_verbosity_warning()
457
+ diffusers.utils.logging.set_verbosity_info()
458
+ else:
459
+ datasets.utils.logging.set_verbosity_error()
460
+ transformers.utils.logging.set_verbosity_error()
461
+ diffusers.utils.logging.set_verbosity_error()
462
+
463
+ # If passed along, set the training seed now.
464
+ if args.seed is not None:
465
+ set_seed(args.seed)
466
+
467
+ # Handle the repository creation
468
+ if accelerator.is_main_process:
469
+ if args.output_dir is not None:
470
+ os.makedirs(args.output_dir, exist_ok=True)
471
+
472
+ if args.push_to_hub:
473
+ repo_id = create_repo(
474
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
475
+ ).repo_id
476
+
477
+ # Load scheduler, tokenizer and models.
478
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
479
+ tokenizer = CLIPTokenizer.from_pretrained(
480
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
481
+ )
482
+
483
+ def deepspeed_zero_init_disabled_context_manager():
484
+ """
485
+ returns either a context list that includes one that will disable zero.Init or an empty context list
486
+ """
487
+ deepspeed_plugin = AcceleratorState().deepspeed_plugin if accelerate.state.is_initialized() else None
488
+ if deepspeed_plugin is None:
489
+ return []
490
+
491
+ return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
492
+
493
+ # Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3.
494
+ # For this to work properly all models must be run through `accelerate.prepare`. But accelerate
495
+ # will try to assign the same optimizer with the same weights to all models during
496
+ # `deepspeed.initialize`, which of course doesn't work.
497
+ #
498
+ # For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2
499
+ # frozen models from being partitioned during `zero.Init` which gets called during
500
+ # `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding
501
+ # across multiple gpus and only UNet2DConditionModel will get ZeRO sharded.
502
+ with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
503
+ text_encoder = CLIPTextModel.from_pretrained(
504
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
505
+ )
506
+ vae = AutoencoderKL.from_pretrained(
507
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision
508
+ )
509
+
510
+ unet = UNet2DConditionModel.from_pretrained(
511
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision
512
+ )
513
+
514
+ # Freeze vae and text_encoder
515
+ vae.requires_grad_(False)
516
+ text_encoder.requires_grad_(False)
517
+
518
+ # Create EMA for the unet.
519
+ if args.use_ema:
520
+ ema_unet = UNet2DConditionModel.from_pretrained(
521
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
522
+ )
523
+ ema_unet = EMAModel(ema_unet.parameters(), model_cls=UNet2DConditionModel, model_config=ema_unet.config)
524
+
525
+ if args.enable_xformers_memory_efficient_attention:
526
+ if is_xformers_available():
527
+ import xformers
528
+
529
+ xformers_version = version.parse(xformers.__version__)
530
+ if xformers_version == version.parse("0.0.16"):
531
+ logger.warning(
532
+ "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."
533
+ )
534
+ unet.enable_xformers_memory_efficient_attention()
535
+ else:
536
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
537
+
538
+ # `accelerate` 0.16.0 will have better support for customized saving
539
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
540
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
541
+ def save_model_hook(models, weights, output_dir):
542
+ if accelerator.is_main_process:
543
+ if args.use_ema:
544
+ ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
545
+
546
+ for i, model in enumerate(models):
547
+ model.save_pretrained(os.path.join(output_dir, "unet"))
548
+
549
+ # make sure to pop weight so that corresponding model is not saved again
550
+ weights.pop()
551
+
552
+ def load_model_hook(models, input_dir):
553
+ if args.use_ema:
554
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
555
+ ema_unet.load_state_dict(load_model.state_dict())
556
+ ema_unet.to(accelerator.device)
557
+ del load_model
558
+
559
+ for i in range(len(models)):
560
+ # pop models so that they are not loaded again
561
+ model = models.pop()
562
+
563
+ # load diffusers style into model
564
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
565
+ model.register_to_config(**load_model.config)
566
+
567
+ model.load_state_dict(load_model.state_dict())
568
+ del load_model
569
+
570
+ accelerator.register_save_state_pre_hook(save_model_hook)
571
+ accelerator.register_load_state_pre_hook(load_model_hook)
572
+
573
+ if args.gradient_checkpointing:
574
+ unet.enable_gradient_checkpointing()
575
+
576
+ # Enable TF32 for faster training on Ampere GPUs,
577
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
578
+ if args.allow_tf32:
579
+ torch.backends.cuda.matmul.allow_tf32 = True
580
+
581
+ if args.scale_lr:
582
+ args.learning_rate = (
583
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
584
+ )
585
+
586
+ # Initialize the optimizer
587
+ if args.use_8bit_adam:
588
+ try:
589
+ import bitsandbytes as bnb
590
+ except ImportError:
591
+ raise ImportError(
592
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
593
+ )
594
+
595
+ optimizer_cls = bnb.optim.AdamW8bit
596
+ else:
597
+ optimizer_cls = torch.optim.AdamW
598
+
599
+ optimizer = optimizer_cls(
600
+ unet.parameters(),
601
+ lr=args.learning_rate,
602
+ betas=(args.adam_beta1, args.adam_beta2),
603
+ weight_decay=args.adam_weight_decay,
604
+ eps=args.adam_epsilon,
605
+ )
606
+
607
+ optimizer = ORT_FP16_Optimizer(optimizer)
608
+
609
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
610
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
611
+
612
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
613
+ # download the dataset.
614
+ if args.dataset_name is not None:
615
+ # Downloading and loading a dataset from the hub.
616
+ dataset = load_dataset(
617
+ args.dataset_name,
618
+ args.dataset_config_name,
619
+ cache_dir=args.cache_dir,
620
+ )
621
+ else:
622
+ data_files = {}
623
+ if args.train_data_dir is not None:
624
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
625
+ dataset = load_dataset(
626
+ "imagefolder",
627
+ data_files=data_files,
628
+ cache_dir=args.cache_dir,
629
+ )
630
+ # See more about loading custom images at
631
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
632
+
633
+ # Preprocessing the datasets.
634
+ # We need to tokenize inputs and targets.
635
+ column_names = dataset["train"].column_names
636
+
637
+ # 6. Get the column names for input/target.
638
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
639
+ if args.image_column is None:
640
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
641
+ else:
642
+ image_column = args.image_column
643
+ if image_column not in column_names:
644
+ raise ValueError(
645
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
646
+ )
647
+ if args.caption_column is None:
648
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
649
+ else:
650
+ caption_column = args.caption_column
651
+ if caption_column not in column_names:
652
+ raise ValueError(
653
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
654
+ )
655
+
656
+ # Preprocessing the datasets.
657
+ # We need to tokenize input captions and transform the images.
658
+ def tokenize_captions(examples, is_train=True):
659
+ captions = []
660
+ for caption in examples[caption_column]:
661
+ if isinstance(caption, str):
662
+ captions.append(caption)
663
+ elif isinstance(caption, (list, np.ndarray)):
664
+ # take a random caption if there are multiple
665
+ captions.append(random.choice(caption) if is_train else caption[0])
666
+ else:
667
+ raise ValueError(
668
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
669
+ )
670
+ inputs = tokenizer(
671
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
672
+ )
673
+ return inputs.input_ids
674
+
675
+ # Preprocessing the datasets.
676
+ train_transforms = transforms.Compose(
677
+ [
678
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
679
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
680
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
681
+ transforms.ToTensor(),
682
+ transforms.Normalize([0.5], [0.5]),
683
+ ]
684
+ )
685
+
686
+ def preprocess_train(examples):
687
+ images = [image.convert("RGB") for image in examples[image_column]]
688
+ examples["pixel_values"] = [train_transforms(image) for image in images]
689
+ examples["input_ids"] = tokenize_captions(examples)
690
+ return examples
691
+
692
+ with accelerator.main_process_first():
693
+ if args.max_train_samples is not None:
694
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
695
+ # Set the training transforms
696
+ train_dataset = dataset["train"].with_transform(preprocess_train)
697
+
698
+ def collate_fn(examples):
699
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
700
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
701
+ input_ids = torch.stack([example["input_ids"] for example in examples])
702
+ return {"pixel_values": pixel_values, "input_ids": input_ids}
703
+
704
+ # DataLoaders creation:
705
+ train_dataloader = torch.utils.data.DataLoader(
706
+ train_dataset,
707
+ shuffle=True,
708
+ collate_fn=collate_fn,
709
+ batch_size=args.train_batch_size,
710
+ num_workers=args.dataloader_num_workers,
711
+ )
712
+
713
+ # Scheduler and math around the number of training steps.
714
+ overrode_max_train_steps = False
715
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
716
+ if args.max_train_steps is None:
717
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
718
+ overrode_max_train_steps = True
719
+
720
+ lr_scheduler = get_scheduler(
721
+ args.lr_scheduler,
722
+ optimizer=optimizer,
723
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
724
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
725
+ )
726
+
727
+ # Prepare everything with our `accelerator`.
728
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
729
+ unet, optimizer, train_dataloader, lr_scheduler
730
+ )
731
+
732
+ if args.use_ema:
733
+ ema_unet.to(accelerator.device)
734
+
735
+ unet = ORTModule(unet)
736
+
737
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
738
+ # as these models are only used for inference, keeping weights in full precision is not required.
739
+ weight_dtype = torch.float32
740
+ if accelerator.mixed_precision == "fp16":
741
+ weight_dtype = torch.float16
742
+ elif accelerator.mixed_precision == "bf16":
743
+ weight_dtype = torch.bfloat16
744
+
745
+ # Move text_encode and vae to gpu and cast to weight_dtype
746
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
747
+ vae.to(accelerator.device, dtype=weight_dtype)
748
+
749
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
750
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
751
+ if overrode_max_train_steps:
752
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
753
+ # Afterwards we recalculate our number of training epochs
754
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
755
+
756
+ # We need to initialize the trackers we use, and also store our configuration.
757
+ # The trackers initializes automatically on the main process.
758
+ if accelerator.is_main_process:
759
+ tracker_config = dict(vars(args))
760
+ tracker_config.pop("validation_prompts")
761
+ accelerator.init_trackers(args.tracker_project_name, tracker_config)
762
+
763
+ # Train!
764
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
765
+
766
+ logger.info("***** Running training *****")
767
+ logger.info(f" Num examples = {len(train_dataset)}")
768
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
769
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
770
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
771
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
772
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
773
+ global_step = 0
774
+ first_epoch = 0
775
+
776
+ # Potentially load in the weights and states from a previous save
777
+ if args.resume_from_checkpoint:
778
+ if args.resume_from_checkpoint != "latest":
779
+ path = os.path.basename(args.resume_from_checkpoint)
780
+ else:
781
+ # Get the most recent checkpoint
782
+ dirs = os.listdir(args.output_dir)
783
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
784
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
785
+ path = dirs[-1] if len(dirs) > 0 else None
786
+
787
+ if path is None:
788
+ accelerator.print(
789
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
790
+ )
791
+ args.resume_from_checkpoint = None
792
+ else:
793
+ accelerator.print(f"Resuming from checkpoint {path}")
794
+ accelerator.load_state(os.path.join(args.output_dir, path))
795
+ global_step = int(path.split("-")[1])
796
+
797
+ resume_global_step = global_step * args.gradient_accumulation_steps
798
+ first_epoch = global_step // num_update_steps_per_epoch
799
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
800
+
801
+ # Only show the progress bar once on each machine.
802
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
803
+ progress_bar.set_description("Steps")
804
+
805
+ for epoch in range(first_epoch, args.num_train_epochs):
806
+ unet.train()
807
+ train_loss = 0.0
808
+ for step, batch in enumerate(train_dataloader):
809
+ # Skip steps until we reach the resumed step
810
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
811
+ if step % args.gradient_accumulation_steps == 0:
812
+ progress_bar.update(1)
813
+ continue
814
+
815
+ with accelerator.accumulate(unet):
816
+ # Convert images to latent space
817
+ latents = vae.encode(batch["pixel_values"].to(weight_dtype)).latent_dist.sample()
818
+ latents = latents * vae.config.scaling_factor
819
+
820
+ # Sample noise that we'll add to the latents
821
+ noise = torch.randn_like(latents)
822
+ if args.noise_offset:
823
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
824
+ noise += args.noise_offset * torch.randn(
825
+ (latents.shape[0], latents.shape[1], 1, 1), device=latents.device
826
+ )
827
+ if args.input_pertubation:
828
+ new_noise = noise + args.input_pertubation * torch.randn_like(noise)
829
+ bsz = latents.shape[0]
830
+ # Sample a random timestep for each image
831
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
832
+ timesteps = timesteps.long()
833
+
834
+ # Add noise to the latents according to the noise magnitude at each timestep
835
+ # (this is the forward diffusion process)
836
+ if args.input_pertubation:
837
+ noisy_latents = noise_scheduler.add_noise(latents, new_noise, timesteps)
838
+ else:
839
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
840
+
841
+ # Get the text embedding for conditioning
842
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
843
+
844
+ # Get the target for loss depending on the prediction type
845
+ if noise_scheduler.config.prediction_type == "epsilon":
846
+ target = noise
847
+ elif noise_scheduler.config.prediction_type == "v_prediction":
848
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
849
+ else:
850
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
851
+
852
+ # Predict the noise residual and compute loss
853
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
854
+
855
+ if args.snr_gamma is None:
856
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
857
+ else:
858
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
859
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
860
+ # This is discussed in Section 4.2 of the same paper.
861
+ snr = compute_snr(noise_scheduler, timesteps)
862
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
863
+ dim=1
864
+ )[0]
865
+ if noise_scheduler.config.prediction_type == "epsilon":
866
+ mse_loss_weights = mse_loss_weights / snr
867
+ elif noise_scheduler.config.prediction_type == "v_prediction":
868
+ mse_loss_weights = mse_loss_weights / (snr + 1)
869
+
870
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
871
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
872
+ loss = loss.mean()
873
+
874
+ # Gather the losses across all processes for logging (if we use distributed training).
875
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
876
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
877
+
878
+ # Backpropagate
879
+ accelerator.backward(loss)
880
+ if accelerator.sync_gradients:
881
+ accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm)
882
+ optimizer.step()
883
+ lr_scheduler.step()
884
+ optimizer.zero_grad()
885
+
886
+ # Checks if the accelerator has performed an optimization step behind the scenes
887
+ if accelerator.sync_gradients:
888
+ if args.use_ema:
889
+ ema_unet.step(unet.parameters())
890
+ progress_bar.update(1)
891
+ global_step += 1
892
+ accelerator.log({"train_loss": train_loss}, step=global_step)
893
+ train_loss = 0.0
894
+
895
+ if global_step % args.checkpointing_steps == 0:
896
+ if accelerator.is_main_process:
897
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
898
+ accelerator.save_state(save_path)
899
+ logger.info(f"Saved state to {save_path}")
900
+
901
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
902
+ progress_bar.set_postfix(**logs)
903
+
904
+ if global_step >= args.max_train_steps:
905
+ break
906
+
907
+ if accelerator.is_main_process:
908
+ if args.validation_prompts is not None and epoch % args.validation_epochs == 0:
909
+ if args.use_ema:
910
+ # Store the UNet parameters temporarily and load the EMA parameters to perform inference.
911
+ ema_unet.store(unet.parameters())
912
+ ema_unet.copy_to(unet.parameters())
913
+ log_validation(
914
+ vae,
915
+ text_encoder,
916
+ tokenizer,
917
+ unet,
918
+ args,
919
+ accelerator,
920
+ weight_dtype,
921
+ global_step,
922
+ )
923
+ if args.use_ema:
924
+ # Switch back to the original UNet parameters.
925
+ ema_unet.restore(unet.parameters())
926
+
927
+ # Create the pipeline using the trained modules and save it.
928
+ accelerator.wait_for_everyone()
929
+ if accelerator.is_main_process:
930
+ unet = accelerator.unwrap_model(unet)
931
+ if args.use_ema:
932
+ ema_unet.copy_to(unet.parameters())
933
+
934
+ pipeline = StableDiffusionPipeline.from_pretrained(
935
+ args.pretrained_model_name_or_path,
936
+ text_encoder=text_encoder,
937
+ vae=vae,
938
+ unet=unet,
939
+ revision=args.revision,
940
+ )
941
+ pipeline.save_pretrained(args.output_dir)
942
+
943
+ if args.push_to_hub:
944
+ upload_folder(
945
+ repo_id=repo_id,
946
+ folder_path=args.output_dir,
947
+ commit_message="End of training",
948
+ ignore_patterns=["step_*", "epoch_*"],
949
+ )
950
+
951
+ accelerator.end_training()
952
+
953
+
954
+ if __name__ == "__main__":
955
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/textual_inversion/README.md ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
40
+ ### Cat toy example
41
+
42
+ You need to accept the model license before downloading or using the weights. In this example we'll use model version `v1-5`, so you'll need to visit [its card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5), read the license and tick the checkbox if you agree.
43
+
44
+ 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).
45
+
46
+ Run the following command to authenticate your token
47
+
48
+ ```bash
49
+ hf auth login
50
+ ```
51
+
52
+ If you have already cloned the repo, then you won't need to go through these steps.
53
+
54
+ <br>
55
+
56
+ Now let's get our dataset. For this example we will use some cat images: https://huggingface.co/datasets/diffusers/cat_toy_example .
57
+
58
+ Let's first download it locally:
59
+
60
+ ```py
61
+ from huggingface_hub import snapshot_download
62
+
63
+ local_dir = "./cat"
64
+ snapshot_download("diffusers/cat_toy_example", local_dir=local_dir, repo_type="dataset", ignore_patterns=".gitattributes")
65
+ ```
66
+
67
+ This will be our training data.
68
+ Now we can launch the training using
69
+
70
+ ## Use ONNXRuntime to accelerate training
71
+ In order to leverage onnxruntime to accelerate training, please use textual_inversion.py
72
+
73
+ The command to train on custom data with onnxruntime:
74
+
75
+ ```bash
76
+ export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
77
+ export DATA_DIR="path-to-dir-containing-images"
78
+
79
+ accelerate launch textual_inversion.py \
80
+ --pretrained_model_name_or_path=$MODEL_NAME \
81
+ --train_data_dir=$DATA_DIR \
82
+ --learnable_property="object" \
83
+ --placeholder_token="<cat-toy>" --initializer_token="toy" \
84
+ --resolution=512 \
85
+ --train_batch_size=1 \
86
+ --gradient_accumulation_steps=4 \
87
+ --max_train_steps=3000 \
88
+ --learning_rate=5.0e-04 --scale_lr \
89
+ --lr_scheduler="constant" \
90
+ --lr_warmup_steps=0 \
91
+ --output_dir="textual_inversion_cat"
92
+ ```
93
+
94
+ Please contact Prathik Rao (prathikr), Sunghoon Choi (hanbitmyths), Ashwini Khade (askhade), or Peng Wang (pengwa) on github with any questions.
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/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
+ modelcards
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/textual_inversion/textual_inversion.py ADDED
@@ -0,0 +1,959 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import PIL
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ import transformers
31
+ from accelerate import Accelerator
32
+ from accelerate.logging import get_logger
33
+ from accelerate.utils import ProjectConfiguration, set_seed
34
+ from huggingface_hub import create_repo, upload_folder
35
+ from onnxruntime.training.optim.fp16_optimizer import FP16_Optimizer as ORT_FP16_Optimizer
36
+ from onnxruntime.training.ortmodule import ORTModule
37
+
38
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
39
+ from packaging import version
40
+ from PIL import Image
41
+ from torch.utils.data import Dataset
42
+ from torchvision import transforms
43
+ from tqdm.auto import tqdm
44
+ from transformers import CLIPTextModel, CLIPTokenizer
45
+
46
+ import diffusers
47
+ from diffusers import (
48
+ AutoencoderKL,
49
+ DDPMScheduler,
50
+ DiffusionPipeline,
51
+ DPMSolverMultistepScheduler,
52
+ StableDiffusionPipeline,
53
+ UNet2DConditionModel,
54
+ )
55
+ from diffusers.optimization import get_scheduler
56
+ from diffusers.utils import check_min_version, is_wandb_available
57
+ from diffusers.utils.import_utils import is_xformers_available
58
+
59
+
60
+ if is_wandb_available():
61
+ import wandb
62
+
63
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
64
+ PIL_INTERPOLATION = {
65
+ "linear": PIL.Image.Resampling.BILINEAR,
66
+ "bilinear": PIL.Image.Resampling.BILINEAR,
67
+ "bicubic": PIL.Image.Resampling.BICUBIC,
68
+ "lanczos": PIL.Image.Resampling.LANCZOS,
69
+ "nearest": PIL.Image.Resampling.NEAREST,
70
+ }
71
+ else:
72
+ PIL_INTERPOLATION = {
73
+ "linear": PIL.Image.LINEAR,
74
+ "bilinear": PIL.Image.BILINEAR,
75
+ "bicubic": PIL.Image.BICUBIC,
76
+ "lanczos": PIL.Image.LANCZOS,
77
+ "nearest": PIL.Image.NEAREST,
78
+ }
79
+ # ------------------------------------------------------------------------------
80
+
81
+
82
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
83
+ check_min_version("0.17.0.dev0")
84
+
85
+ logger = get_logger(__name__)
86
+
87
+
88
+ def save_model_card(repo_id: str, images=None, base_model=str, repo_folder=None):
89
+ img_str = ""
90
+ for i, image in enumerate(images):
91
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
92
+ img_str += f"![img_{i}](./image_{i}.png)\n"
93
+
94
+ yaml = f"""
95
+ ---
96
+ license: creativeml-openrail-m
97
+ base_model: {base_model}
98
+ tags:
99
+ - stable-diffusion
100
+ - stable-diffusion-diffusers
101
+ - text-to-image
102
+ - diffusers
103
+ - textual_inversion
104
+ - diffusers-training
105
+ - onxruntime
106
+ inference: true
107
+ ---
108
+ """
109
+ model_card = f"""
110
+ # Textual inversion text2image fine-tuning - {repo_id}
111
+ These are textual inversion adaption weights for {base_model}. You can find some example images in the following. \n
112
+ {img_str}
113
+ """
114
+ with open(os.path.join(repo_folder, "README.md"), "w") as f:
115
+ f.write(yaml + model_card)
116
+
117
+
118
+ def log_validation(text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch):
119
+ logger.info(
120
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
121
+ f" {args.validation_prompt}."
122
+ )
123
+ # create pipeline (note: unet and vae are loaded again in float32)
124
+ pipeline = DiffusionPipeline.from_pretrained(
125
+ args.pretrained_model_name_or_path,
126
+ text_encoder=accelerator.unwrap_model(text_encoder),
127
+ tokenizer=tokenizer,
128
+ unet=unet,
129
+ vae=vae,
130
+ safety_checker=None,
131
+ revision=args.revision,
132
+ torch_dtype=weight_dtype,
133
+ )
134
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
135
+ pipeline = pipeline.to(accelerator.device)
136
+ pipeline.set_progress_bar_config(disable=True)
137
+
138
+ # run inference
139
+ generator = None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)
140
+ images = []
141
+ for _ in range(args.num_validation_images):
142
+ with torch.autocast("cuda"):
143
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
144
+ images.append(image)
145
+
146
+ for tracker in accelerator.trackers:
147
+ if tracker.name == "tensorboard":
148
+ np_images = np.stack([np.asarray(img) for img in images])
149
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
150
+ if tracker.name == "wandb":
151
+ tracker.log(
152
+ {
153
+ "validation": [
154
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}") for i, image in enumerate(images)
155
+ ]
156
+ }
157
+ )
158
+
159
+ del pipeline
160
+ torch.cuda.empty_cache()
161
+ return images
162
+
163
+
164
+ def save_progress(text_encoder, placeholder_token_ids, accelerator, args, save_path):
165
+ logger.info("Saving embeddings")
166
+ learned_embeds = (
167
+ accelerator.unwrap_model(text_encoder)
168
+ .get_input_embeddings()
169
+ .weight[min(placeholder_token_ids) : max(placeholder_token_ids) + 1]
170
+ )
171
+ learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
172
+ torch.save(learned_embeds_dict, save_path)
173
+
174
+
175
+ def parse_args():
176
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
177
+ parser.add_argument(
178
+ "--save_steps",
179
+ type=int,
180
+ default=500,
181
+ help="Save learned_embeds.bin every X updates steps.",
182
+ )
183
+ parser.add_argument(
184
+ "--save_as_full_pipeline",
185
+ action="store_true",
186
+ help="Save the complete stable diffusion pipeline.",
187
+ )
188
+ parser.add_argument(
189
+ "--num_vectors",
190
+ type=int,
191
+ default=1,
192
+ help="How many textual inversion vectors shall be used to learn the concept.",
193
+ )
194
+ parser.add_argument(
195
+ "--pretrained_model_name_or_path",
196
+ type=str,
197
+ default=None,
198
+ required=True,
199
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
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
+ "--tokenizer_name",
210
+ type=str,
211
+ default=None,
212
+ help="Pretrained tokenizer name or path if not the same as model_name",
213
+ )
214
+ parser.add_argument(
215
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
216
+ )
217
+ parser.add_argument(
218
+ "--placeholder_token",
219
+ type=str,
220
+ default=None,
221
+ required=True,
222
+ help="A token to use as a placeholder for the concept.",
223
+ )
224
+ parser.add_argument(
225
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
226
+ )
227
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
228
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
229
+ parser.add_argument(
230
+ "--output_dir",
231
+ type=str,
232
+ default="text-inversion-model",
233
+ help="The output directory where the model predictions and checkpoints will be written.",
234
+ )
235
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
236
+ parser.add_argument(
237
+ "--resolution",
238
+ type=int,
239
+ default=512,
240
+ help=(
241
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
242
+ " resolution"
243
+ ),
244
+ )
245
+ parser.add_argument(
246
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
247
+ )
248
+ parser.add_argument(
249
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
250
+ )
251
+ parser.add_argument("--num_train_epochs", type=int, default=100)
252
+ parser.add_argument(
253
+ "--max_train_steps",
254
+ type=int,
255
+ default=5000,
256
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
257
+ )
258
+ parser.add_argument(
259
+ "--gradient_accumulation_steps",
260
+ type=int,
261
+ default=1,
262
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
263
+ )
264
+ parser.add_argument(
265
+ "--gradient_checkpointing",
266
+ action="store_true",
267
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
268
+ )
269
+ parser.add_argument(
270
+ "--learning_rate",
271
+ type=float,
272
+ default=1e-4,
273
+ help="Initial learning rate (after the potential warmup period) to use.",
274
+ )
275
+ parser.add_argument(
276
+ "--scale_lr",
277
+ action="store_true",
278
+ default=False,
279
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
280
+ )
281
+ parser.add_argument(
282
+ "--lr_scheduler",
283
+ type=str,
284
+ default="constant",
285
+ help=(
286
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
287
+ ' "constant", "constant_with_warmup"]'
288
+ ),
289
+ )
290
+ parser.add_argument(
291
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
292
+ )
293
+ parser.add_argument(
294
+ "--dataloader_num_workers",
295
+ type=int,
296
+ default=0,
297
+ help=(
298
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
299
+ ),
300
+ )
301
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
302
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
303
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
304
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
305
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
306
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
307
+ parser.add_argument(
308
+ "--hub_model_id",
309
+ type=str,
310
+ default=None,
311
+ help="The name of the repository to keep in sync with the local `output_dir`.",
312
+ )
313
+ parser.add_argument(
314
+ "--logging_dir",
315
+ type=str,
316
+ default="logs",
317
+ help=(
318
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
319
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
320
+ ),
321
+ )
322
+ parser.add_argument(
323
+ "--mixed_precision",
324
+ type=str,
325
+ default="no",
326
+ choices=["no", "fp16", "bf16"],
327
+ help=(
328
+ "Whether to use mixed precision. Choose"
329
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
330
+ "and an Nvidia Ampere GPU."
331
+ ),
332
+ )
333
+ parser.add_argument(
334
+ "--allow_tf32",
335
+ action="store_true",
336
+ help=(
337
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
338
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
339
+ ),
340
+ )
341
+ parser.add_argument(
342
+ "--report_to",
343
+ type=str,
344
+ default="tensorboard",
345
+ help=(
346
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
347
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
348
+ ),
349
+ )
350
+ parser.add_argument(
351
+ "--validation_prompt",
352
+ type=str,
353
+ default=None,
354
+ help="A prompt that is used during validation to verify that the model is learning.",
355
+ )
356
+ parser.add_argument(
357
+ "--num_validation_images",
358
+ type=int,
359
+ default=4,
360
+ help="Number of images that should be generated during validation with `validation_prompt`.",
361
+ )
362
+ parser.add_argument(
363
+ "--validation_steps",
364
+ type=int,
365
+ default=100,
366
+ help=(
367
+ "Run validation every X steps. Validation consists of running the prompt"
368
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
369
+ " and logging the images."
370
+ ),
371
+ )
372
+ parser.add_argument(
373
+ "--validation_epochs",
374
+ type=int,
375
+ default=None,
376
+ help=(
377
+ "Deprecated in favor of validation_steps. Run validation every X epochs. Validation consists of running the prompt"
378
+ " `args.validation_prompt` multiple times: `args.num_validation_images`"
379
+ " and logging the images."
380
+ ),
381
+ )
382
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
383
+ parser.add_argument(
384
+ "--checkpointing_steps",
385
+ type=int,
386
+ default=500,
387
+ help=(
388
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
389
+ " training using `--resume_from_checkpoint`."
390
+ ),
391
+ )
392
+ parser.add_argument(
393
+ "--checkpoints_total_limit",
394
+ type=int,
395
+ default=None,
396
+ help=(
397
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
398
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
399
+ " for more docs"
400
+ ),
401
+ )
402
+ parser.add_argument(
403
+ "--resume_from_checkpoint",
404
+ type=str,
405
+ default=None,
406
+ help=(
407
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
408
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
409
+ ),
410
+ )
411
+ parser.add_argument(
412
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
413
+ )
414
+
415
+ args = parser.parse_args()
416
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
417
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
418
+ args.local_rank = env_local_rank
419
+
420
+ if args.train_data_dir is None:
421
+ raise ValueError("You must specify a train data directory.")
422
+
423
+ return args
424
+
425
+
426
+ imagenet_templates_small = [
427
+ "a photo of a {}",
428
+ "a rendering of a {}",
429
+ "a cropped photo of the {}",
430
+ "the photo of a {}",
431
+ "a photo of a clean {}",
432
+ "a photo of a dirty {}",
433
+ "a dark photo of the {}",
434
+ "a photo of my {}",
435
+ "a photo of the cool {}",
436
+ "a close-up photo of a {}",
437
+ "a bright photo of the {}",
438
+ "a cropped photo of a {}",
439
+ "a photo of the {}",
440
+ "a good photo of the {}",
441
+ "a photo of one {}",
442
+ "a close-up photo of the {}",
443
+ "a rendition of the {}",
444
+ "a photo of the clean {}",
445
+ "a rendition of a {}",
446
+ "a photo of a nice {}",
447
+ "a good photo of a {}",
448
+ "a photo of the nice {}",
449
+ "a photo of the small {}",
450
+ "a photo of the weird {}",
451
+ "a photo of the large {}",
452
+ "a photo of a cool {}",
453
+ "a photo of a small {}",
454
+ ]
455
+
456
+ imagenet_style_templates_small = [
457
+ "a painting in the style of {}",
458
+ "a rendering in the style of {}",
459
+ "a cropped painting in the style of {}",
460
+ "the painting in the style of {}",
461
+ "a clean painting in the style of {}",
462
+ "a dirty painting in the style of {}",
463
+ "a dark painting in the style of {}",
464
+ "a picture in the style of {}",
465
+ "a cool painting in the style of {}",
466
+ "a close-up painting in the style of {}",
467
+ "a bright painting in the style of {}",
468
+ "a cropped painting in the style of {}",
469
+ "a good painting in the style of {}",
470
+ "a close-up painting in the style of {}",
471
+ "a rendition in the style of {}",
472
+ "a nice painting in the style of {}",
473
+ "a small painting in the style of {}",
474
+ "a weird painting in the style of {}",
475
+ "a large painting in the style of {}",
476
+ ]
477
+
478
+
479
+ class TextualInversionDataset(Dataset):
480
+ def __init__(
481
+ self,
482
+ data_root,
483
+ tokenizer,
484
+ learnable_property="object", # [object, style]
485
+ size=512,
486
+ repeats=100,
487
+ interpolation="bicubic",
488
+ flip_p=0.5,
489
+ set="train",
490
+ placeholder_token="*",
491
+ center_crop=False,
492
+ ):
493
+ self.data_root = data_root
494
+ self.tokenizer = tokenizer
495
+ self.learnable_property = learnable_property
496
+ self.size = size
497
+ self.placeholder_token = placeholder_token
498
+ self.center_crop = center_crop
499
+ self.flip_p = flip_p
500
+
501
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
502
+
503
+ self.num_images = len(self.image_paths)
504
+ self._length = self.num_images
505
+
506
+ if set == "train":
507
+ self._length = self.num_images * repeats
508
+
509
+ self.interpolation = {
510
+ "linear": PIL_INTERPOLATION["linear"],
511
+ "bilinear": PIL_INTERPOLATION["bilinear"],
512
+ "bicubic": PIL_INTERPOLATION["bicubic"],
513
+ "lanczos": PIL_INTERPOLATION["lanczos"],
514
+ }[interpolation]
515
+
516
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
517
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
518
+
519
+ def __len__(self):
520
+ return self._length
521
+
522
+ def __getitem__(self, i):
523
+ example = {}
524
+ image = Image.open(self.image_paths[i % self.num_images])
525
+
526
+ if not image.mode == "RGB":
527
+ image = image.convert("RGB")
528
+
529
+ placeholder_string = self.placeholder_token
530
+ text = random.choice(self.templates).format(placeholder_string)
531
+
532
+ example["input_ids"] = self.tokenizer(
533
+ text,
534
+ padding="max_length",
535
+ truncation=True,
536
+ max_length=self.tokenizer.model_max_length,
537
+ return_tensors="pt",
538
+ ).input_ids[0]
539
+
540
+ # default to score-sde preprocessing
541
+ img = np.array(image).astype(np.uint8)
542
+
543
+ if self.center_crop:
544
+ crop = min(img.shape[0], img.shape[1])
545
+ (
546
+ h,
547
+ w,
548
+ ) = (
549
+ img.shape[0],
550
+ img.shape[1],
551
+ )
552
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
553
+
554
+ image = Image.fromarray(img)
555
+ image = image.resize((self.size, self.size), resample=self.interpolation)
556
+
557
+ image = self.flip_transform(image)
558
+ image = np.array(image).astype(np.uint8)
559
+ image = (image / 127.5 - 1.0).astype(np.float32)
560
+
561
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
562
+ return example
563
+
564
+
565
+ def main():
566
+ args = parse_args()
567
+ if args.report_to == "wandb" and args.hub_token is not None:
568
+ raise ValueError(
569
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
570
+ " Please use `hf auth login` to authenticate with the Hub."
571
+ )
572
+
573
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
574
+ accelerator_project_config = ProjectConfiguration(
575
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
576
+ )
577
+
578
+ accelerator = Accelerator(
579
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
580
+ mixed_precision=args.mixed_precision,
581
+ log_with=args.report_to,
582
+ project_config=accelerator_project_config,
583
+ )
584
+
585
+ # Disable AMP for MPS.
586
+ if torch.backends.mps.is_available():
587
+ accelerator.native_amp = False
588
+
589
+ if args.report_to == "wandb":
590
+ if not is_wandb_available():
591
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
592
+
593
+ # Make one log on every process with the configuration for debugging.
594
+ logging.basicConfig(
595
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
596
+ datefmt="%m/%d/%Y %H:%M:%S",
597
+ level=logging.INFO,
598
+ )
599
+ logger.info(accelerator.state, main_process_only=False)
600
+ if accelerator.is_local_main_process:
601
+ transformers.utils.logging.set_verbosity_warning()
602
+ diffusers.utils.logging.set_verbosity_info()
603
+ else:
604
+ transformers.utils.logging.set_verbosity_error()
605
+ diffusers.utils.logging.set_verbosity_error()
606
+
607
+ # If passed along, set the training seed now.
608
+ if args.seed is not None:
609
+ set_seed(args.seed)
610
+
611
+ # Handle the repository creation
612
+ if accelerator.is_main_process:
613
+ if args.output_dir is not None:
614
+ os.makedirs(args.output_dir, exist_ok=True)
615
+
616
+ if args.push_to_hub:
617
+ repo_id = create_repo(
618
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
619
+ ).repo_id
620
+
621
+ # Load tokenizer
622
+ if args.tokenizer_name:
623
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
624
+ elif args.pretrained_model_name_or_path:
625
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
626
+
627
+ # Load scheduler and models
628
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
629
+ text_encoder = CLIPTextModel.from_pretrained(
630
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
631
+ )
632
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
633
+ unet = UNet2DConditionModel.from_pretrained(
634
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
635
+ )
636
+
637
+ # Add the placeholder token in tokenizer
638
+ placeholder_tokens = [args.placeholder_token]
639
+
640
+ if args.num_vectors < 1:
641
+ raise ValueError(f"--num_vectors has to be larger or equal to 1, but is {args.num_vectors}")
642
+
643
+ # add dummy tokens for multi-vector
644
+ additional_tokens = []
645
+ for i in range(1, args.num_vectors):
646
+ additional_tokens.append(f"{args.placeholder_token}_{i}")
647
+ placeholder_tokens += additional_tokens
648
+
649
+ num_added_tokens = tokenizer.add_tokens(placeholder_tokens)
650
+ if num_added_tokens != args.num_vectors:
651
+ raise ValueError(
652
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
653
+ " `placeholder_token` that is not already in the tokenizer."
654
+ )
655
+
656
+ # Convert the initializer_token, placeholder_token to ids
657
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
658
+ # Check if initializer_token is a single token or a sequence of tokens
659
+ if len(token_ids) > 1:
660
+ raise ValueError("The initializer token must be a single token.")
661
+
662
+ initializer_token_id = token_ids[0]
663
+ placeholder_token_ids = tokenizer.convert_tokens_to_ids(placeholder_tokens)
664
+
665
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
666
+ text_encoder.resize_token_embeddings(len(tokenizer))
667
+
668
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
669
+ token_embeds = text_encoder.get_input_embeddings().weight.data
670
+ with torch.no_grad():
671
+ for token_id in placeholder_token_ids:
672
+ token_embeds[token_id] = token_embeds[initializer_token_id].clone()
673
+
674
+ # Freeze vae and unet
675
+ vae.requires_grad_(False)
676
+ unet.requires_grad_(False)
677
+ # Freeze all parameters except for the token embeddings in text encoder
678
+ text_encoder.text_model.encoder.requires_grad_(False)
679
+ text_encoder.text_model.final_layer_norm.requires_grad_(False)
680
+ text_encoder.text_model.embeddings.position_embedding.requires_grad_(False)
681
+
682
+ if args.gradient_checkpointing:
683
+ # Keep unet in train mode if we are using gradient checkpointing to save memory.
684
+ # The dropout cannot be != 0 so it doesn't matter if we are in eval or train mode.
685
+ unet.train()
686
+ text_encoder.gradient_checkpointing_enable()
687
+ unet.enable_gradient_checkpointing()
688
+
689
+ if args.enable_xformers_memory_efficient_attention:
690
+ if is_xformers_available():
691
+ import xformers
692
+
693
+ xformers_version = version.parse(xformers.__version__)
694
+ if xformers_version == version.parse("0.0.16"):
695
+ logger.warning(
696
+ "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."
697
+ )
698
+ unet.enable_xformers_memory_efficient_attention()
699
+ else:
700
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
701
+
702
+ # Enable TF32 for faster training on Ampere GPUs,
703
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
704
+ if args.allow_tf32:
705
+ torch.backends.cuda.matmul.allow_tf32 = True
706
+
707
+ if args.scale_lr:
708
+ args.learning_rate = (
709
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
710
+ )
711
+
712
+ # Initialize the optimizer
713
+ optimizer = torch.optim.AdamW(
714
+ text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
715
+ lr=args.learning_rate,
716
+ betas=(args.adam_beta1, args.adam_beta2),
717
+ weight_decay=args.adam_weight_decay,
718
+ eps=args.adam_epsilon,
719
+ )
720
+
721
+ optimizer = ORT_FP16_Optimizer(optimizer)
722
+
723
+ # Dataset and DataLoaders creation:
724
+ train_dataset = TextualInversionDataset(
725
+ data_root=args.train_data_dir,
726
+ tokenizer=tokenizer,
727
+ size=args.resolution,
728
+ placeholder_token=args.placeholder_token,
729
+ repeats=args.repeats,
730
+ learnable_property=args.learnable_property,
731
+ center_crop=args.center_crop,
732
+ set="train",
733
+ )
734
+ train_dataloader = torch.utils.data.DataLoader(
735
+ train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
736
+ )
737
+ if args.validation_epochs is not None:
738
+ warnings.warn(
739
+ f"FutureWarning: You are doing logging with validation_epochs={args.validation_epochs}."
740
+ " Deprecated validation_epochs in favor of `validation_steps`"
741
+ f"Setting `args.validation_steps` to {args.validation_epochs * len(train_dataset)}",
742
+ FutureWarning,
743
+ stacklevel=2,
744
+ )
745
+ args.validation_steps = args.validation_epochs * len(train_dataset)
746
+
747
+ # Scheduler and math around the number of training steps.
748
+ overrode_max_train_steps = False
749
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
750
+ if args.max_train_steps is None:
751
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
752
+ overrode_max_train_steps = True
753
+
754
+ lr_scheduler = get_scheduler(
755
+ args.lr_scheduler,
756
+ optimizer=optimizer,
757
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
758
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
759
+ )
760
+
761
+ # Prepare everything with our `accelerator`.
762
+ text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
763
+ text_encoder, optimizer, train_dataloader, lr_scheduler
764
+ )
765
+
766
+ text_encoder = ORTModule(text_encoder)
767
+ unet = ORTModule(unet)
768
+ vae = ORTModule(vae)
769
+
770
+ # For mixed precision training we cast the unet and vae weights to half-precision
771
+ # as these models are only used for inference, keeping weights in full precision is not required.
772
+ weight_dtype = torch.float32
773
+ if accelerator.mixed_precision == "fp16":
774
+ weight_dtype = torch.float16
775
+ elif accelerator.mixed_precision == "bf16":
776
+ weight_dtype = torch.bfloat16
777
+
778
+ # Move vae and unet to device and cast to weight_dtype
779
+ unet.to(accelerator.device, dtype=weight_dtype)
780
+ vae.to(accelerator.device, dtype=weight_dtype)
781
+
782
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
783
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
784
+ if overrode_max_train_steps:
785
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
786
+ # Afterwards we recalculate our number of training epochs
787
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
788
+
789
+ # We need to initialize the trackers we use, and also store our configuration.
790
+ # The trackers initializes automatically on the main process.
791
+ if accelerator.is_main_process:
792
+ accelerator.init_trackers("textual_inversion", config=vars(args))
793
+
794
+ # Train!
795
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
796
+
797
+ logger.info("***** Running training *****")
798
+ logger.info(f" Num examples = {len(train_dataset)}")
799
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
800
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
801
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
802
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
803
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
804
+ global_step = 0
805
+ first_epoch = 0
806
+ # Potentially load in the weights and states from a previous save
807
+ if args.resume_from_checkpoint:
808
+ if args.resume_from_checkpoint != "latest":
809
+ path = os.path.basename(args.resume_from_checkpoint)
810
+ else:
811
+ # Get the most recent checkpoint
812
+ dirs = os.listdir(args.output_dir)
813
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
814
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
815
+ path = dirs[-1] if len(dirs) > 0 else None
816
+
817
+ if path is None:
818
+ accelerator.print(
819
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
820
+ )
821
+ args.resume_from_checkpoint = None
822
+ else:
823
+ accelerator.print(f"Resuming from checkpoint {path}")
824
+ accelerator.load_state(os.path.join(args.output_dir, path))
825
+ global_step = int(path.split("-")[1])
826
+
827
+ resume_global_step = global_step * args.gradient_accumulation_steps
828
+ first_epoch = global_step // num_update_steps_per_epoch
829
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
830
+
831
+ # Only show the progress bar once on each machine.
832
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
833
+ progress_bar.set_description("Steps")
834
+
835
+ # keep original embeddings as reference
836
+ orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone()
837
+
838
+ for epoch in range(first_epoch, args.num_train_epochs):
839
+ text_encoder.train()
840
+ for step, batch in enumerate(train_dataloader):
841
+ # Skip steps until we reach the resumed step
842
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
843
+ if step % args.gradient_accumulation_steps == 0:
844
+ progress_bar.update(1)
845
+ continue
846
+
847
+ with accelerator.accumulate(text_encoder):
848
+ # Convert images to latent space
849
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()
850
+ latents = latents * vae.config.scaling_factor
851
+
852
+ # Sample noise that we'll add to the latents
853
+ noise = torch.randn_like(latents)
854
+ bsz = latents.shape[0]
855
+ # Sample a random timestep for each image
856
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
857
+ timesteps = timesteps.long()
858
+
859
+ # Add noise to the latents according to the noise magnitude at each timestep
860
+ # (this is the forward diffusion process)
861
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
862
+
863
+ # Get the text embedding for conditioning
864
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype)
865
+
866
+ # Predict the noise residual
867
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
868
+
869
+ # Get the target for loss depending on the prediction type
870
+ if noise_scheduler.config.prediction_type == "epsilon":
871
+ target = noise
872
+ elif noise_scheduler.config.prediction_type == "v_prediction":
873
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
874
+ else:
875
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
876
+
877
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
878
+
879
+ accelerator.backward(loss)
880
+
881
+ optimizer.step()
882
+ lr_scheduler.step()
883
+ optimizer.zero_grad()
884
+
885
+ # Let's make sure we don't update any embedding weights besides the newly added token
886
+ index_no_updates = torch.ones((len(tokenizer),), dtype=torch.bool)
887
+ index_no_updates[min(placeholder_token_ids) : max(placeholder_token_ids) + 1] = False
888
+
889
+ with torch.no_grad():
890
+ accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[index_no_updates] = (
891
+ orig_embeds_params[index_no_updates]
892
+ )
893
+
894
+ # Checks if the accelerator has performed an optimization step behind the scenes
895
+ if accelerator.sync_gradients:
896
+ images = []
897
+ progress_bar.update(1)
898
+ global_step += 1
899
+ if global_step % args.save_steps == 0:
900
+ save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
901
+ save_progress(text_encoder, placeholder_token_ids, accelerator, args, save_path)
902
+
903
+ if accelerator.is_main_process:
904
+ if global_step % args.checkpointing_steps == 0:
905
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
906
+ accelerator.save_state(save_path)
907
+ logger.info(f"Saved state to {save_path}")
908
+
909
+ if args.validation_prompt is not None and global_step % args.validation_steps == 0:
910
+ images = log_validation(
911
+ text_encoder, tokenizer, unet, vae, args, accelerator, weight_dtype, epoch
912
+ )
913
+
914
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
915
+ progress_bar.set_postfix(**logs)
916
+ accelerator.log(logs, step=global_step)
917
+
918
+ if global_step >= args.max_train_steps:
919
+ break
920
+ # Create the pipeline using the trained modules and save it.
921
+ accelerator.wait_for_everyone()
922
+ if accelerator.is_main_process:
923
+ if args.push_to_hub and not args.save_as_full_pipeline:
924
+ logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
925
+ save_full_model = True
926
+ else:
927
+ save_full_model = args.save_as_full_pipeline
928
+ if save_full_model:
929
+ pipeline = StableDiffusionPipeline.from_pretrained(
930
+ args.pretrained_model_name_or_path,
931
+ text_encoder=accelerator.unwrap_model(text_encoder),
932
+ vae=vae,
933
+ unet=unet,
934
+ tokenizer=tokenizer,
935
+ )
936
+ pipeline.save_pretrained(args.output_dir)
937
+ # Save the newly trained embeddings
938
+ save_path = os.path.join(args.output_dir, "learned_embeds.bin")
939
+ save_progress(text_encoder, placeholder_token_ids, accelerator, args, save_path)
940
+
941
+ if args.push_to_hub:
942
+ save_model_card(
943
+ repo_id,
944
+ images=images,
945
+ base_model=args.pretrained_model_name_or_path,
946
+ repo_folder=args.output_dir,
947
+ )
948
+ upload_folder(
949
+ repo_id=repo_id,
950
+ folder_path=args.output_dir,
951
+ commit_message="End of training",
952
+ ignore_patterns=["step_*", "epoch_*"],
953
+ )
954
+
955
+ accelerator.end_training()
956
+
957
+
958
+ if __name__ == "__main__":
959
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Training examples
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
+ #### Use ONNXRuntime to accelerate training
31
+
32
+ In order to leverage onnxruntime to accelerate training, please use train_unconditional_ort.py
33
+
34
+ The command to train a DDPM UNet model on the Oxford Flowers dataset with onnxruntime:
35
+
36
+ ```bash
37
+ accelerate launch train_unconditional.py \
38
+ --dataset_name="huggan/flowers-102-categories" \
39
+ --resolution=64 --center_crop --random_flip \
40
+ --output_dir="ddpm-ema-flowers-64" \
41
+ --use_ema \
42
+ --train_batch_size=16 \
43
+ --num_epochs=1 \
44
+ --gradient_accumulation_steps=1 \
45
+ --learning_rate=1e-4 \
46
+ --lr_warmup_steps=500 \
47
+ --mixed_precision=fp16
48
+ ```
49
+
50
+ Please contact Prathik Rao (prathikr), Sunghoon Choi (hanbitmyths), Ashwini Khade (askhade), or Peng Wang (pengwa) on github with any questions.
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ datasets
4
+ tensorboard
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/train_unconditional.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import inspect
3
+ import logging
4
+ import math
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import accelerate
9
+ import datasets
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from accelerate import Accelerator
13
+ from accelerate.logging import get_logger
14
+ from accelerate.utils import ProjectConfiguration
15
+ from datasets import load_dataset
16
+ from huggingface_hub import create_repo, upload_folder
17
+ from onnxruntime.training.optim.fp16_optimizer import FP16_Optimizer as ORT_FP16_Optimizer
18
+ from onnxruntime.training.ortmodule import ORTModule
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.17.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 parse_args():
56
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
57
+ parser.add_argument(
58
+ "--dataset_name",
59
+ type=str,
60
+ default=None,
61
+ help=(
62
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
63
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
64
+ " or to a folder containing files that HF Datasets can understand."
65
+ ),
66
+ )
67
+ parser.add_argument(
68
+ "--dataset_config_name",
69
+ type=str,
70
+ default=None,
71
+ help="The config of the Dataset, leave as None if there's only one config.",
72
+ )
73
+ parser.add_argument(
74
+ "--model_config_name_or_path",
75
+ type=str,
76
+ default=None,
77
+ help="The config of the UNet model to train, leave as None to use standard DDPM configuration.",
78
+ )
79
+ parser.add_argument(
80
+ "--train_data_dir",
81
+ type=str,
82
+ default=None,
83
+ help=(
84
+ "A folder containing the training data. Folder contents must follow the structure described in"
85
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
86
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
87
+ ),
88
+ )
89
+ parser.add_argument(
90
+ "--output_dir",
91
+ type=str,
92
+ default="ddpm-model-64",
93
+ help="The output directory where the model predictions and checkpoints will be written.",
94
+ )
95
+ parser.add_argument("--overwrite_output_dir", action="store_true")
96
+ parser.add_argument(
97
+ "--cache_dir",
98
+ type=str,
99
+ default=None,
100
+ help="The directory where the downloaded models and datasets will be stored.",
101
+ )
102
+ parser.add_argument(
103
+ "--resolution",
104
+ type=int,
105
+ default=64,
106
+ help=(
107
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
108
+ " resolution"
109
+ ),
110
+ )
111
+ parser.add_argument(
112
+ "--center_crop",
113
+ default=False,
114
+ action="store_true",
115
+ help=(
116
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
117
+ " cropped. The images will be resized to the resolution first before cropping."
118
+ ),
119
+ )
120
+ parser.add_argument(
121
+ "--random_flip",
122
+ default=False,
123
+ action="store_true",
124
+ help="whether to randomly flip images horizontally",
125
+ )
126
+ parser.add_argument(
127
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
128
+ )
129
+ parser.add_argument(
130
+ "--eval_batch_size", type=int, default=16, help="The number of images to generate for evaluation."
131
+ )
132
+ parser.add_argument(
133
+ "--dataloader_num_workers",
134
+ type=int,
135
+ default=0,
136
+ help=(
137
+ "The number of subprocesses to use for data loading. 0 means that the data will be loaded in the main"
138
+ " process."
139
+ ),
140
+ )
141
+ parser.add_argument("--num_epochs", type=int, default=100)
142
+ parser.add_argument("--save_images_epochs", type=int, default=10, help="How often to save images during training.")
143
+ parser.add_argument(
144
+ "--save_model_epochs", type=int, default=10, help="How often to save the model during training."
145
+ )
146
+ parser.add_argument(
147
+ "--gradient_accumulation_steps",
148
+ type=int,
149
+ default=1,
150
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
151
+ )
152
+ parser.add_argument(
153
+ "--learning_rate",
154
+ type=float,
155
+ default=1e-4,
156
+ help="Initial learning rate (after the potential warmup period) to use.",
157
+ )
158
+ parser.add_argument(
159
+ "--lr_scheduler",
160
+ type=str,
161
+ default="cosine",
162
+ help=(
163
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
164
+ ' "constant", "constant_with_warmup"]'
165
+ ),
166
+ )
167
+ parser.add_argument(
168
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
169
+ )
170
+ parser.add_argument("--adam_beta1", type=float, default=0.95, help="The beta1 parameter for the Adam optimizer.")
171
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
172
+ parser.add_argument(
173
+ "--adam_weight_decay", type=float, default=1e-6, help="Weight decay magnitude for the Adam optimizer."
174
+ )
175
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer.")
176
+ parser.add_argument(
177
+ "--use_ema",
178
+ action="store_true",
179
+ help="Whether to use Exponential Moving Average for the final model weights.",
180
+ )
181
+ parser.add_argument("--ema_inv_gamma", type=float, default=1.0, help="The inverse gamma value for the EMA decay.")
182
+ parser.add_argument("--ema_power", type=float, default=3 / 4, help="The power value for the EMA decay.")
183
+ parser.add_argument("--ema_max_decay", type=float, default=0.9999, help="The maximum decay magnitude for EMA.")
184
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
185
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
186
+ parser.add_argument(
187
+ "--hub_model_id",
188
+ type=str,
189
+ default=None,
190
+ help="The name of the repository to keep in sync with the local `output_dir`.",
191
+ )
192
+ parser.add_argument(
193
+ "--hub_private_repo", action="store_true", help="Whether or not to create a private repository."
194
+ )
195
+ parser.add_argument(
196
+ "--logger",
197
+ type=str,
198
+ default="tensorboard",
199
+ choices=["tensorboard", "wandb"],
200
+ help=(
201
+ "Whether to use [tensorboard](https://www.tensorflow.org/tensorboard) or [wandb](https://www.wandb.ai)"
202
+ " for experiment tracking and logging of model metrics and model checkpoints"
203
+ ),
204
+ )
205
+ parser.add_argument(
206
+ "--logging_dir",
207
+ type=str,
208
+ default="logs",
209
+ help=(
210
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
211
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
212
+ ),
213
+ )
214
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
215
+ parser.add_argument(
216
+ "--mixed_precision",
217
+ type=str,
218
+ default="no",
219
+ choices=["no", "fp16", "bf16"],
220
+ help=(
221
+ "Whether to use mixed precision. Choose"
222
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
223
+ "and an Nvidia Ampere GPU."
224
+ ),
225
+ )
226
+ parser.add_argument(
227
+ "--prediction_type",
228
+ type=str,
229
+ default="epsilon",
230
+ choices=["epsilon", "sample"],
231
+ help="Whether the model should predict the 'epsilon'/noise error or directly the reconstructed image 'x0'.",
232
+ )
233
+ parser.add_argument("--ddpm_num_steps", type=int, default=1000)
234
+ parser.add_argument("--ddpm_num_inference_steps", type=int, default=1000)
235
+ parser.add_argument("--ddpm_beta_schedule", type=str, default="linear")
236
+ parser.add_argument(
237
+ "--checkpointing_steps",
238
+ type=int,
239
+ default=500,
240
+ help=(
241
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
242
+ " training using `--resume_from_checkpoint`."
243
+ ),
244
+ )
245
+ parser.add_argument(
246
+ "--checkpoints_total_limit",
247
+ type=int,
248
+ default=None,
249
+ help=(
250
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
251
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
252
+ " for more docs"
253
+ ),
254
+ )
255
+ parser.add_argument(
256
+ "--resume_from_checkpoint",
257
+ type=str,
258
+ default=None,
259
+ help=(
260
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
261
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
262
+ ),
263
+ )
264
+ parser.add_argument(
265
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
266
+ )
267
+
268
+ args = parser.parse_args()
269
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
270
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
271
+ args.local_rank = env_local_rank
272
+
273
+ if args.dataset_name is None and args.train_data_dir is None:
274
+ raise ValueError("You must specify either a dataset name from the hub or a train data directory.")
275
+
276
+ return args
277
+
278
+
279
+ def main(args):
280
+ if args.report_to == "wandb" and args.hub_token is not None:
281
+ raise ValueError(
282
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
283
+ " Please use `hf auth login` to authenticate with the Hub."
284
+ )
285
+
286
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
287
+ accelerator_project_config = ProjectConfiguration(
288
+ total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
289
+ )
290
+
291
+ accelerator = Accelerator(
292
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
293
+ mixed_precision=args.mixed_precision,
294
+ log_with=args.report_to,
295
+ project_config=accelerator_project_config,
296
+ )
297
+
298
+ # Disable AMP for MPS.
299
+ if torch.backends.mps.is_available():
300
+ accelerator.native_amp = False
301
+
302
+ if args.logger == "tensorboard":
303
+ if not is_tensorboard_available():
304
+ raise ImportError("Make sure to install tensorboard if you want to use it for logging during training.")
305
+
306
+ elif args.logger == "wandb":
307
+ if not is_wandb_available():
308
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
309
+ import wandb
310
+
311
+ # `accelerate` 0.16.0 will have better support for customized saving
312
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
313
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
314
+ def save_model_hook(models, weights, output_dir):
315
+ if accelerator.is_main_process:
316
+ if args.use_ema:
317
+ ema_model.save_pretrained(os.path.join(output_dir, "unet_ema"))
318
+
319
+ for i, model in enumerate(models):
320
+ model.save_pretrained(os.path.join(output_dir, "unet"))
321
+
322
+ # make sure to pop weight so that corresponding model is not saved again
323
+ weights.pop()
324
+
325
+ def load_model_hook(models, input_dir):
326
+ if args.use_ema:
327
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DModel)
328
+ ema_model.load_state_dict(load_model.state_dict())
329
+ ema_model.to(accelerator.device)
330
+ del load_model
331
+
332
+ for i in range(len(models)):
333
+ # pop models so that they are not loaded again
334
+ model = models.pop()
335
+
336
+ # load diffusers style into model
337
+ load_model = UNet2DModel.from_pretrained(input_dir, subfolder="unet")
338
+ model.register_to_config(**load_model.config)
339
+
340
+ model.load_state_dict(load_model.state_dict())
341
+ del load_model
342
+
343
+ accelerator.register_save_state_pre_hook(save_model_hook)
344
+ accelerator.register_load_state_pre_hook(load_model_hook)
345
+
346
+ # Make one log on every process with the configuration for debugging.
347
+ logging.basicConfig(
348
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
349
+ datefmt="%m/%d/%Y %H:%M:%S",
350
+ level=logging.INFO,
351
+ )
352
+ logger.info(accelerator.state, main_process_only=False)
353
+ if accelerator.is_local_main_process:
354
+ datasets.utils.logging.set_verbosity_warning()
355
+ diffusers.utils.logging.set_verbosity_info()
356
+ else:
357
+ datasets.utils.logging.set_verbosity_error()
358
+ diffusers.utils.logging.set_verbosity_error()
359
+
360
+ # Handle the repository creation
361
+ if accelerator.is_main_process:
362
+ if args.output_dir is not None:
363
+ os.makedirs(args.output_dir, exist_ok=True)
364
+
365
+ if args.push_to_hub:
366
+ repo_id = create_repo(
367
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
368
+ ).repo_id
369
+
370
+ # Initialize the model
371
+ if args.model_config_name_or_path is None:
372
+ model = UNet2DModel(
373
+ sample_size=args.resolution,
374
+ in_channels=3,
375
+ out_channels=3,
376
+ layers_per_block=2,
377
+ block_out_channels=(128, 128, 256, 256, 512, 512),
378
+ down_block_types=(
379
+ "DownBlock2D",
380
+ "DownBlock2D",
381
+ "DownBlock2D",
382
+ "DownBlock2D",
383
+ "AttnDownBlock2D",
384
+ "DownBlock2D",
385
+ ),
386
+ up_block_types=(
387
+ "UpBlock2D",
388
+ "AttnUpBlock2D",
389
+ "UpBlock2D",
390
+ "UpBlock2D",
391
+ "UpBlock2D",
392
+ "UpBlock2D",
393
+ ),
394
+ )
395
+ else:
396
+ config = UNet2DModel.load_config(args.model_config_name_or_path)
397
+ model = UNet2DModel.from_config(config)
398
+
399
+ # Create EMA for the model.
400
+ if args.use_ema:
401
+ ema_model = EMAModel(
402
+ model.parameters(),
403
+ decay=args.ema_max_decay,
404
+ use_ema_warmup=True,
405
+ inv_gamma=args.ema_inv_gamma,
406
+ power=args.ema_power,
407
+ model_cls=UNet2DModel,
408
+ model_config=model.config,
409
+ )
410
+
411
+ if args.enable_xformers_memory_efficient_attention:
412
+ if is_xformers_available():
413
+ import xformers
414
+
415
+ xformers_version = version.parse(xformers.__version__)
416
+ if xformers_version == version.parse("0.0.16"):
417
+ logger.warning(
418
+ "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."
419
+ )
420
+ model.enable_xformers_memory_efficient_attention()
421
+ else:
422
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
423
+
424
+ # Initialize the scheduler
425
+ accepts_prediction_type = "prediction_type" in set(inspect.signature(DDPMScheduler.__init__).parameters.keys())
426
+ if accepts_prediction_type:
427
+ noise_scheduler = DDPMScheduler(
428
+ num_train_timesteps=args.ddpm_num_steps,
429
+ beta_schedule=args.ddpm_beta_schedule,
430
+ prediction_type=args.prediction_type,
431
+ )
432
+ else:
433
+ noise_scheduler = DDPMScheduler(num_train_timesteps=args.ddpm_num_steps, beta_schedule=args.ddpm_beta_schedule)
434
+
435
+ # Initialize the optimizer
436
+ optimizer = torch.optim.AdamW(
437
+ model.parameters(),
438
+ lr=args.learning_rate,
439
+ betas=(args.adam_beta1, args.adam_beta2),
440
+ weight_decay=args.adam_weight_decay,
441
+ eps=args.adam_epsilon,
442
+ )
443
+
444
+ optimizer = ORT_FP16_Optimizer(optimizer)
445
+
446
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
447
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
448
+
449
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
450
+ # download the dataset.
451
+ if args.dataset_name is not None:
452
+ dataset = load_dataset(
453
+ args.dataset_name,
454
+ args.dataset_config_name,
455
+ cache_dir=args.cache_dir,
456
+ split="train",
457
+ )
458
+ else:
459
+ dataset = load_dataset("imagefolder", data_dir=args.train_data_dir, cache_dir=args.cache_dir, split="train")
460
+ # See more about loading custom images at
461
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
462
+
463
+ # Preprocessing the datasets and DataLoaders creation.
464
+ augmentations = transforms.Compose(
465
+ [
466
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
467
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
468
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
469
+ transforms.ToTensor(),
470
+ transforms.Normalize([0.5], [0.5]),
471
+ ]
472
+ )
473
+
474
+ def transform_images(examples):
475
+ images = [augmentations(image.convert("RGB")) for image in examples["image"]]
476
+ return {"input": images}
477
+
478
+ logger.info(f"Dataset size: {len(dataset)}")
479
+
480
+ dataset.set_transform(transform_images)
481
+ train_dataloader = torch.utils.data.DataLoader(
482
+ dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
483
+ )
484
+
485
+ # Initialize the learning rate scheduler
486
+ lr_scheduler = get_scheduler(
487
+ args.lr_scheduler,
488
+ optimizer=optimizer,
489
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
490
+ num_training_steps=(len(train_dataloader) * args.num_epochs),
491
+ )
492
+
493
+ # Prepare everything with our `accelerator`.
494
+ model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
495
+ model, optimizer, train_dataloader, lr_scheduler
496
+ )
497
+
498
+ if args.use_ema:
499
+ ema_model.to(accelerator.device)
500
+
501
+ # We need to initialize the trackers we use, and also store our configuration.
502
+ # The trackers initializes automatically on the main process.
503
+ if accelerator.is_main_process:
504
+ run = os.path.split(__file__)[-1].split(".")[0]
505
+ accelerator.init_trackers(run)
506
+
507
+ model = ORTModule(model)
508
+
509
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
510
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
511
+ max_train_steps = args.num_epochs * num_update_steps_per_epoch
512
+
513
+ logger.info("***** Running training *****")
514
+ logger.info(f" Num examples = {len(dataset)}")
515
+ logger.info(f" Num Epochs = {args.num_epochs}")
516
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
517
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
518
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
519
+ logger.info(f" Total optimization steps = {max_train_steps}")
520
+
521
+ global_step = 0
522
+ first_epoch = 0
523
+
524
+ # Potentially load in the weights and states from a previous save
525
+ if args.resume_from_checkpoint:
526
+ if args.resume_from_checkpoint != "latest":
527
+ path = os.path.basename(args.resume_from_checkpoint)
528
+ else:
529
+ # Get the most recent checkpoint
530
+ dirs = os.listdir(args.output_dir)
531
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
532
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
533
+ path = dirs[-1] if len(dirs) > 0 else None
534
+
535
+ if path is None:
536
+ accelerator.print(
537
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
538
+ )
539
+ args.resume_from_checkpoint = None
540
+ else:
541
+ accelerator.print(f"Resuming from checkpoint {path}")
542
+ accelerator.load_state(os.path.join(args.output_dir, path))
543
+ global_step = int(path.split("-")[1])
544
+
545
+ resume_global_step = global_step * args.gradient_accumulation_steps
546
+ first_epoch = global_step // num_update_steps_per_epoch
547
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
548
+
549
+ # Train!
550
+ for epoch in range(first_epoch, args.num_epochs):
551
+ model.train()
552
+ progress_bar = tqdm(total=num_update_steps_per_epoch, disable=not accelerator.is_local_main_process)
553
+ progress_bar.set_description(f"Epoch {epoch}")
554
+ for step, batch in enumerate(train_dataloader):
555
+ # Skip steps until we reach the resumed step
556
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
557
+ if step % args.gradient_accumulation_steps == 0:
558
+ progress_bar.update(1)
559
+ continue
560
+
561
+ clean_images = batch["input"]
562
+ # Sample noise that we'll add to the images
563
+ noise = torch.randn(
564
+ clean_images.shape, dtype=(torch.float32 if args.mixed_precision == "no" else torch.float16)
565
+ ).to(clean_images.device)
566
+ bsz = clean_images.shape[0]
567
+ # Sample a random timestep for each image
568
+ timesteps = torch.randint(
569
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=clean_images.device
570
+ ).long()
571
+
572
+ # Add noise to the clean images according to the noise magnitude at each timestep
573
+ # (this is the forward diffusion process)
574
+ noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
575
+
576
+ with accelerator.accumulate(model):
577
+ # Predict the noise residual
578
+ model_output = model(noisy_images, timesteps, return_dict=False)[0]
579
+
580
+ if args.prediction_type == "epsilon":
581
+ loss = F.mse_loss(model_output, noise) # this could have different weights!
582
+ elif args.prediction_type == "sample":
583
+ alpha_t = _extract_into_tensor(
584
+ noise_scheduler.alphas_cumprod, timesteps, (clean_images.shape[0], 1, 1, 1)
585
+ )
586
+ snr_weights = alpha_t / (1 - alpha_t)
587
+ loss = snr_weights * F.mse_loss(
588
+ model_output, clean_images, reduction="none"
589
+ ) # use SNR weighting from distillation paper
590
+ loss = loss.mean()
591
+ else:
592
+ raise ValueError(f"Unsupported prediction type: {args.prediction_type}")
593
+
594
+ accelerator.backward(loss)
595
+
596
+ if accelerator.sync_gradients:
597
+ accelerator.clip_grad_norm_(model.parameters(), 1.0)
598
+ optimizer.step()
599
+ lr_scheduler.step()
600
+ optimizer.zero_grad()
601
+
602
+ # Checks if the accelerator has performed an optimization step behind the scenes
603
+ if accelerator.sync_gradients:
604
+ if args.use_ema:
605
+ ema_model.step(model.parameters())
606
+ progress_bar.update(1)
607
+ global_step += 1
608
+
609
+ if global_step % args.checkpointing_steps == 0:
610
+ if accelerator.is_main_process:
611
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
612
+ accelerator.save_state(save_path)
613
+ logger.info(f"Saved state to {save_path}")
614
+
615
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
616
+ if args.use_ema:
617
+ logs["ema_decay"] = ema_model.cur_decay_value
618
+ progress_bar.set_postfix(**logs)
619
+ accelerator.log(logs, step=global_step)
620
+ progress_bar.close()
621
+
622
+ accelerator.wait_for_everyone()
623
+
624
+ # Generate sample images for visual inspection
625
+ if accelerator.is_main_process:
626
+ if epoch % args.save_images_epochs == 0 or epoch == args.num_epochs - 1:
627
+ unet = accelerator.unwrap_model(model)
628
+
629
+ if args.use_ema:
630
+ ema_model.store(unet.parameters())
631
+ ema_model.copy_to(unet.parameters())
632
+
633
+ pipeline = DDPMPipeline(
634
+ unet=unet,
635
+ scheduler=noise_scheduler,
636
+ )
637
+
638
+ generator = torch.Generator(device=pipeline.device).manual_seed(0)
639
+ # run pipeline in inference (sample random noise and denoise)
640
+ images = pipeline(
641
+ generator=generator,
642
+ batch_size=args.eval_batch_size,
643
+ num_inference_steps=args.ddpm_num_inference_steps,
644
+ output_type="np",
645
+ ).images
646
+
647
+ if args.use_ema:
648
+ ema_model.restore(unet.parameters())
649
+
650
+ # denormalize the images and save to tensorboard
651
+ images_processed = (images * 255).round().astype("uint8")
652
+
653
+ if args.logger == "tensorboard":
654
+ if is_accelerate_version(">=", "0.17.0.dev0"):
655
+ tracker = accelerator.get_tracker("tensorboard", unwrap=True)
656
+ else:
657
+ tracker = accelerator.get_tracker("tensorboard")
658
+ tracker.add_images("test_samples", images_processed.transpose(0, 3, 1, 2), epoch)
659
+ elif args.logger == "wandb":
660
+ # Upcoming `log_images` helper coming in https://github.com/huggingface/accelerate/pull/962/files
661
+ accelerator.get_tracker("wandb").log(
662
+ {"test_samples": [wandb.Image(img) for img in images_processed], "epoch": epoch},
663
+ step=global_step,
664
+ )
665
+
666
+ if epoch % args.save_model_epochs == 0 or epoch == args.num_epochs - 1:
667
+ # save the model
668
+ unet = accelerator.unwrap_model(model)
669
+
670
+ if args.use_ema:
671
+ ema_model.store(unet.parameters())
672
+ ema_model.copy_to(unet.parameters())
673
+
674
+ pipeline = DDPMPipeline(
675
+ unet=unet,
676
+ scheduler=noise_scheduler,
677
+ )
678
+
679
+ pipeline.save_pretrained(args.output_dir)
680
+
681
+ if args.use_ema:
682
+ ema_model.restore(unet.parameters())
683
+
684
+ if args.push_to_hub:
685
+ upload_folder(
686
+ repo_id=repo_id,
687
+ folder_path=args.output_dir,
688
+ commit_message=f"Epoch {epoch}",
689
+ ignore_patterns=["step_*", "epoch_*"],
690
+ )
691
+
692
+ accelerator.end_training()
693
+
694
+
695
+ if __name__ == "__main__":
696
+ args = parse_args()
697
+ main(args)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ images/
2
+ output/
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/controlnet_pixart_alpha.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
7
+ from diffusers.models import PixArtTransformer2DModel
8
+ from diffusers.models.attention import BasicTransformerBlock
9
+ from diffusers.models.modeling_outputs import Transformer2DModelOutput
10
+ from diffusers.models.modeling_utils import ModelMixin
11
+
12
+
13
+ class PixArtControlNetAdapterBlock(nn.Module):
14
+ def __init__(
15
+ self,
16
+ block_index,
17
+ # taken from PixArtTransformer2DModel
18
+ num_attention_heads: int = 16,
19
+ attention_head_dim: int = 72,
20
+ dropout: float = 0.0,
21
+ cross_attention_dim: Optional[int] = 1152,
22
+ attention_bias: bool = True,
23
+ activation_fn: str = "gelu-approximate",
24
+ num_embeds_ada_norm: Optional[int] = 1000,
25
+ upcast_attention: bool = False,
26
+ norm_type: str = "ada_norm_single",
27
+ norm_elementwise_affine: bool = False,
28
+ norm_eps: float = 1e-6,
29
+ attention_type: Optional[str] = "default",
30
+ ):
31
+ super().__init__()
32
+
33
+ self.block_index = block_index
34
+ self.inner_dim = num_attention_heads * attention_head_dim
35
+
36
+ # the first block has a zero before layer
37
+ if self.block_index == 0:
38
+ self.before_proj = nn.Linear(self.inner_dim, self.inner_dim)
39
+ nn.init.zeros_(self.before_proj.weight)
40
+ nn.init.zeros_(self.before_proj.bias)
41
+
42
+ self.transformer_block = BasicTransformerBlock(
43
+ self.inner_dim,
44
+ num_attention_heads,
45
+ attention_head_dim,
46
+ dropout=dropout,
47
+ cross_attention_dim=cross_attention_dim,
48
+ activation_fn=activation_fn,
49
+ num_embeds_ada_norm=num_embeds_ada_norm,
50
+ attention_bias=attention_bias,
51
+ upcast_attention=upcast_attention,
52
+ norm_type=norm_type,
53
+ norm_elementwise_affine=norm_elementwise_affine,
54
+ norm_eps=norm_eps,
55
+ attention_type=attention_type,
56
+ )
57
+
58
+ self.after_proj = nn.Linear(self.inner_dim, self.inner_dim)
59
+ nn.init.zeros_(self.after_proj.weight)
60
+ nn.init.zeros_(self.after_proj.bias)
61
+
62
+ def train(self, mode: bool = True):
63
+ self.transformer_block.train(mode)
64
+
65
+ if self.block_index == 0:
66
+ self.before_proj.train(mode)
67
+
68
+ self.after_proj.train(mode)
69
+
70
+ def forward(
71
+ self,
72
+ hidden_states: torch.Tensor,
73
+ controlnet_states: torch.Tensor,
74
+ encoder_hidden_states: Optional[torch.Tensor] = None,
75
+ timestep: Optional[torch.LongTensor] = None,
76
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
77
+ cross_attention_kwargs: Dict[str, Any] = None,
78
+ attention_mask: Optional[torch.Tensor] = None,
79
+ encoder_attention_mask: Optional[torch.Tensor] = None,
80
+ ):
81
+ if self.block_index == 0:
82
+ controlnet_states = self.before_proj(controlnet_states)
83
+ controlnet_states = hidden_states + controlnet_states
84
+
85
+ controlnet_states_down = self.transformer_block(
86
+ hidden_states=controlnet_states,
87
+ encoder_hidden_states=encoder_hidden_states,
88
+ timestep=timestep,
89
+ added_cond_kwargs=added_cond_kwargs,
90
+ cross_attention_kwargs=cross_attention_kwargs,
91
+ attention_mask=attention_mask,
92
+ encoder_attention_mask=encoder_attention_mask,
93
+ class_labels=None,
94
+ )
95
+
96
+ controlnet_states_left = self.after_proj(controlnet_states_down)
97
+
98
+ return controlnet_states_left, controlnet_states_down
99
+
100
+
101
+ class PixArtControlNetAdapterModel(ModelMixin, ConfigMixin):
102
+ # N=13, as specified in the paper https://arxiv.org/html/2401.05252v1/#S4 ControlNet-Transformer
103
+ @register_to_config
104
+ def __init__(self, num_layers=13) -> None:
105
+ super().__init__()
106
+
107
+ self.num_layers = num_layers
108
+
109
+ self.controlnet_blocks = nn.ModuleList(
110
+ [PixArtControlNetAdapterBlock(block_index=i) for i in range(num_layers)]
111
+ )
112
+
113
+ @classmethod
114
+ def from_transformer(cls, transformer: PixArtTransformer2DModel):
115
+ control_net = PixArtControlNetAdapterModel()
116
+
117
+ # copied the specified number of blocks from the transformer
118
+ for depth in range(control_net.num_layers):
119
+ control_net.controlnet_blocks[depth].transformer_block.load_state_dict(
120
+ transformer.transformer_blocks[depth].state_dict()
121
+ )
122
+
123
+ return control_net
124
+
125
+ def train(self, mode: bool = True):
126
+ for block in self.controlnet_blocks:
127
+ block.train(mode)
128
+
129
+
130
+ class PixArtControlNetTransformerModel(ModelMixin, ConfigMixin):
131
+ def __init__(
132
+ self,
133
+ transformer: PixArtTransformer2DModel,
134
+ controlnet: PixArtControlNetAdapterModel,
135
+ blocks_num=13,
136
+ init_from_transformer=False,
137
+ training=False,
138
+ ):
139
+ super().__init__()
140
+
141
+ self.blocks_num = blocks_num
142
+ self.gradient_checkpointing = False
143
+ self.register_to_config(**transformer.config)
144
+ self.training = training
145
+
146
+ if init_from_transformer:
147
+ # copies the specified number of blocks from the transformer
148
+ controlnet.from_transformer(transformer, self.blocks_num)
149
+
150
+ self.transformer = transformer
151
+ self.controlnet = controlnet
152
+
153
+ def forward(
154
+ self,
155
+ hidden_states: torch.Tensor,
156
+ encoder_hidden_states: Optional[torch.Tensor] = None,
157
+ timestep: Optional[torch.LongTensor] = None,
158
+ controlnet_cond: Optional[torch.Tensor] = None,
159
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
160
+ cross_attention_kwargs: Dict[str, Any] = None,
161
+ attention_mask: Optional[torch.Tensor] = None,
162
+ encoder_attention_mask: Optional[torch.Tensor] = None,
163
+ return_dict: bool = True,
164
+ ):
165
+ if self.transformer.use_additional_conditions and added_cond_kwargs is None:
166
+ raise ValueError("`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`.")
167
+
168
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
169
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
170
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
171
+ # expects mask of shape:
172
+ # [batch, key_tokens]
173
+ # adds singleton query_tokens dimension:
174
+ # [batch, 1, key_tokens]
175
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
176
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
177
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
178
+ if attention_mask is not None and attention_mask.ndim == 2:
179
+ # assume that mask is expressed as:
180
+ # (1 = keep, 0 = discard)
181
+ # convert mask into a bias that can be added to attention scores:
182
+ # (keep = +0, discard = -10000.0)
183
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
184
+ attention_mask = attention_mask.unsqueeze(1)
185
+
186
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
187
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
188
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
189
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
190
+
191
+ # 1. Input
192
+ batch_size = hidden_states.shape[0]
193
+ height, width = (
194
+ hidden_states.shape[-2] // self.transformer.config.patch_size,
195
+ hidden_states.shape[-1] // self.transformer.config.patch_size,
196
+ )
197
+ hidden_states = self.transformer.pos_embed(hidden_states)
198
+
199
+ timestep, embedded_timestep = self.transformer.adaln_single(
200
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
201
+ )
202
+
203
+ if self.transformer.caption_projection is not None:
204
+ encoder_hidden_states = self.transformer.caption_projection(encoder_hidden_states)
205
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
206
+
207
+ controlnet_states_down = None
208
+ if controlnet_cond is not None:
209
+ controlnet_states_down = self.transformer.pos_embed(controlnet_cond)
210
+
211
+ # 2. Blocks
212
+ for block_index, block in enumerate(self.transformer.transformer_blocks):
213
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
214
+ # rc todo: for training and gradient checkpointing
215
+ print("Gradient checkpointing is not supported for the controlnet transformer model, yet.")
216
+ exit(1)
217
+
218
+ hidden_states = self._gradient_checkpointing_func(
219
+ block,
220
+ hidden_states,
221
+ attention_mask,
222
+ encoder_hidden_states,
223
+ encoder_attention_mask,
224
+ timestep,
225
+ cross_attention_kwargs,
226
+ None,
227
+ )
228
+ else:
229
+ # the control nets are only used for the blocks 1 to self.blocks_num
230
+ if block_index > 0 and block_index <= self.blocks_num and controlnet_states_down is not None:
231
+ controlnet_states_left, controlnet_states_down = self.controlnet.controlnet_blocks[
232
+ block_index - 1
233
+ ](
234
+ hidden_states=hidden_states, # used only in the first block
235
+ controlnet_states=controlnet_states_down,
236
+ encoder_hidden_states=encoder_hidden_states,
237
+ timestep=timestep,
238
+ added_cond_kwargs=added_cond_kwargs,
239
+ cross_attention_kwargs=cross_attention_kwargs,
240
+ attention_mask=attention_mask,
241
+ encoder_attention_mask=encoder_attention_mask,
242
+ )
243
+
244
+ hidden_states = hidden_states + controlnet_states_left
245
+
246
+ hidden_states = block(
247
+ hidden_states,
248
+ attention_mask=attention_mask,
249
+ encoder_hidden_states=encoder_hidden_states,
250
+ encoder_attention_mask=encoder_attention_mask,
251
+ timestep=timestep,
252
+ cross_attention_kwargs=cross_attention_kwargs,
253
+ class_labels=None,
254
+ )
255
+
256
+ # 3. Output
257
+ shift, scale = (
258
+ self.transformer.scale_shift_table[None]
259
+ + embedded_timestep[:, None].to(self.transformer.scale_shift_table.device)
260
+ ).chunk(2, dim=1)
261
+ hidden_states = self.transformer.norm_out(hidden_states)
262
+ # Modulation
263
+ hidden_states = hidden_states * (1 + scale.to(hidden_states.device)) + shift.to(hidden_states.device)
264
+ hidden_states = self.transformer.proj_out(hidden_states)
265
+ hidden_states = hidden_states.squeeze(1)
266
+
267
+ # unpatchify
268
+ hidden_states = hidden_states.reshape(
269
+ shape=(
270
+ -1,
271
+ height,
272
+ width,
273
+ self.transformer.config.patch_size,
274
+ self.transformer.config.patch_size,
275
+ self.transformer.out_channels,
276
+ )
277
+ )
278
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
279
+ output = hidden_states.reshape(
280
+ shape=(
281
+ -1,
282
+ self.transformer.out_channels,
283
+ height * self.transformer.config.patch_size,
284
+ width * self.transformer.config.patch_size,
285
+ )
286
+ )
287
+
288
+ if not return_dict:
289
+ return (output,)
290
+
291
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/pipeline_pixart_alpha_controlnet.py ADDED
@@ -0,0 +1,1098 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 PixArt-Alpha Authors 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
+ import html
16
+ import inspect
17
+ import re
18
+ import urllib.parse as ul
19
+ from typing import Callable, List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import PIL
23
+ import torch
24
+ from controlnet_pixart_alpha import PixArtControlNetAdapterModel, PixArtControlNetTransformerModel
25
+ from transformers import T5EncoderModel, T5Tokenizer
26
+
27
+ from diffusers.image_processor import PipelineImageInput, PixArtImageProcessor
28
+ from diffusers.models import AutoencoderKL, PixArtTransformer2DModel
29
+ from diffusers.pipelines import DiffusionPipeline, ImagePipelineOutput
30
+ from diffusers.schedulers import DPMSolverMultistepScheduler
31
+ from diffusers.utils import (
32
+ BACKENDS_MAPPING,
33
+ deprecate,
34
+ is_bs4_available,
35
+ is_ftfy_available,
36
+ logging,
37
+ replace_example_docstring,
38
+ )
39
+ from diffusers.utils.torch_utils import randn_tensor
40
+
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_bs4_available():
45
+ from bs4 import BeautifulSoup
46
+
47
+ if is_ftfy_available():
48
+ import ftfy
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```py
53
+ >>> import torch
54
+ >>> from diffusers import PixArtAlphaPipeline
55
+
56
+ >>> # You can replace the checkpoint id with "PixArt-alpha/PixArt-XL-2-512x512" too.
57
+ >>> pipe = PixArtAlphaPipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16)
58
+ >>> # Enable memory optimizations.
59
+ >>> pipe.enable_model_cpu_offload()
60
+
61
+ >>> prompt = "A small cactus with a happy face in the Sahara desert."
62
+ >>> image = pipe(prompt).images[0]
63
+ ```
64
+ """
65
+
66
+ ASPECT_RATIO_1024_BIN = {
67
+ "0.25": [512.0, 2048.0],
68
+ "0.28": [512.0, 1856.0],
69
+ "0.32": [576.0, 1792.0],
70
+ "0.33": [576.0, 1728.0],
71
+ "0.35": [576.0, 1664.0],
72
+ "0.4": [640.0, 1600.0],
73
+ "0.42": [640.0, 1536.0],
74
+ "0.48": [704.0, 1472.0],
75
+ "0.5": [704.0, 1408.0],
76
+ "0.52": [704.0, 1344.0],
77
+ "0.57": [768.0, 1344.0],
78
+ "0.6": [768.0, 1280.0],
79
+ "0.68": [832.0, 1216.0],
80
+ "0.72": [832.0, 1152.0],
81
+ "0.78": [896.0, 1152.0],
82
+ "0.82": [896.0, 1088.0],
83
+ "0.88": [960.0, 1088.0],
84
+ "0.94": [960.0, 1024.0],
85
+ "1.0": [1024.0, 1024.0],
86
+ "1.07": [1024.0, 960.0],
87
+ "1.13": [1088.0, 960.0],
88
+ "1.21": [1088.0, 896.0],
89
+ "1.29": [1152.0, 896.0],
90
+ "1.38": [1152.0, 832.0],
91
+ "1.46": [1216.0, 832.0],
92
+ "1.67": [1280.0, 768.0],
93
+ "1.75": [1344.0, 768.0],
94
+ "2.0": [1408.0, 704.0],
95
+ "2.09": [1472.0, 704.0],
96
+ "2.4": [1536.0, 640.0],
97
+ "2.5": [1600.0, 640.0],
98
+ "3.0": [1728.0, 576.0],
99
+ "4.0": [2048.0, 512.0],
100
+ }
101
+
102
+ ASPECT_RATIO_512_BIN = {
103
+ "0.25": [256.0, 1024.0],
104
+ "0.28": [256.0, 928.0],
105
+ "0.32": [288.0, 896.0],
106
+ "0.33": [288.0, 864.0],
107
+ "0.35": [288.0, 832.0],
108
+ "0.4": [320.0, 800.0],
109
+ "0.42": [320.0, 768.0],
110
+ "0.48": [352.0, 736.0],
111
+ "0.5": [352.0, 704.0],
112
+ "0.52": [352.0, 672.0],
113
+ "0.57": [384.0, 672.0],
114
+ "0.6": [384.0, 640.0],
115
+ "0.68": [416.0, 608.0],
116
+ "0.72": [416.0, 576.0],
117
+ "0.78": [448.0, 576.0],
118
+ "0.82": [448.0, 544.0],
119
+ "0.88": [480.0, 544.0],
120
+ "0.94": [480.0, 512.0],
121
+ "1.0": [512.0, 512.0],
122
+ "1.07": [512.0, 480.0],
123
+ "1.13": [544.0, 480.0],
124
+ "1.21": [544.0, 448.0],
125
+ "1.29": [576.0, 448.0],
126
+ "1.38": [576.0, 416.0],
127
+ "1.46": [608.0, 416.0],
128
+ "1.67": [640.0, 384.0],
129
+ "1.75": [672.0, 384.0],
130
+ "2.0": [704.0, 352.0],
131
+ "2.09": [736.0, 352.0],
132
+ "2.4": [768.0, 320.0],
133
+ "2.5": [800.0, 320.0],
134
+ "3.0": [864.0, 288.0],
135
+ "4.0": [1024.0, 256.0],
136
+ }
137
+
138
+ ASPECT_RATIO_256_BIN = {
139
+ "0.25": [128.0, 512.0],
140
+ "0.28": [128.0, 464.0],
141
+ "0.32": [144.0, 448.0],
142
+ "0.33": [144.0, 432.0],
143
+ "0.35": [144.0, 416.0],
144
+ "0.4": [160.0, 400.0],
145
+ "0.42": [160.0, 384.0],
146
+ "0.48": [176.0, 368.0],
147
+ "0.5": [176.0, 352.0],
148
+ "0.52": [176.0, 336.0],
149
+ "0.57": [192.0, 336.0],
150
+ "0.6": [192.0, 320.0],
151
+ "0.68": [208.0, 304.0],
152
+ "0.72": [208.0, 288.0],
153
+ "0.78": [224.0, 288.0],
154
+ "0.82": [224.0, 272.0],
155
+ "0.88": [240.0, 272.0],
156
+ "0.94": [240.0, 256.0],
157
+ "1.0": [256.0, 256.0],
158
+ "1.07": [256.0, 240.0],
159
+ "1.13": [272.0, 240.0],
160
+ "1.21": [272.0, 224.0],
161
+ "1.29": [288.0, 224.0],
162
+ "1.38": [288.0, 208.0],
163
+ "1.46": [304.0, 208.0],
164
+ "1.67": [320.0, 192.0],
165
+ "1.75": [336.0, 192.0],
166
+ "2.0": [352.0, 176.0],
167
+ "2.09": [368.0, 176.0],
168
+ "2.4": [384.0, 160.0],
169
+ "2.5": [400.0, 160.0],
170
+ "3.0": [432.0, 144.0],
171
+ "4.0": [512.0, 128.0],
172
+ }
173
+
174
+
175
+ def get_closest_hw(width, height, image_size):
176
+ if image_size == 1024:
177
+ aspect_ratio_bin = ASPECT_RATIO_1024_BIN
178
+ elif image_size == 512:
179
+ aspect_ratio_bin = ASPECT_RATIO_512_BIN
180
+ else:
181
+ raise ValueError("Invalid image size")
182
+
183
+ height, width = PixArtImageProcessor.classify_height_width_bin(height, width, ratios=aspect_ratio_bin)
184
+
185
+ return width, height
186
+
187
+
188
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
189
+ def retrieve_timesteps(
190
+ scheduler,
191
+ num_inference_steps: Optional[int] = None,
192
+ device: Optional[Union[str, torch.device]] = None,
193
+ timesteps: Optional[List[int]] = None,
194
+ sigmas: Optional[List[float]] = None,
195
+ **kwargs,
196
+ ):
197
+ """
198
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
199
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
200
+
201
+ Args:
202
+ scheduler (`SchedulerMixin`):
203
+ The scheduler to get timesteps from.
204
+ num_inference_steps (`int`):
205
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
206
+ must be `None`.
207
+ device (`str` or `torch.device`, *optional*):
208
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
209
+ timesteps (`List[int]`, *optional*):
210
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
211
+ `num_inference_steps` and `sigmas` must be `None`.
212
+ sigmas (`List[float]`, *optional*):
213
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
214
+ `num_inference_steps` and `timesteps` must be `None`.
215
+
216
+ Returns:
217
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
218
+ second element is the number of inference steps.
219
+ """
220
+ if timesteps is not None and sigmas is not None:
221
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
222
+ if timesteps is not None:
223
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
224
+ if not accepts_timesteps:
225
+ raise ValueError(
226
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
227
+ f" timestep schedules. Please check whether you are using the correct scheduler."
228
+ )
229
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
230
+ timesteps = scheduler.timesteps
231
+ num_inference_steps = len(timesteps)
232
+ elif sigmas is not None:
233
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
234
+ if not accept_sigmas:
235
+ raise ValueError(
236
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
237
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
238
+ )
239
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
240
+ timesteps = scheduler.timesteps
241
+ num_inference_steps = len(timesteps)
242
+ else:
243
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
244
+ timesteps = scheduler.timesteps
245
+ return timesteps, num_inference_steps
246
+
247
+
248
+ class PixArtAlphaControlnetPipeline(DiffusionPipeline):
249
+ r"""
250
+ Pipeline for text-to-image generation using PixArt-Alpha.
251
+
252
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
253
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
254
+
255
+ Args:
256
+ vae ([`AutoencoderKL`]):
257
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
258
+ text_encoder ([`T5EncoderModel`]):
259
+ Frozen text-encoder. PixArt-Alpha uses
260
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
261
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
262
+ tokenizer (`T5Tokenizer`):
263
+ Tokenizer of class
264
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
265
+ transformer ([`PixArtTransformer2DModel`]):
266
+ A text conditioned `PixArtTransformer2DModel` to denoise the encoded image latents.
267
+ scheduler ([`SchedulerMixin`]):
268
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
269
+ """
270
+
271
+ bad_punct_regex = re.compile(
272
+ r"["
273
+ + "#®•©™&@·º½¾¿¡§~"
274
+ + r"\)"
275
+ + r"\("
276
+ + r"\]"
277
+ + r"\["
278
+ + r"\}"
279
+ + r"\{"
280
+ + r"\|"
281
+ + "\\"
282
+ + r"\/"
283
+ + r"\*"
284
+ + r"]{1,}"
285
+ ) # noqa
286
+
287
+ _optional_components = ["tokenizer", "text_encoder"]
288
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
289
+
290
+ def __init__(
291
+ self,
292
+ tokenizer: T5Tokenizer,
293
+ text_encoder: T5EncoderModel,
294
+ vae: AutoencoderKL,
295
+ transformer: PixArtTransformer2DModel,
296
+ controlnet: PixArtControlNetAdapterModel,
297
+ scheduler: DPMSolverMultistepScheduler,
298
+ ):
299
+ super().__init__()
300
+
301
+ # change to the controlnet transformer model
302
+ transformer = PixArtControlNetTransformerModel(transformer=transformer, controlnet=controlnet)
303
+
304
+ self.register_modules(
305
+ tokenizer=tokenizer,
306
+ text_encoder=text_encoder,
307
+ vae=vae,
308
+ transformer=transformer,
309
+ scheduler=scheduler,
310
+ controlnet=controlnet,
311
+ )
312
+
313
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
314
+ self.image_processor = PixArtImageProcessor(vae_scale_factor=self.vae_scale_factor)
315
+ self.control_image_processor = PixArtImageProcessor(vae_scale_factor=self.vae_scale_factor)
316
+
317
+ # Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
318
+ def encode_prompt(
319
+ self,
320
+ prompt: Union[str, List[str]],
321
+ do_classifier_free_guidance: bool = True,
322
+ negative_prompt: str = "",
323
+ num_images_per_prompt: int = 1,
324
+ device: Optional[torch.device] = None,
325
+ prompt_embeds: Optional[torch.Tensor] = None,
326
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
327
+ prompt_attention_mask: Optional[torch.Tensor] = None,
328
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
329
+ clean_caption: bool = False,
330
+ max_sequence_length: int = 120,
331
+ **kwargs,
332
+ ):
333
+ r"""
334
+ Encodes the prompt into text encoder hidden states.
335
+
336
+ Args:
337
+ prompt (`str` or `List[str]`, *optional*):
338
+ prompt to be encoded
339
+ negative_prompt (`str` or `List[str]`, *optional*):
340
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
341
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
342
+ PixArt-Alpha, this should be "".
343
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
344
+ whether to use classifier free guidance or not
345
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
346
+ number of images that should be generated per prompt
347
+ device: (`torch.device`, *optional*):
348
+ torch device to place the resulting embeddings on
349
+ prompt_embeds (`torch.Tensor`, *optional*):
350
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
351
+ provided, text embeddings will be generated from `prompt` input argument.
352
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
353
+ Pre-generated negative text embeddings. For PixArt-Alpha, it's should be the embeddings of the ""
354
+ string.
355
+ clean_caption (`bool`, defaults to `False`):
356
+ If `True`, the function will preprocess and clean the provided caption before encoding.
357
+ max_sequence_length (`int`, defaults to 120): Maximum sequence length to use for the prompt.
358
+ """
359
+
360
+ if "mask_feature" in kwargs:
361
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
362
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
363
+
364
+ if device is None:
365
+ device = self._execution_device
366
+
367
+ if prompt is not None and isinstance(prompt, str):
368
+ batch_size = 1
369
+ elif prompt is not None and isinstance(prompt, list):
370
+ batch_size = len(prompt)
371
+ else:
372
+ batch_size = prompt_embeds.shape[0]
373
+
374
+ # See Section 3.1. of the paper.
375
+ max_length = max_sequence_length
376
+
377
+ if prompt_embeds is None:
378
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
379
+ text_inputs = self.tokenizer(
380
+ prompt,
381
+ padding="max_length",
382
+ max_length=max_length,
383
+ truncation=True,
384
+ add_special_tokens=True,
385
+ return_tensors="pt",
386
+ )
387
+ text_input_ids = text_inputs.input_ids
388
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
389
+
390
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
391
+ text_input_ids, untruncated_ids
392
+ ):
393
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_length - 1 : -1])
394
+ logger.warning(
395
+ "The following part of your input was truncated because T5 can only handle sequences up to"
396
+ f" {max_length} tokens: {removed_text}"
397
+ )
398
+
399
+ prompt_attention_mask = text_inputs.attention_mask
400
+ prompt_attention_mask = prompt_attention_mask.to(device)
401
+
402
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)
403
+ prompt_embeds = prompt_embeds[0]
404
+
405
+ if self.text_encoder is not None:
406
+ dtype = self.text_encoder.dtype
407
+ elif self.transformer is not None:
408
+ dtype = self.transformer.controlnet.dtype
409
+ else:
410
+ dtype = None
411
+
412
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
413
+
414
+ bs_embed, seq_len, _ = prompt_embeds.shape
415
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
416
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
417
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
418
+ prompt_attention_mask = prompt_attention_mask.view(bs_embed, -1)
419
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
420
+
421
+ # get unconditional embeddings for classifier free guidance
422
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
423
+ uncond_tokens = [negative_prompt] * batch_size
424
+ uncond_tokens = self._text_preprocessing(uncond_tokens, clean_caption=clean_caption)
425
+ max_length = prompt_embeds.shape[1]
426
+ uncond_input = self.tokenizer(
427
+ uncond_tokens,
428
+ padding="max_length",
429
+ max_length=max_length,
430
+ truncation=True,
431
+ return_attention_mask=True,
432
+ add_special_tokens=True,
433
+ return_tensors="pt",
434
+ )
435
+ negative_prompt_attention_mask = uncond_input.attention_mask
436
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(device)
437
+
438
+ negative_prompt_embeds = self.text_encoder(
439
+ uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask
440
+ )
441
+ negative_prompt_embeds = negative_prompt_embeds[0]
442
+
443
+ if do_classifier_free_guidance:
444
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
445
+ seq_len = negative_prompt_embeds.shape[1]
446
+
447
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
448
+
449
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
450
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
451
+
452
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed, -1)
453
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
454
+ else:
455
+ negative_prompt_embeds = None
456
+ negative_prompt_attention_mask = None
457
+
458
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
459
+
460
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
461
+ def prepare_extra_step_kwargs(self, generator, eta):
462
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
463
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
464
+ # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
465
+ # and should be between [0, 1]
466
+
467
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
468
+ extra_step_kwargs = {}
469
+ if accepts_eta:
470
+ extra_step_kwargs["eta"] = eta
471
+
472
+ # check if the scheduler accepts generator
473
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
474
+ if accepts_generator:
475
+ extra_step_kwargs["generator"] = generator
476
+ return extra_step_kwargs
477
+
478
+ def check_inputs(
479
+ self,
480
+ prompt,
481
+ height,
482
+ width,
483
+ negative_prompt,
484
+ callback_steps,
485
+ image=None,
486
+ prompt_embeds=None,
487
+ negative_prompt_embeds=None,
488
+ prompt_attention_mask=None,
489
+ negative_prompt_attention_mask=None,
490
+ ):
491
+ if height % 8 != 0 or width % 8 != 0:
492
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
493
+
494
+ if (callback_steps is None) or (
495
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
496
+ ):
497
+ raise ValueError(
498
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
499
+ f" {type(callback_steps)}."
500
+ )
501
+
502
+ if prompt is not None and prompt_embeds is not None:
503
+ raise ValueError(
504
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
505
+ " only forward one of the two."
506
+ )
507
+ elif prompt is None and prompt_embeds is None:
508
+ raise ValueError(
509
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
510
+ )
511
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
512
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
513
+
514
+ if prompt is not None and negative_prompt_embeds is not None:
515
+ raise ValueError(
516
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
517
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
518
+ )
519
+
520
+ if negative_prompt is not None and negative_prompt_embeds is not None:
521
+ raise ValueError(
522
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
523
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
524
+ )
525
+
526
+ if prompt_embeds is not None and prompt_attention_mask is None:
527
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
528
+
529
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
530
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
531
+
532
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
533
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
534
+ raise ValueError(
535
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
536
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
537
+ f" {negative_prompt_embeds.shape}."
538
+ )
539
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
540
+ raise ValueError(
541
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
542
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
543
+ f" {negative_prompt_attention_mask.shape}."
544
+ )
545
+
546
+ if image is not None:
547
+ self.check_image(image, prompt, prompt_embeds)
548
+
549
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
550
+ def check_image(self, image, prompt, prompt_embeds):
551
+ image_is_pil = isinstance(image, PIL.Image.Image)
552
+ image_is_tensor = isinstance(image, torch.Tensor)
553
+ image_is_np = isinstance(image, np.ndarray)
554
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
555
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
556
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
557
+
558
+ if (
559
+ not image_is_pil
560
+ and not image_is_tensor
561
+ and not image_is_np
562
+ and not image_is_pil_list
563
+ and not image_is_tensor_list
564
+ and not image_is_np_list
565
+ ):
566
+ raise TypeError(
567
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
568
+ )
569
+
570
+ if image_is_pil:
571
+ image_batch_size = 1
572
+ else:
573
+ image_batch_size = len(image)
574
+
575
+ if prompt is not None and isinstance(prompt, str):
576
+ prompt_batch_size = 1
577
+ elif prompt is not None and isinstance(prompt, list):
578
+ prompt_batch_size = len(prompt)
579
+ elif prompt_embeds is not None:
580
+ prompt_batch_size = prompt_embeds.shape[0]
581
+
582
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
583
+ raise ValueError(
584
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
585
+ )
586
+
587
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
588
+ def _text_preprocessing(self, text, clean_caption=False):
589
+ if clean_caption and not is_bs4_available():
590
+ logger.warning(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
591
+ logger.warning("Setting `clean_caption` to False...")
592
+ clean_caption = False
593
+
594
+ if clean_caption and not is_ftfy_available():
595
+ logger.warning(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))
596
+ logger.warning("Setting `clean_caption` to False...")
597
+ clean_caption = False
598
+
599
+ if not isinstance(text, (tuple, list)):
600
+ text = [text]
601
+
602
+ def process(text: str):
603
+ if clean_caption:
604
+ text = self._clean_caption(text)
605
+ text = self._clean_caption(text)
606
+ else:
607
+ text = text.lower().strip()
608
+ return text
609
+
610
+ return [process(t) for t in text]
611
+
612
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
613
+ def _clean_caption(self, caption):
614
+ caption = str(caption)
615
+ caption = ul.unquote_plus(caption)
616
+ caption = caption.strip().lower()
617
+ caption = re.sub("<person>", "person", caption)
618
+ # urls:
619
+ caption = re.sub(
620
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
621
+ "",
622
+ caption,
623
+ ) # regex for urls
624
+ caption = re.sub(
625
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
626
+ "",
627
+ caption,
628
+ ) # regex for urls
629
+ # html:
630
+ caption = BeautifulSoup(caption, features="html.parser").text
631
+
632
+ # @<nickname>
633
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
634
+
635
+ # 31C0—31EF CJK Strokes
636
+ # 31F0—31FF Katakana Phonetic Extensions
637
+ # 3200—32FF Enclosed CJK Letters and Months
638
+ # 3300—33FF CJK Compatibility
639
+ # 3400—4DBF CJK Unified Ideographs Extension A
640
+ # 4DC0—4DFF Yijing Hexagram Symbols
641
+ # 4E00—9FFF CJK Unified Ideographs
642
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
643
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
644
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
645
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
646
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
647
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
648
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
649
+ #######################################################
650
+
651
+ # все виды тире / all types of dash --> "-"
652
+ caption = re.sub(
653
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
654
+ "-",
655
+ caption,
656
+ )
657
+
658
+ # кавычки к одному стандарту
659
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
660
+ caption = re.sub(r"[‘’]", "'", caption)
661
+
662
+ # &quot;
663
+ caption = re.sub(r"&quot;?", "", caption)
664
+ # &amp
665
+ caption = re.sub(r"&amp", "", caption)
666
+
667
+ # ip addresses:
668
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
669
+
670
+ # article ids:
671
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
672
+
673
+ # \n
674
+ caption = re.sub(r"\\n", " ", caption)
675
+
676
+ # "#123"
677
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
678
+ # "#12345.."
679
+ caption = re.sub(r"#\d{5,}\b", "", caption)
680
+ # "123456.."
681
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
682
+ # filenames:
683
+ caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)
684
+
685
+ #
686
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
687
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
688
+
689
+ caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
690
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
691
+
692
+ # this-is-my-cute-cat / this_is_my_cute_cat
693
+ regex2 = re.compile(r"(?:\-|\_)")
694
+ if len(re.findall(regex2, caption)) > 3:
695
+ caption = re.sub(regex2, " ", caption)
696
+
697
+ caption = ftfy.fix_text(caption)
698
+ caption = html.unescape(html.unescape(caption))
699
+
700
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
701
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
702
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
703
+
704
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
705
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
706
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
707
+ caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)
708
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
709
+
710
+ caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...
711
+
712
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
713
+
714
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
715
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
716
+ caption = re.sub(r"\s+", " ", caption)
717
+
718
+ caption.strip()
719
+
720
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
721
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
722
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
723
+ caption = re.sub(r"^\.\S+$", "", caption)
724
+
725
+ return caption.strip()
726
+
727
+ def prepare_image(
728
+ self,
729
+ image,
730
+ width,
731
+ height,
732
+ batch_size,
733
+ num_images_per_prompt,
734
+ device,
735
+ dtype,
736
+ do_classifier_free_guidance=False,
737
+ ):
738
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
739
+ image_batch_size = image.shape[0]
740
+
741
+ if image_batch_size == 1:
742
+ repeat_by = batch_size
743
+ else:
744
+ # image batch size is the same as prompt batch size
745
+ repeat_by = num_images_per_prompt
746
+
747
+ image = image.repeat_interleave(repeat_by, dim=0)
748
+
749
+ image = image.to(device=device, dtype=dtype)
750
+
751
+ if do_classifier_free_guidance:
752
+ image = torch.cat([image] * 2)
753
+
754
+ return image
755
+
756
+ # based on pipeline_pixart_inpaiting.py
757
+ def prepare_image_latents(self, image, device, dtype):
758
+ image = image.to(device=device, dtype=dtype)
759
+
760
+ image_latents = self.vae.encode(image).latent_dist.sample()
761
+ image_latents = image_latents * self.vae.config.scaling_factor
762
+ return image_latents
763
+
764
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
765
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
766
+ shape = (
767
+ batch_size,
768
+ num_channels_latents,
769
+ int(height) // self.vae_scale_factor,
770
+ int(width) // self.vae_scale_factor,
771
+ )
772
+ if isinstance(generator, list) and len(generator) != batch_size:
773
+ raise ValueError(
774
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
775
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
776
+ )
777
+
778
+ if latents is None:
779
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
780
+ else:
781
+ latents = latents.to(device)
782
+
783
+ # scale the initial noise by the standard deviation required by the scheduler
784
+ latents = latents * self.scheduler.init_noise_sigma
785
+ return latents
786
+
787
+ @torch.no_grad()
788
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
789
+ def __call__(
790
+ self,
791
+ prompt: Union[str, List[str]] = None,
792
+ image: PipelineImageInput = None,
793
+ negative_prompt: str = "",
794
+ num_inference_steps: int = 20,
795
+ timesteps: List[int] = None,
796
+ sigmas: List[float] = None,
797
+ guidance_scale: float = 4.5,
798
+ num_images_per_prompt: Optional[int] = 1,
799
+ height: Optional[int] = None,
800
+ width: Optional[int] = None,
801
+ eta: float = 0.0,
802
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
803
+ latents: Optional[torch.Tensor] = None,
804
+ prompt_embeds: Optional[torch.Tensor] = None,
805
+ prompt_attention_mask: Optional[torch.Tensor] = None,
806
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
807
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
808
+ # rc todo: controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
809
+ # rc todo: control_guidance_start = 0.0,
810
+ # rc todo: control_guidance_end = 1.0,
811
+ output_type: Optional[str] = "pil",
812
+ return_dict: bool = True,
813
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
814
+ callback_steps: int = 1,
815
+ clean_caption: bool = True,
816
+ use_resolution_binning: bool = True,
817
+ max_sequence_length: int = 120,
818
+ **kwargs,
819
+ ) -> Union[ImagePipelineOutput, Tuple]:
820
+ """
821
+ Function invoked when calling the pipeline for generation.
822
+
823
+ Args:
824
+ prompt (`str` or `List[str]`, *optional*):
825
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
826
+ instead.
827
+ negative_prompt (`str` or `List[str]`, *optional*):
828
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
829
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
830
+ less than `1`).
831
+ num_inference_steps (`int`, *optional*, defaults to 100):
832
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
833
+ expense of slower inference.
834
+ timesteps (`List[int]`, *optional*):
835
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
836
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
837
+ passed will be used. Must be in descending order.
838
+ sigmas (`List[float]`, *optional*):
839
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
840
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
841
+ will be used.
842
+ guidance_scale (`float`, *optional*, defaults to 4.5):
843
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598).
844
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
845
+ Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting `guidance_scale >
846
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
847
+ usually at the expense of lower image quality.
848
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
849
+ The number of images to generate per prompt.
850
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
851
+ The height in pixels of the generated image.
852
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
853
+ The width in pixels of the generated image.
854
+ eta (`float`, *optional*, defaults to 0.0):
855
+ Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only applies to
856
+ [`schedulers.DDIMScheduler`], will be ignored for others.
857
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
858
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
859
+ to make generation deterministic.
860
+ latents (`torch.Tensor`, *optional*):
861
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
862
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
863
+ tensor will be generated by sampling using the supplied random `generator`.
864
+ prompt_embeds (`torch.Tensor`, *optional*):
865
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
866
+ provided, text embeddings will be generated from `prompt` input argument.
867
+ prompt_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
868
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
869
+ Pre-generated negative text embeddings. For PixArt-Alpha this negative prompt should be "". If not
870
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
871
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
872
+ Pre-generated attention mask for negative text embeddings.
873
+ output_type (`str`, *optional*, defaults to `"pil"`):
874
+ The output format of the generate image. Choose between
875
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
876
+ return_dict (`bool`, *optional*, defaults to `True`):
877
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
878
+ callback (`Callable`, *optional*):
879
+ A function that will be called every `callback_steps` steps during inference. The function will be
880
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
881
+ callback_steps (`int`, *optional*, defaults to 1):
882
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
883
+ called at every step.
884
+ clean_caption (`bool`, *optional*, defaults to `True`):
885
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
886
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
887
+ prompt.
888
+ use_resolution_binning (`bool` defaults to `True`):
889
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
890
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
891
+ the requested resolution. Useful for generating non-square images.
892
+ max_sequence_length (`int` defaults to 120): Maximum sequence length to use with the `prompt`.
893
+
894
+ Examples:
895
+
896
+ Returns:
897
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
898
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
899
+ returned where the first element is a list with the generated images
900
+ """
901
+ if "mask_feature" in kwargs:
902
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
903
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
904
+ # 1. Check inputs. Raise error if not correct
905
+ height = height or self.transformer.config.sample_size * self.vae_scale_factor
906
+ width = width or self.transformer.config.sample_size * self.vae_scale_factor
907
+ if use_resolution_binning:
908
+ if self.transformer.config.sample_size == 128:
909
+ aspect_ratio_bin = ASPECT_RATIO_1024_BIN
910
+ elif self.transformer.config.sample_size == 64:
911
+ aspect_ratio_bin = ASPECT_RATIO_512_BIN
912
+ elif self.transformer.config.sample_size == 32:
913
+ aspect_ratio_bin = ASPECT_RATIO_256_BIN
914
+ else:
915
+ raise ValueError("Invalid sample size")
916
+ orig_height, orig_width = height, width
917
+ height, width = self.image_processor.classify_height_width_bin(height, width, ratios=aspect_ratio_bin)
918
+
919
+ self.check_inputs(
920
+ prompt,
921
+ height,
922
+ width,
923
+ negative_prompt,
924
+ callback_steps,
925
+ image,
926
+ prompt_embeds,
927
+ negative_prompt_embeds,
928
+ prompt_attention_mask,
929
+ negative_prompt_attention_mask,
930
+ )
931
+
932
+ # 2. Default height and width to transformer
933
+ if prompt is not None and isinstance(prompt, str):
934
+ batch_size = 1
935
+ elif prompt is not None and isinstance(prompt, list):
936
+ batch_size = len(prompt)
937
+ else:
938
+ batch_size = prompt_embeds.shape[0]
939
+
940
+ device = self._execution_device
941
+
942
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
943
+ # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
944
+ # corresponds to doing no classifier free guidance.
945
+ do_classifier_free_guidance = guidance_scale > 1.0
946
+
947
+ # 3. Encode input prompt
948
+ (
949
+ prompt_embeds,
950
+ prompt_attention_mask,
951
+ negative_prompt_embeds,
952
+ negative_prompt_attention_mask,
953
+ ) = self.encode_prompt(
954
+ prompt,
955
+ do_classifier_free_guidance,
956
+ negative_prompt=negative_prompt,
957
+ num_images_per_prompt=num_images_per_prompt,
958
+ device=device,
959
+ prompt_embeds=prompt_embeds,
960
+ negative_prompt_embeds=negative_prompt_embeds,
961
+ prompt_attention_mask=prompt_attention_mask,
962
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
963
+ clean_caption=clean_caption,
964
+ max_sequence_length=max_sequence_length,
965
+ )
966
+ if do_classifier_free_guidance:
967
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
968
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
969
+
970
+ # 4. Prepare timesteps
971
+ timesteps, num_inference_steps = retrieve_timesteps(
972
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
973
+ )
974
+
975
+ # 4.1 Prepare image
976
+ image_latents = None
977
+ if image is not None:
978
+ image = self.prepare_image(
979
+ image=image,
980
+ width=width,
981
+ height=height,
982
+ batch_size=batch_size * num_images_per_prompt,
983
+ num_images_per_prompt=num_images_per_prompt,
984
+ device=device,
985
+ dtype=self.transformer.controlnet.dtype,
986
+ do_classifier_free_guidance=do_classifier_free_guidance,
987
+ )
988
+
989
+ image_latents = self.prepare_image_latents(image, device, self.transformer.controlnet.dtype)
990
+
991
+ # 5. Prepare latents.
992
+ latent_channels = self.transformer.config.in_channels
993
+ latents = self.prepare_latents(
994
+ batch_size * num_images_per_prompt,
995
+ latent_channels,
996
+ height,
997
+ width,
998
+ prompt_embeds.dtype,
999
+ device,
1000
+ generator,
1001
+ latents,
1002
+ )
1003
+
1004
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1005
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1006
+
1007
+ # 6.1 Prepare micro-conditions.
1008
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
1009
+ if self.transformer.config.sample_size == 128:
1010
+ resolution = torch.tensor([height, width]).repeat(batch_size * num_images_per_prompt, 1)
1011
+ aspect_ratio = torch.tensor([float(height / width)]).repeat(batch_size * num_images_per_prompt, 1)
1012
+ resolution = resolution.to(dtype=prompt_embeds.dtype, device=device)
1013
+ aspect_ratio = aspect_ratio.to(dtype=prompt_embeds.dtype, device=device)
1014
+
1015
+ if do_classifier_free_guidance:
1016
+ resolution = torch.cat([resolution, resolution], dim=0)
1017
+ aspect_ratio = torch.cat([aspect_ratio, aspect_ratio], dim=0)
1018
+
1019
+ added_cond_kwargs = {"resolution": resolution, "aspect_ratio": aspect_ratio}
1020
+
1021
+ # 7. Denoising loop
1022
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1023
+
1024
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1025
+ for i, t in enumerate(timesteps):
1026
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1027
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1028
+
1029
+ current_timestep = t
1030
+ if not torch.is_tensor(current_timestep):
1031
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1032
+ # This would be a good case for the `match` statement (Python 3.10+)
1033
+ is_mps = latent_model_input.device.type == "mps"
1034
+ is_npu = latent_model_input.device.type == "npu"
1035
+ if isinstance(current_timestep, float):
1036
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
1037
+ else:
1038
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
1039
+ current_timestep = torch.tensor([current_timestep], dtype=dtype, device=latent_model_input.device)
1040
+ elif len(current_timestep.shape) == 0:
1041
+ current_timestep = current_timestep[None].to(latent_model_input.device)
1042
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1043
+ current_timestep = current_timestep.expand(latent_model_input.shape[0])
1044
+
1045
+ # predict noise model_output
1046
+ noise_pred = self.transformer(
1047
+ latent_model_input,
1048
+ encoder_hidden_states=prompt_embeds,
1049
+ encoder_attention_mask=prompt_attention_mask,
1050
+ timestep=current_timestep,
1051
+ controlnet_cond=image_latents,
1052
+ # rc todo: controlnet_conditioning_scale=1.0,
1053
+ added_cond_kwargs=added_cond_kwargs,
1054
+ return_dict=False,
1055
+ )[0]
1056
+
1057
+ # perform guidance
1058
+ if do_classifier_free_guidance:
1059
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1060
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1061
+
1062
+ # learned sigma
1063
+ if self.transformer.config.out_channels // 2 == latent_channels:
1064
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1065
+ else:
1066
+ noise_pred = noise_pred
1067
+
1068
+ # compute previous image: x_t -> x_t-1
1069
+ if num_inference_steps == 1:
1070
+ # For DMD one step sampling: https://huggingface.co/papers/2311.18828
1071
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).pred_original_sample
1072
+ else:
1073
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1074
+
1075
+ # call the callback, if provided
1076
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1077
+ progress_bar.update()
1078
+ if callback is not None and i % callback_steps == 0:
1079
+ step_idx = i // getattr(self.scheduler, "order", 1)
1080
+ callback(step_idx, t, latents)
1081
+
1082
+ if not output_type == "latent":
1083
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1084
+ if use_resolution_binning:
1085
+ image = self.image_processor.resize_and_crop_tensor(image, orig_width, orig_height)
1086
+ else:
1087
+ image = latents
1088
+
1089
+ if not output_type == "latent":
1090
+ image = self.image_processor.postprocess(image, output_type=output_type)
1091
+
1092
+ # Offload all models
1093
+ self.maybe_free_model_hooks()
1094
+
1095
+ if not return_dict:
1096
+ return (image,)
1097
+
1098
+ return ImagePipelineOutput(images=image)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers
2
+ SentencePiece
3
+ torchvision
4
+ controlnet-aux
5
+ datasets
6
+ # wandb
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/run_pixart_alpha_controlnet_pipeline.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms as T
3
+ from controlnet_aux import HEDdetector
4
+
5
+ from diffusers.utils import load_image
6
+ from examples.research_projects.pixart.controlnet_pixart_alpha import PixArtControlNetAdapterModel
7
+ from examples.research_projects.pixart.pipeline_pixart_alpha_controlnet import PixArtAlphaControlnetPipeline
8
+
9
+
10
+ controlnet_repo_id = "raulc0399/pixart-alpha-hed-controlnet"
11
+
12
+ weight_dtype = torch.float16
13
+ image_size = 1024
14
+
15
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
+
17
+ torch.manual_seed(0)
18
+
19
+ # load controlnet
20
+ controlnet = PixArtControlNetAdapterModel.from_pretrained(
21
+ controlnet_repo_id,
22
+ torch_dtype=weight_dtype,
23
+ use_safetensors=True,
24
+ ).to(device)
25
+
26
+ pipe = PixArtAlphaControlnetPipeline.from_pretrained(
27
+ "PixArt-alpha/PixArt-XL-2-1024-MS",
28
+ controlnet=controlnet,
29
+ torch_dtype=weight_dtype,
30
+ use_safetensors=True,
31
+ ).to(device)
32
+
33
+ images_path = "images"
34
+ control_image_file = "0_7.jpg"
35
+
36
+ # prompt = "cinematic photo of superman in action . 35mm photograph, film, bokeh, professional, 4k, highly detailed"
37
+ # prompt = "yellow modern car, city in background, beautiful rainy day"
38
+ # prompt = "modern villa, clear sky, suny day . 35mm photograph, film, bokeh, professional, 4k, highly detailed"
39
+ # prompt = "robot dog toy in park . 35mm photograph, film, bokeh, professional, 4k, highly detailed"
40
+ # prompt = "purple car, on highway, beautiful sunny day"
41
+ # prompt = "realistical photo of a loving couple standing in the open kitchen of the living room, cooking ."
42
+ prompt = "battleship in space, galaxy in background"
43
+
44
+ control_image_name = control_image_file.split(".")[0]
45
+
46
+ control_image = load_image(f"{images_path}/{control_image_file}")
47
+ print(control_image.size)
48
+ height, width = control_image.size
49
+
50
+ hed = HEDdetector.from_pretrained("lllyasviel/Annotators")
51
+
52
+ condition_transform = T.Compose(
53
+ [
54
+ T.Lambda(lambda img: img.convert("RGB")),
55
+ T.CenterCrop([image_size, image_size]),
56
+ ]
57
+ )
58
+
59
+ control_image = condition_transform(control_image)
60
+ hed_edge = hed(control_image, detect_resolution=image_size, image_resolution=image_size)
61
+
62
+ hed_edge.save(f"{images_path}/{control_image_name}_hed.jpg")
63
+
64
+ # run pipeline
65
+ with torch.no_grad():
66
+ out = pipe(
67
+ prompt=prompt,
68
+ image=hed_edge,
69
+ num_inference_steps=14,
70
+ guidance_scale=4.5,
71
+ height=image_size,
72
+ width=image_size,
73
+ )
74
+
75
+ out.images[0].save(f"{images_path}//{control_image_name}_output.jpg")
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/train_controlnet_hf_diffusers.sh ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # run
4
+ # accelerate config
5
+
6
+ # check with
7
+ # accelerate env
8
+
9
+ export MODEL_DIR="PixArt-alpha/PixArt-XL-2-512x512"
10
+ export OUTPUT_DIR="output/pixart-controlnet-hf-diffusers-test"
11
+
12
+ accelerate launch ./train_pixart_controlnet_hf.py --mixed_precision="fp16" \
13
+ --pretrained_model_name_or_path=$MODEL_DIR \
14
+ --output_dir=$OUTPUT_DIR \
15
+ --dataset_name=fusing/fill50k \
16
+ --resolution=512 \
17
+ --learning_rate=1e-5 \
18
+ --train_batch_size=1 \
19
+ --gradient_accumulation_steps=4 \
20
+ --report_to="wandb" \
21
+ --seed=42 \
22
+ --dataloader_num_workers=8
23
+ # --lr_scheduler="cosine" --lr_warmup_steps=0 \
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pixart/train_pixart_controlnet_hf.py ADDED
@@ -0,0 +1,1174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
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
+ """Fine-tuning script for Stable Diffusion for text2image with HuggingFace diffusers."""
16
+
17
+ import argparse
18
+ import gc
19
+ import logging
20
+ import math
21
+ import os
22
+ import random
23
+ import shutil
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.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 PIL import Image
40
+ from pipeline_pixart_alpha_controlnet import PixArtAlphaControlnetPipeline
41
+ from torchvision import transforms
42
+ from tqdm.auto import tqdm
43
+ from transformers import T5EncoderModel, T5Tokenizer
44
+
45
+ import diffusers
46
+ from diffusers import AutoencoderKL, DDPMScheduler
47
+ from diffusers.models import PixArtTransformer2DModel
48
+ from diffusers.optimization import get_scheduler
49
+ from diffusers.training_utils import compute_snr
50
+ from diffusers.utils import check_min_version, is_wandb_available, make_image_grid
51
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
52
+ from diffusers.utils.import_utils import is_xformers_available
53
+ from diffusers.utils.torch_utils import is_compiled_module
54
+ from examples.research_projects.pixart.controlnet_pixart_alpha import (
55
+ PixArtControlNetAdapterModel,
56
+ PixArtControlNetTransformerModel,
57
+ )
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.29.2")
65
+
66
+ logger = get_logger(__name__, log_level="INFO")
67
+
68
+
69
+ def log_validation(
70
+ vae,
71
+ transformer,
72
+ controlnet,
73
+ tokenizer,
74
+ scheduler,
75
+ text_encoder,
76
+ args,
77
+ accelerator,
78
+ weight_dtype,
79
+ step,
80
+ is_final_validation=False,
81
+ ):
82
+ if weight_dtype == torch.float16 or weight_dtype == torch.bfloat16:
83
+ raise ValueError(
84
+ "Validation is not supported with mixed precision training, disable validation and use the validation script, that will generate images from the saved checkpoints."
85
+ )
86
+
87
+ if not is_final_validation:
88
+ logger.info(f"Running validation step {step} ... ")
89
+
90
+ controlnet = accelerator.unwrap_model(controlnet)
91
+ pipeline = PixArtAlphaControlnetPipeline.from_pretrained(
92
+ args.pretrained_model_name_or_path,
93
+ vae=vae,
94
+ transformer=transformer,
95
+ scheduler=scheduler,
96
+ text_encoder=text_encoder,
97
+ tokenizer=tokenizer,
98
+ controlnet=controlnet,
99
+ revision=args.revision,
100
+ variant=args.variant,
101
+ torch_dtype=weight_dtype,
102
+ )
103
+ else:
104
+ logger.info("Running validation - final ... ")
105
+
106
+ controlnet = PixArtControlNetAdapterModel.from_pretrained(args.output_dir, torch_dtype=weight_dtype)
107
+
108
+ pipeline = PixArtAlphaControlnetPipeline.from_pretrained(
109
+ args.pretrained_model_name_or_path,
110
+ controlnet=controlnet,
111
+ revision=args.revision,
112
+ variant=args.variant,
113
+ torch_dtype=weight_dtype,
114
+ )
115
+
116
+ pipeline = pipeline.to(accelerator.device)
117
+ pipeline.set_progress_bar_config(disable=True)
118
+
119
+ if args.enable_xformers_memory_efficient_attention:
120
+ pipeline.enable_xformers_memory_efficient_attention()
121
+
122
+ if args.seed is None:
123
+ generator = None
124
+ else:
125
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
126
+
127
+ if len(args.validation_image) == len(args.validation_prompt):
128
+ validation_images = args.validation_image
129
+ validation_prompts = args.validation_prompt
130
+ elif len(args.validation_image) == 1:
131
+ validation_images = args.validation_image * len(args.validation_prompt)
132
+ validation_prompts = args.validation_prompt
133
+ elif len(args.validation_prompt) == 1:
134
+ validation_images = args.validation_image
135
+ validation_prompts = args.validation_prompt * len(args.validation_image)
136
+ else:
137
+ raise ValueError(
138
+ "number of `args.validation_image` and `args.validation_prompt` should be checked in `parse_args`"
139
+ )
140
+
141
+ image_logs = []
142
+
143
+ for validation_prompt, validation_image in zip(validation_prompts, validation_images):
144
+ validation_image = Image.open(validation_image).convert("RGB")
145
+ validation_image = validation_image.resize((args.resolution, args.resolution))
146
+
147
+ images = []
148
+
149
+ for _ in range(args.num_validation_images):
150
+ image = pipeline(
151
+ prompt=validation_prompt, image=validation_image, num_inference_steps=20, generator=generator
152
+ ).images[0]
153
+ images.append(image)
154
+
155
+ image_logs.append(
156
+ {"validation_image": validation_image, "images": images, "validation_prompt": validation_prompt}
157
+ )
158
+
159
+ tracker_key = "test" if is_final_validation else "validation"
160
+ for tracker in accelerator.trackers:
161
+ if tracker.name == "tensorboard":
162
+ for log in image_logs:
163
+ images = log["images"]
164
+ validation_prompt = log["validation_prompt"]
165
+ validation_image = log["validation_image"]
166
+
167
+ formatted_images = [np.asarray(validation_image)]
168
+
169
+ for image in images:
170
+ formatted_images.append(np.asarray(image))
171
+
172
+ formatted_images = np.stack(formatted_images)
173
+
174
+ tracker.writer.add_images(validation_prompt, formatted_images, step, dataformats="NHWC")
175
+ elif tracker.name == "wandb":
176
+ formatted_images = []
177
+
178
+ for log in image_logs:
179
+ images = log["images"]
180
+ validation_prompt = log["validation_prompt"]
181
+ validation_image = log["validation_image"]
182
+
183
+ formatted_images.append(wandb.Image(validation_image, caption="Controlnet conditioning"))
184
+
185
+ for image in images:
186
+ image = wandb.Image(image, caption=validation_prompt)
187
+ formatted_images.append(image)
188
+
189
+ tracker.log({tracker_key: formatted_images})
190
+ else:
191
+ logger.warning(f"image logging not implemented for {tracker.name}")
192
+
193
+ del pipeline
194
+ gc.collect()
195
+ torch.cuda.empty_cache()
196
+
197
+ logger.info("Validation done!!")
198
+
199
+ return image_logs
200
+
201
+
202
+ def save_model_card(repo_id: str, image_logs=None, base_model=str, dataset_name=str, repo_folder=None):
203
+ img_str = ""
204
+ if image_logs is not None:
205
+ img_str = "You can find some example images below.\n\n"
206
+ for i, log in enumerate(image_logs):
207
+ images = log["images"]
208
+ validation_prompt = log["validation_prompt"]
209
+ validation_image = log["validation_image"]
210
+ validation_image.save(os.path.join(repo_folder, "image_control.png"))
211
+ img_str += f"prompt: {validation_prompt}\n"
212
+ images = [validation_image] + images
213
+ make_image_grid(images, 1, len(images)).save(os.path.join(repo_folder, f"images_{i}.png"))
214
+ img_str += f"![images_{i})](./images_{i}.png)\n"
215
+
216
+ model_description = f"""
217
+ # controlnet-{repo_id}
218
+
219
+ These are controlnet weights trained on {base_model} with new type of conditioning.
220
+ {img_str}
221
+ """
222
+
223
+ model_card = load_or_create_model_card(
224
+ repo_id_or_path=repo_id,
225
+ from_training=True,
226
+ license="openrail++",
227
+ base_model=base_model,
228
+ model_description=model_description,
229
+ inference=True,
230
+ )
231
+
232
+ tags = [
233
+ "pixart-alpha",
234
+ "pixart-alpha-diffusers",
235
+ "text-to-image",
236
+ "diffusers",
237
+ "controlnet",
238
+ "diffusers-training",
239
+ ]
240
+ model_card = populate_model_card(model_card, tags=tags)
241
+
242
+ model_card.save(os.path.join(repo_folder, "README.md"))
243
+
244
+
245
+ def parse_args():
246
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
247
+ parser.add_argument(
248
+ "--pretrained_model_name_or_path",
249
+ type=str,
250
+ default=None,
251
+ required=True,
252
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
253
+ )
254
+ parser.add_argument(
255
+ "--revision",
256
+ type=str,
257
+ default=None,
258
+ required=False,
259
+ help="Revision of pretrained model identifier from huggingface.co/models.",
260
+ )
261
+ parser.add_argument(
262
+ "--variant",
263
+ type=str,
264
+ default=None,
265
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
266
+ )
267
+ parser.add_argument(
268
+ "--controlnet_model_name_or_path",
269
+ type=str,
270
+ default=None,
271
+ help="Path to pretrained controlnet model or model identifier from huggingface.co/models."
272
+ " If not specified controlnet weights are initialized from the transformer.",
273
+ )
274
+ parser.add_argument(
275
+ "--dataset_name",
276
+ type=str,
277
+ default=None,
278
+ help=(
279
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
280
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
281
+ " or to a folder containing files that 🤗 Datasets can understand."
282
+ ),
283
+ )
284
+ parser.add_argument(
285
+ "--dataset_config_name",
286
+ type=str,
287
+ default=None,
288
+ help="The config of the Dataset, leave as None if there's only one config.",
289
+ )
290
+ parser.add_argument(
291
+ "--train_data_dir",
292
+ type=str,
293
+ default=None,
294
+ help=(
295
+ "A folder containing the training data. Folder contents must follow the structure described in"
296
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
297
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
298
+ ),
299
+ )
300
+ parser.add_argument(
301
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
302
+ )
303
+ parser.add_argument(
304
+ "--conditioning_image_column",
305
+ type=str,
306
+ default="conditioning_image",
307
+ help="The column of the dataset containing the controlnet conditioning image.",
308
+ )
309
+ parser.add_argument(
310
+ "--caption_column",
311
+ type=str,
312
+ default="text",
313
+ help="The column of the dataset containing a caption or a list of captions.",
314
+ )
315
+ parser.add_argument(
316
+ "--validation_prompt",
317
+ type=str,
318
+ nargs="+",
319
+ default=None,
320
+ help="One or more prompts to be evaluated every `--validation_steps`."
321
+ " Provide either a matching number of `--validation_image`s, a single `--validation_image`"
322
+ " to be used with all prompts, or a single prompt that will be used with all `--validation_image`s.",
323
+ )
324
+ parser.add_argument(
325
+ "--validation_image",
326
+ type=str,
327
+ default=None,
328
+ nargs="+",
329
+ help=(
330
+ "A set of paths to the controlnet conditioning image be evaluated every `--validation_steps`"
331
+ " and logged to `--report_to`. Provide either a matching number of `--validation_prompt`s, a"
332
+ " a single `--validation_prompt` to be used with all `--validation_image`s, or a single"
333
+ " `--validation_image` that will be used with all `--validation_prompt`s."
334
+ ),
335
+ )
336
+ parser.add_argument(
337
+ "--num_validation_images",
338
+ type=int,
339
+ default=4,
340
+ help="Number of images that should be generated during validation with `validation_prompt`.",
341
+ )
342
+ parser.add_argument(
343
+ "--validation_steps",
344
+ type=int,
345
+ default=100,
346
+ help=(
347
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
348
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
349
+ ),
350
+ )
351
+ parser.add_argument(
352
+ "--max_train_samples",
353
+ type=int,
354
+ default=None,
355
+ help=(
356
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
357
+ "value if set."
358
+ ),
359
+ )
360
+ parser.add_argument(
361
+ "--output_dir",
362
+ type=str,
363
+ default="pixart-controlnet",
364
+ help="The output directory where the model predictions and checkpoints will be written.",
365
+ )
366
+ parser.add_argument(
367
+ "--cache_dir",
368
+ type=str,
369
+ default=None,
370
+ help="The directory where the downloaded models and datasets will be stored.",
371
+ )
372
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
373
+ parser.add_argument(
374
+ "--resolution",
375
+ type=int,
376
+ default=512,
377
+ help=(
378
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
379
+ " resolution"
380
+ ),
381
+ )
382
+ parser.add_argument(
383
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
384
+ )
385
+ parser.add_argument("--num_train_epochs", type=int, default=1)
386
+ parser.add_argument(
387
+ "--max_train_steps",
388
+ type=int,
389
+ default=None,
390
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
391
+ )
392
+ parser.add_argument(
393
+ "--gradient_accumulation_steps",
394
+ type=int,
395
+ default=1,
396
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
397
+ )
398
+ parser.add_argument(
399
+ "--gradient_checkpointing",
400
+ action="store_true",
401
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
402
+ )
403
+ parser.add_argument(
404
+ "--learning_rate",
405
+ type=float,
406
+ default=1e-6,
407
+ help="Initial learning rate (after the potential warmup period) to use.",
408
+ )
409
+ parser.add_argument(
410
+ "--scale_lr",
411
+ action="store_true",
412
+ default=False,
413
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
414
+ )
415
+ parser.add_argument(
416
+ "--lr_scheduler",
417
+ type=str,
418
+ default="constant",
419
+ help=(
420
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
421
+ ' "constant", "constant_with_warmup"]'
422
+ ),
423
+ )
424
+ parser.add_argument(
425
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
426
+ )
427
+ parser.add_argument(
428
+ "--snr_gamma",
429
+ type=float,
430
+ default=None,
431
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
432
+ "More details here: https://huggingface.co/papers/2303.09556.",
433
+ )
434
+ parser.add_argument(
435
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
436
+ )
437
+ parser.add_argument(
438
+ "--allow_tf32",
439
+ action="store_true",
440
+ help=(
441
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
442
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
443
+ ),
444
+ )
445
+ parser.add_argument(
446
+ "--dataloader_num_workers",
447
+ type=int,
448
+ default=0,
449
+ help=(
450
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
451
+ ),
452
+ )
453
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
454
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
455
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
456
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
457
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
458
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
459
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
460
+ # ----Diffusion Training Arguments----
461
+ parser.add_argument(
462
+ "--proportion_empty_prompts",
463
+ type=float,
464
+ default=0,
465
+ help="Proportion of image prompts to be replaced with empty strings. Defaults to 0 (no prompt replacement).",
466
+ )
467
+ parser.add_argument(
468
+ "--prediction_type",
469
+ type=str,
470
+ default=None,
471
+ 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.",
472
+ )
473
+ parser.add_argument(
474
+ "--hub_model_id",
475
+ type=str,
476
+ default=None,
477
+ help="The name of the repository to keep in sync with the local `output_dir`.",
478
+ )
479
+ parser.add_argument(
480
+ "--logging_dir",
481
+ type=str,
482
+ default="logs",
483
+ help=(
484
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
485
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
486
+ ),
487
+ )
488
+ parser.add_argument(
489
+ "--mixed_precision",
490
+ type=str,
491
+ default=None,
492
+ choices=["no", "fp16", "bf16"],
493
+ help=(
494
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
495
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
496
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
497
+ ),
498
+ )
499
+ parser.add_argument(
500
+ "--report_to",
501
+ type=str,
502
+ default="tensorboard",
503
+ help=(
504
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
505
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
506
+ ),
507
+ )
508
+ parser.add_argument(
509
+ "--checkpointing_steps",
510
+ type=int,
511
+ default=500,
512
+ help=(
513
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
514
+ " training using `--resume_from_checkpoint`."
515
+ ),
516
+ )
517
+ parser.add_argument(
518
+ "--checkpoints_total_limit",
519
+ type=int,
520
+ default=None,
521
+ help=("Max number of checkpoints to store."),
522
+ )
523
+ parser.add_argument(
524
+ "--resume_from_checkpoint",
525
+ type=str,
526
+ default=None,
527
+ help=(
528
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
529
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
530
+ ),
531
+ )
532
+ parser.add_argument(
533
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
534
+ )
535
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
536
+
537
+ parser.add_argument(
538
+ "--tracker_project_name",
539
+ type=str,
540
+ default="pixart_controlnet",
541
+ help=(
542
+ "The `project_name` argument passed to Accelerator.init_trackers for"
543
+ " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
544
+ ),
545
+ )
546
+
547
+ args = parser.parse_args()
548
+
549
+ # Sanity checks
550
+ if args.dataset_name is None and args.train_data_dir is None:
551
+ raise ValueError("Need either a dataset name or a training folder.")
552
+
553
+ if args.proportion_empty_prompts < 0 or args.proportion_empty_prompts > 1:
554
+ raise ValueError("`--proportion_empty_prompts` must be in the range [0, 1].")
555
+
556
+ return args
557
+
558
+
559
+ def main():
560
+ args = parse_args()
561
+
562
+ if args.report_to == "wandb" and args.hub_token is not None:
563
+ raise ValueError(
564
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
565
+ " Please use `hf auth login` to authenticate with the Hub."
566
+ )
567
+
568
+ logging_dir = Path(args.output_dir, args.logging_dir)
569
+
570
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
571
+
572
+ accelerator = Accelerator(
573
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
574
+ mixed_precision=args.mixed_precision,
575
+ log_with=args.report_to,
576
+ project_config=accelerator_project_config,
577
+ )
578
+ if args.report_to == "wandb":
579
+ if not is_wandb_available():
580
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
581
+
582
+ # Make one log on every process with the configuration for debugging.
583
+ logging.basicConfig(
584
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
585
+ datefmt="%m/%d/%Y %H:%M:%S",
586
+ level=logging.INFO,
587
+ )
588
+ logger.info(accelerator.state, main_process_only=False)
589
+ if accelerator.is_local_main_process:
590
+ datasets.utils.logging.set_verbosity_warning()
591
+ transformers.utils.logging.set_verbosity_warning()
592
+ diffusers.utils.logging.set_verbosity_info()
593
+ else:
594
+ datasets.utils.logging.set_verbosity_error()
595
+ transformers.utils.logging.set_verbosity_error()
596
+ diffusers.utils.logging.set_verbosity_error()
597
+
598
+ # If passed along, set the training seed now.
599
+ if args.seed is not None:
600
+ set_seed(args.seed)
601
+
602
+ # Handle the repository creation
603
+ if accelerator.is_main_process:
604
+ if args.output_dir is not None:
605
+ os.makedirs(args.output_dir, exist_ok=True)
606
+
607
+ if args.push_to_hub:
608
+ repo_id = create_repo(
609
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
610
+ ).repo_id
611
+
612
+ # See Section 3.1. of the paper.
613
+ max_length = 120
614
+
615
+ # For mixed precision training we cast all non-trainable weights (vae, text_encoder) to half-precision
616
+ # as these weights are only used for inference, keeping weights in full precision is not required.
617
+ weight_dtype = torch.float32
618
+ if accelerator.mixed_precision == "fp16":
619
+ weight_dtype = torch.float16
620
+ elif accelerator.mixed_precision == "bf16":
621
+ weight_dtype = torch.bfloat16
622
+
623
+ # Load scheduler, tokenizer and models.
624
+ noise_scheduler = DDPMScheduler.from_pretrained(
625
+ args.pretrained_model_name_or_path, subfolder="scheduler", torch_dtype=weight_dtype
626
+ )
627
+ tokenizer = T5Tokenizer.from_pretrained(
628
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, torch_dtype=weight_dtype
629
+ )
630
+
631
+ text_encoder = T5EncoderModel.from_pretrained(
632
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, torch_dtype=weight_dtype
633
+ )
634
+ text_encoder.requires_grad_(False)
635
+ text_encoder.to(accelerator.device)
636
+
637
+ vae = AutoencoderKL.from_pretrained(
638
+ args.pretrained_model_name_or_path,
639
+ subfolder="vae",
640
+ revision=args.revision,
641
+ variant=args.variant,
642
+ torch_dtype=weight_dtype,
643
+ )
644
+ vae.requires_grad_(False)
645
+ vae.to(accelerator.device)
646
+
647
+ transformer = PixArtTransformer2DModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="transformer")
648
+ transformer.to(accelerator.device)
649
+ transformer.requires_grad_(False)
650
+
651
+ if args.controlnet_model_name_or_path:
652
+ logger.info("Loading existing controlnet weights")
653
+ controlnet = PixArtControlNetAdapterModel.from_pretrained(args.controlnet_model_name_or_path)
654
+ else:
655
+ logger.info("Initializing controlnet weights from transformer.")
656
+ controlnet = PixArtControlNetAdapterModel.from_transformer(transformer)
657
+
658
+ transformer.to(dtype=weight_dtype)
659
+
660
+ controlnet.to(accelerator.device)
661
+ controlnet.train()
662
+
663
+ def unwrap_model(model, keep_fp32_wrapper=True):
664
+ model = accelerator.unwrap_model(model, keep_fp32_wrapper=keep_fp32_wrapper)
665
+ model = model._orig_mod if is_compiled_module(model) else model
666
+ return model
667
+
668
+ # 10. Handle saving and loading of checkpoints
669
+ # `accelerate` 0.16.0 will have better support for customized saving
670
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
671
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
672
+ def save_model_hook(models, weights, output_dir):
673
+ if accelerator.is_main_process:
674
+ for _, model in enumerate(models):
675
+ if isinstance(model, PixArtControlNetTransformerModel):
676
+ print(f"Saving model {model.__class__.__name__} to {output_dir}")
677
+ model.controlnet.save_pretrained(os.path.join(output_dir, "controlnet"))
678
+
679
+ # make sure to pop weight so that corresponding model is not saved again
680
+ weights.pop()
681
+
682
+ def load_model_hook(models, input_dir):
683
+ # rc todo: test and load the controlenet adapter and transformer
684
+ raise ValueError("load model hook not tested")
685
+
686
+ for i in range(len(models)):
687
+ # pop models so that they are not loaded again
688
+ model = models.pop()
689
+
690
+ if isinstance(model, PixArtControlNetTransformerModel):
691
+ load_model = PixArtControlNetAdapterModel.from_pretrained(input_dir, subfolder="controlnet")
692
+ model.register_to_config(**load_model.config)
693
+
694
+ model.load_state_dict(load_model.state_dict())
695
+ del load_model
696
+
697
+ accelerator.register_save_state_pre_hook(save_model_hook)
698
+ accelerator.register_load_state_pre_hook(load_model_hook)
699
+
700
+ if args.enable_xformers_memory_efficient_attention:
701
+ if is_xformers_available():
702
+ import xformers
703
+
704
+ xformers_version = version.parse(xformers.__version__)
705
+ if xformers_version == version.parse("0.0.16"):
706
+ logger.warn(
707
+ "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."
708
+ )
709
+ transformer.enable_xformers_memory_efficient_attention()
710
+ controlnet.enable_xformers_memory_efficient_attention()
711
+ else:
712
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
713
+
714
+ if unwrap_model(controlnet).dtype != torch.float32:
715
+ raise ValueError(
716
+ f"Transformer loaded as datatype {unwrap_model(controlnet).dtype}. The trainable parameters should be in torch.float32."
717
+ )
718
+
719
+ # Enable TF32 for faster training on Ampere GPUs,
720
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
721
+ if args.allow_tf32:
722
+ torch.backends.cuda.matmul.allow_tf32 = True
723
+
724
+ if args.gradient_checkpointing:
725
+ transformer.enable_gradient_checkpointing()
726
+ controlnet.enable_gradient_checkpointing()
727
+
728
+ if args.scale_lr:
729
+ args.learning_rate = (
730
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
731
+ )
732
+
733
+ # Initialize the optimizer
734
+ if args.use_8bit_adam:
735
+ try:
736
+ import bitsandbytes as bnb
737
+ except ImportError:
738
+ raise ImportError(
739
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
740
+ )
741
+
742
+ optimizer_cls = bnb.optim.AdamW8bit
743
+ else:
744
+ optimizer_cls = torch.optim.AdamW
745
+
746
+ params_to_optimize = controlnet.parameters()
747
+ optimizer = optimizer_cls(
748
+ params_to_optimize,
749
+ lr=args.learning_rate,
750
+ betas=(args.adam_beta1, args.adam_beta2),
751
+ weight_decay=args.adam_weight_decay,
752
+ eps=args.adam_epsilon,
753
+ )
754
+
755
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
756
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
757
+
758
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
759
+ # download the dataset.
760
+ if args.dataset_name is not None:
761
+ # Downloading and loading a dataset from the hub.
762
+ dataset = load_dataset(
763
+ args.dataset_name,
764
+ args.dataset_config_name,
765
+ cache_dir=args.cache_dir,
766
+ data_dir=args.train_data_dir,
767
+ )
768
+ else:
769
+ data_files = {}
770
+ if args.train_data_dir is not None:
771
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
772
+ dataset = load_dataset(
773
+ "imagefolder",
774
+ data_files=data_files,
775
+ cache_dir=args.cache_dir,
776
+ )
777
+ # See more about loading custom images at
778
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
779
+
780
+ # Preprocessing the datasets.
781
+ # We need to tokenize inputs and targets.
782
+ column_names = dataset["train"].column_names
783
+
784
+ # 6. Get the column names for input/target.
785
+ if args.image_column is None:
786
+ image_column = column_names[0]
787
+ else:
788
+ image_column = args.image_column
789
+ if image_column not in column_names:
790
+ raise ValueError(
791
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
792
+ )
793
+ if args.caption_column is None:
794
+ caption_column = column_names[1]
795
+ else:
796
+ caption_column = args.caption_column
797
+ if caption_column not in column_names:
798
+ raise ValueError(
799
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
800
+ )
801
+
802
+ if args.conditioning_image_column is None:
803
+ conditioning_image_column = column_names[2]
804
+ logger.info(f"conditioning image column defaulting to {conditioning_image_column}")
805
+ else:
806
+ conditioning_image_column = args.conditioning_image_column
807
+ if conditioning_image_column not in column_names:
808
+ raise ValueError(
809
+ f"`--conditioning_image_column` value '{args.conditioning_image_column}' not found in dataset columns. Dataset columns are: {', '.join(column_names)}"
810
+ )
811
+
812
+ # Preprocessing the datasets.
813
+ # We need to tokenize input captions and transform the images.
814
+ def tokenize_captions(examples, is_train=True, proportion_empty_prompts=0.0, max_length=120):
815
+ captions = []
816
+ for caption in examples[caption_column]:
817
+ if random.random() < proportion_empty_prompts:
818
+ captions.append("")
819
+ elif isinstance(caption, str):
820
+ captions.append(caption)
821
+ elif isinstance(caption, (list, np.ndarray)):
822
+ # take a random caption if there are multiple
823
+ captions.append(random.choice(caption) if is_train else caption[0])
824
+ else:
825
+ raise ValueError(
826
+ f"Caption column `{caption_column}` should contain either strings or lists of strings."
827
+ )
828
+ inputs = tokenizer(captions, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt")
829
+ return inputs.input_ids, inputs.attention_mask
830
+
831
+ # Preprocessing the datasets.
832
+ train_transforms = transforms.Compose(
833
+ [
834
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
835
+ transforms.CenterCrop(args.resolution),
836
+ transforms.ToTensor(),
837
+ transforms.Normalize([0.5], [0.5]),
838
+ ]
839
+ )
840
+
841
+ conditioning_image_transforms = transforms.Compose(
842
+ [
843
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
844
+ transforms.CenterCrop(args.resolution),
845
+ transforms.ToTensor(),
846
+ ]
847
+ )
848
+
849
+ def preprocess_train(examples):
850
+ images = [image.convert("RGB") for image in examples[image_column]]
851
+ examples["pixel_values"] = [train_transforms(image) for image in images]
852
+
853
+ conditioning_images = [image.convert("RGB") for image in examples[args.conditioning_image_column]]
854
+ examples["conditioning_pixel_values"] = [conditioning_image_transforms(image) for image in conditioning_images]
855
+
856
+ examples["input_ids"], examples["prompt_attention_mask"] = tokenize_captions(
857
+ examples, proportion_empty_prompts=args.proportion_empty_prompts, max_length=max_length
858
+ )
859
+
860
+ return examples
861
+
862
+ with accelerator.main_process_first():
863
+ if args.max_train_samples is not None:
864
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
865
+ # Set the training transforms
866
+ train_dataset = dataset["train"].with_transform(preprocess_train)
867
+
868
+ def collate_fn(examples):
869
+ pixel_values = torch.stack([example["pixel_values"] for example in examples])
870
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
871
+
872
+ conditioning_pixel_values = torch.stack([example["conditioning_pixel_values"] for example in examples])
873
+ conditioning_pixel_values = conditioning_pixel_values.to(memory_format=torch.contiguous_format).float()
874
+
875
+ input_ids = torch.stack([example["input_ids"] for example in examples])
876
+ prompt_attention_mask = torch.stack([example["prompt_attention_mask"] for example in examples])
877
+
878
+ return {
879
+ "pixel_values": pixel_values,
880
+ "conditioning_pixel_values": conditioning_pixel_values,
881
+ "input_ids": input_ids,
882
+ "prompt_attention_mask": prompt_attention_mask,
883
+ }
884
+
885
+ # DataLoaders creation:
886
+ train_dataloader = torch.utils.data.DataLoader(
887
+ train_dataset,
888
+ shuffle=True,
889
+ collate_fn=collate_fn,
890
+ batch_size=args.train_batch_size,
891
+ num_workers=args.dataloader_num_workers,
892
+ )
893
+
894
+ # Scheduler and math around the number of training steps.
895
+ overrode_max_train_steps = False
896
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
897
+ if args.max_train_steps is None:
898
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
899
+ overrode_max_train_steps = True
900
+
901
+ lr_scheduler = get_scheduler(
902
+ args.lr_scheduler,
903
+ optimizer=optimizer,
904
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
905
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
906
+ )
907
+
908
+ # Prepare everything with our `accelerator`.
909
+ controlnet_transformer = PixArtControlNetTransformerModel(transformer, controlnet, training=True)
910
+ controlnet_transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
911
+ controlnet_transformer, optimizer, train_dataloader, lr_scheduler
912
+ )
913
+
914
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
915
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
916
+ if overrode_max_train_steps:
917
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
918
+ # Afterwards we recalculate our number of training epochs
919
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
920
+
921
+ # We need to initialize the trackers we use, and also store our configuration.
922
+ # The trackers initializes automatically on the main process.
923
+ if accelerator.is_main_process:
924
+ accelerator.init_trackers(args.tracker_project_name, config=vars(args))
925
+
926
+ # Train!
927
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
928
+
929
+ logger.info("***** Running training *****")
930
+ logger.info(f" Num examples = {len(train_dataset)}")
931
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
932
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
933
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
934
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
935
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
936
+ global_step = 0
937
+ first_epoch = 0
938
+
939
+ # Potentially load in the weights and states from a previous save
940
+ if args.resume_from_checkpoint:
941
+ if args.resume_from_checkpoint != "latest":
942
+ path = os.path.basename(args.resume_from_checkpoint)
943
+ else:
944
+ # Get the most recent checkpoint
945
+ dirs = os.listdir(args.output_dir)
946
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
947
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
948
+ path = dirs[-1] if len(dirs) > 0 else None
949
+
950
+ if path is None:
951
+ accelerator.print(
952
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
953
+ )
954
+ args.resume_from_checkpoint = None
955
+ initial_global_step = 0
956
+ else:
957
+ accelerator.print(f"Resuming from checkpoint {path}")
958
+ accelerator.load_state(os.path.join(args.output_dir, path))
959
+ global_step = int(path.split("-")[1])
960
+
961
+ initial_global_step = global_step
962
+ first_epoch = global_step // num_update_steps_per_epoch
963
+ else:
964
+ initial_global_step = 0
965
+
966
+ progress_bar = tqdm(
967
+ range(0, args.max_train_steps),
968
+ initial=initial_global_step,
969
+ desc="Steps",
970
+ # Only show the progress bar once on each machine.
971
+ disable=not accelerator.is_local_main_process,
972
+ )
973
+
974
+ latent_channels = transformer.config.in_channels
975
+ for epoch in range(first_epoch, args.num_train_epochs):
976
+ controlnet_transformer.controlnet.train()
977
+ train_loss = 0.0
978
+ for step, batch in enumerate(train_dataloader):
979
+ with accelerator.accumulate(controlnet):
980
+ # Convert images to latent space
981
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
982
+ latents = latents * vae.config.scaling_factor
983
+
984
+ # Convert control images to latent space
985
+ controlnet_image_latents = vae.encode(
986
+ batch["conditioning_pixel_values"].to(dtype=weight_dtype)
987
+ ).latent_dist.sample()
988
+ controlnet_image_latents = controlnet_image_latents * vae.config.scaling_factor
989
+
990
+ # Sample noise that we'll add to the latents
991
+ noise = torch.randn_like(latents)
992
+ if args.noise_offset:
993
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
994
+ noise += args.noise_offset * torch.randn(
995
+ (latents.shape[0], latents.shape[1], 1, 1), device=latents.device
996
+ )
997
+
998
+ bsz = latents.shape[0]
999
+ # Sample a random timestep for each image
1000
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
1001
+ timesteps = timesteps.long()
1002
+
1003
+ # Add noise to the latents according to the noise magnitude at each timestep
1004
+ # (this is the forward diffusion process)
1005
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
1006
+
1007
+ # Get the text embedding for conditioning
1008
+ prompt_embeds = text_encoder(batch["input_ids"], attention_mask=batch["prompt_attention_mask"])[0]
1009
+ prompt_attention_mask = batch["prompt_attention_mask"]
1010
+ # Get the target for loss depending on the prediction type
1011
+ if args.prediction_type is not None:
1012
+ # set prediction_type of scheduler if defined
1013
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
1014
+
1015
+ if noise_scheduler.config.prediction_type == "epsilon":
1016
+ target = noise
1017
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1018
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
1019
+ else:
1020
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1021
+
1022
+ # Prepare micro-conditions.
1023
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
1024
+ if getattr(transformer, "module", transformer).config.sample_size == 128:
1025
+ resolution = torch.tensor([args.resolution, args.resolution]).repeat(bsz, 1)
1026
+ aspect_ratio = torch.tensor([float(args.resolution / args.resolution)]).repeat(bsz, 1)
1027
+ resolution = resolution.to(dtype=weight_dtype, device=latents.device)
1028
+ aspect_ratio = aspect_ratio.to(dtype=weight_dtype, device=latents.device)
1029
+ added_cond_kwargs = {"resolution": resolution, "aspect_ratio": aspect_ratio}
1030
+
1031
+ # Predict the noise residual and compute loss
1032
+ model_pred = controlnet_transformer(
1033
+ noisy_latents,
1034
+ encoder_hidden_states=prompt_embeds,
1035
+ encoder_attention_mask=prompt_attention_mask,
1036
+ timestep=timesteps,
1037
+ controlnet_cond=controlnet_image_latents,
1038
+ added_cond_kwargs=added_cond_kwargs,
1039
+ return_dict=False,
1040
+ )[0]
1041
+
1042
+ if transformer.config.out_channels // 2 == latent_channels:
1043
+ model_pred = model_pred.chunk(2, dim=1)[0]
1044
+ else:
1045
+ model_pred = model_pred
1046
+
1047
+ if args.snr_gamma is None:
1048
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1049
+ else:
1050
+ # Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
1051
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
1052
+ # This is discussed in Section 4.2 of the same paper.
1053
+ snr = compute_snr(noise_scheduler, timesteps)
1054
+ if noise_scheduler.config.prediction_type == "v_prediction":
1055
+ # Velocity objective requires that we add one to SNR values before we divide by them.
1056
+ snr = snr + 1
1057
+ mse_loss_weights = (
1058
+ torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(dim=1)[0] / snr
1059
+ )
1060
+
1061
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
1062
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
1063
+ loss = loss.mean()
1064
+
1065
+ # Gather the losses across all processes for logging (if we use distributed training).
1066
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
1067
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1068
+
1069
+ # Backpropagate
1070
+ accelerator.backward(loss)
1071
+ if accelerator.sync_gradients:
1072
+ params_to_clip = controlnet_transformer.controlnet.parameters()
1073
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1074
+ optimizer.step()
1075
+ lr_scheduler.step()
1076
+ optimizer.zero_grad()
1077
+
1078
+ # Checks if the accelerator has performed an optimization step behind the scenes
1079
+ if accelerator.sync_gradients:
1080
+ progress_bar.update(1)
1081
+ global_step += 1
1082
+ accelerator.log({"train_loss": train_loss}, step=global_step)
1083
+ train_loss = 0.0
1084
+
1085
+ if accelerator.is_main_process:
1086
+ if global_step % args.checkpointing_steps == 0:
1087
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1088
+ if args.checkpoints_total_limit is not None:
1089
+ checkpoints = os.listdir(args.output_dir)
1090
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1091
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1092
+
1093
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1094
+ if len(checkpoints) >= args.checkpoints_total_limit:
1095
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1096
+ removing_checkpoints = checkpoints[0:num_to_remove]
1097
+
1098
+ logger.info(
1099
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1100
+ )
1101
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1102
+
1103
+ for removing_checkpoint in removing_checkpoints:
1104
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1105
+ shutil.rmtree(removing_checkpoint)
1106
+
1107
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1108
+ accelerator.save_state(save_path)
1109
+
1110
+ logger.info(f"Saved state to {save_path}")
1111
+
1112
+ if args.validation_prompt is not None and global_step % args.validation_steps == 0:
1113
+ log_validation(
1114
+ vae,
1115
+ transformer,
1116
+ controlnet_transformer.controlnet,
1117
+ tokenizer,
1118
+ noise_scheduler,
1119
+ text_encoder,
1120
+ args,
1121
+ accelerator,
1122
+ weight_dtype,
1123
+ global_step,
1124
+ is_final_validation=False,
1125
+ )
1126
+
1127
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1128
+ progress_bar.set_postfix(**logs)
1129
+
1130
+ if global_step >= args.max_train_steps:
1131
+ break
1132
+
1133
+ # Save the lora layers
1134
+ accelerator.wait_for_everyone()
1135
+ if accelerator.is_main_process:
1136
+ controlnet = unwrap_model(controlnet_transformer.controlnet, keep_fp32_wrapper=False)
1137
+ controlnet.save_pretrained(os.path.join(args.output_dir, "controlnet"))
1138
+
1139
+ image_logs = None
1140
+ if args.validation_prompt is not None:
1141
+ image_logs = log_validation(
1142
+ vae,
1143
+ transformer,
1144
+ controlnet,
1145
+ tokenizer,
1146
+ noise_scheduler,
1147
+ text_encoder,
1148
+ args,
1149
+ accelerator,
1150
+ weight_dtype,
1151
+ global_step,
1152
+ is_final_validation=True,
1153
+ )
1154
+
1155
+ if args.push_to_hub:
1156
+ save_model_card(
1157
+ repo_id,
1158
+ image_logs=image_logs,
1159
+ base_model=args.pretrained_model_name_or_path,
1160
+ dataset_name=args.dataset_name,
1161
+ repo_folder=args.output_dir,
1162
+ )
1163
+ upload_folder(
1164
+ repo_id=repo_id,
1165
+ folder_path=args.output_dir,
1166
+ commit_message="End of training",
1167
+ ignore_patterns=["step_*", "epoch_*"],
1168
+ )
1169
+
1170
+ accelerator.end_training()
1171
+
1172
+
1173
+ if __name__ == "__main__":
1174
+ main()
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PromptDiffusion Pipeline
2
+
3
+ From the project [page](https://zhendong-wang.github.io/prompt-diffusion.github.io/)
4
+
5
+ "With a prompt consisting of a task-specific example pair of images and text guidance, and a new query image, Prompt Diffusion can comprehend the desired task and generate the corresponding output image on both seen (trained) and unseen (new) task types."
6
+
7
+ For any usage questions, please refer to the [paper](https://huggingface.co/papers/2305.01115).
8
+
9
+ Prepare models by converting them from the [checkpoint](https://huggingface.co/zhendongw/prompt-diffusion)
10
+
11
+ To convert the controlnet, use cldm_v15.yaml from the [repository](https://github.com/Zhendong-Wang/Prompt-Diffusion/tree/main/models/):
12
+
13
+ ```bash
14
+ python convert_original_promptdiffusion_to_diffusers.py --checkpoint_path path-to-network-step04999.ckpt --original_config_file path-to-cldm_v15.yaml --dump_path path-to-output-directory
15
+ ```
16
+
17
+ To learn about how to convert the fine-tuned stable diffusion model, see the [Load different Stable Diffusion formats guide](https://huggingface.co/docs/diffusers/main/en/using-diffusers/other-formats).
18
+
19
+
20
+ ```py
21
+ import torch
22
+ from diffusers import UniPCMultistepScheduler
23
+ from diffusers.utils import load_image
24
+ from promptdiffusioncontrolnet import PromptDiffusionControlNetModel
25
+ from pipeline_prompt_diffusion import PromptDiffusionPipeline
26
+
27
+
28
+ from PIL import ImageOps
29
+
30
+ image_a = ImageOps.invert(load_image("https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/house_line.png?raw=true"))
31
+
32
+ image_b = load_image("https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/house.png?raw=true")
33
+ query = ImageOps.invert(load_image("https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/new_01.png?raw=true"))
34
+
35
+ # load prompt diffusion controlnet and prompt diffusion
36
+
37
+ controlnet = PromptDiffusionControlNetModel.from_pretrained("iczaw/prompt-diffusion-diffusers", subfolder="controlnet", torch_dtype=torch.float16)
38
+ model_id = "path-to-model"
39
+ pipe = PromptDiffusionPipeline.from_pretrained("iczaw/prompt-diffusion-diffusers", subfolder="base", controlnet=controlnet, torch_dtype=torch.float16, variant="fp16")
40
+
41
+ # speed up diffusion process with faster scheduler and memory optimization
42
+ pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
43
+ # remove following line if xformers is not installed
44
+ pipe.enable_xformers_memory_efficient_attention()
45
+ pipe.enable_model_cpu_offload()
46
+ # generate image
47
+ generator = torch.manual_seed(0)
48
+ image = pipe("a tortoise", num_inference_steps=20, generator=generator, image_pair=[image_a,image_b], image=query).images[0]
49
+ ```
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/convert_original_promptdiffusion_to_diffusers.py ADDED
@@ -0,0 +1,2119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Conversion script for stable diffusion checkpoints which _only_ contain a controlnet."""
16
+
17
+ import argparse
18
+ import re
19
+ from contextlib import nullcontext
20
+ from io import BytesIO
21
+ from typing import Dict, Optional, Union
22
+
23
+ import requests
24
+ import torch
25
+ import yaml
26
+ from promptdiffusioncontrolnet import PromptDiffusionControlNetModel
27
+ from transformers import (
28
+ AutoFeatureExtractor,
29
+ BertTokenizerFast,
30
+ CLIPImageProcessor,
31
+ CLIPTextConfig,
32
+ CLIPTextModel,
33
+ CLIPTextModelWithProjection,
34
+ CLIPTokenizer,
35
+ CLIPVisionConfig,
36
+ CLIPVisionModelWithProjection,
37
+ )
38
+
39
+ from diffusers.models import (
40
+ AutoencoderKL,
41
+ ControlNetModel,
42
+ PriorTransformer,
43
+ UNet2DConditionModel,
44
+ )
45
+ from diffusers.pipelines.latent_diffusion.pipeline_latent_diffusion import LDMBertConfig, LDMBertModel
46
+ from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
47
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
48
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
49
+ from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
50
+ from diffusers.schedulers import (
51
+ DDIMScheduler,
52
+ DDPMScheduler,
53
+ DPMSolverMultistepScheduler,
54
+ EulerAncestralDiscreteScheduler,
55
+ EulerDiscreteScheduler,
56
+ HeunDiscreteScheduler,
57
+ LMSDiscreteScheduler,
58
+ PNDMScheduler,
59
+ UnCLIPScheduler,
60
+ )
61
+ from diffusers.utils import is_accelerate_available, logging
62
+ from diffusers.utils.constants import DIFFUSERS_REQUEST_TIMEOUT
63
+
64
+
65
+ if is_accelerate_available():
66
+ from accelerate import init_empty_weights
67
+ from accelerate.utils import set_module_tensor_to_device
68
+
69
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
70
+
71
+
72
+ def shave_segments(path, n_shave_prefix_segments=1):
73
+ """
74
+ Removes segments. Positive values shave the first segments, negative shave the last segments.
75
+ """
76
+ if n_shave_prefix_segments >= 0:
77
+ return ".".join(path.split(".")[n_shave_prefix_segments:])
78
+ else:
79
+ return ".".join(path.split(".")[:n_shave_prefix_segments])
80
+
81
+
82
+ def renew_resnet_paths(old_list, n_shave_prefix_segments=0):
83
+ """
84
+ Updates paths inside resnets to the new naming scheme (local renaming)
85
+ """
86
+ mapping = []
87
+ for old_item in old_list:
88
+ new_item = old_item.replace("in_layers.0", "norm1")
89
+ new_item = new_item.replace("in_layers.2", "conv1")
90
+
91
+ new_item = new_item.replace("out_layers.0", "norm2")
92
+ new_item = new_item.replace("out_layers.3", "conv2")
93
+
94
+ new_item = new_item.replace("emb_layers.1", "time_emb_proj")
95
+ new_item = new_item.replace("skip_connection", "conv_shortcut")
96
+
97
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
98
+
99
+ mapping.append({"old": old_item, "new": new_item})
100
+
101
+ return mapping
102
+
103
+
104
+ def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0):
105
+ """
106
+ Updates paths inside resnets to the new naming scheme (local renaming)
107
+ """
108
+ mapping = []
109
+ for old_item in old_list:
110
+ new_item = old_item
111
+
112
+ new_item = new_item.replace("nin_shortcut", "conv_shortcut")
113
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
114
+
115
+ mapping.append({"old": old_item, "new": new_item})
116
+
117
+ return mapping
118
+
119
+
120
+ def renew_attention_paths(old_list, n_shave_prefix_segments=0):
121
+ """
122
+ Updates paths inside attentions to the new naming scheme (local renaming)
123
+ """
124
+ mapping = []
125
+ for old_item in old_list:
126
+ new_item = old_item
127
+
128
+ # new_item = new_item.replace('norm.weight', 'group_norm.weight')
129
+ # new_item = new_item.replace('norm.bias', 'group_norm.bias')
130
+
131
+ # new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')
132
+ # new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')
133
+
134
+ # new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
135
+
136
+ mapping.append({"old": old_item, "new": new_item})
137
+
138
+ return mapping
139
+
140
+
141
+ def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):
142
+ """
143
+ Updates paths inside attentions to the new naming scheme (local renaming)
144
+ """
145
+ mapping = []
146
+ for old_item in old_list:
147
+ new_item = old_item
148
+
149
+ new_item = new_item.replace("norm.weight", "group_norm.weight")
150
+ new_item = new_item.replace("norm.bias", "group_norm.bias")
151
+
152
+ new_item = new_item.replace("q.weight", "to_q.weight")
153
+ new_item = new_item.replace("q.bias", "to_q.bias")
154
+
155
+ new_item = new_item.replace("k.weight", "to_k.weight")
156
+ new_item = new_item.replace("k.bias", "to_k.bias")
157
+
158
+ new_item = new_item.replace("v.weight", "to_v.weight")
159
+ new_item = new_item.replace("v.bias", "to_v.bias")
160
+
161
+ new_item = new_item.replace("proj_out.weight", "to_out.0.weight")
162
+ new_item = new_item.replace("proj_out.bias", "to_out.0.bias")
163
+
164
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
165
+
166
+ mapping.append({"old": old_item, "new": new_item})
167
+
168
+ return mapping
169
+
170
+
171
+ def assign_to_checkpoint(
172
+ paths, checkpoint, old_checkpoint, attention_paths_to_split=None, additional_replacements=None, config=None
173
+ ):
174
+ """
175
+ This does the final conversion step: take locally converted weights and apply a global renaming to them. It splits
176
+ attention layers, and takes into account additional replacements that may arise.
177
+
178
+ Assigns the weights to the new checkpoint.
179
+ """
180
+ assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."
181
+
182
+ # Splits the attention layers into three variables.
183
+ if attention_paths_to_split is not None:
184
+ for path, path_map in attention_paths_to_split.items():
185
+ old_tensor = old_checkpoint[path]
186
+ channels = old_tensor.shape[0] // 3
187
+
188
+ target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)
189
+
190
+ num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3
191
+
192
+ old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])
193
+ query, key, value = old_tensor.split(channels // num_heads, dim=1)
194
+
195
+ checkpoint[path_map["query"]] = query.reshape(target_shape)
196
+ checkpoint[path_map["key"]] = key.reshape(target_shape)
197
+ checkpoint[path_map["value"]] = value.reshape(target_shape)
198
+
199
+ for path in paths:
200
+ new_path = path["new"]
201
+
202
+ # These have already been assigned
203
+ if attention_paths_to_split is not None and new_path in attention_paths_to_split:
204
+ continue
205
+
206
+ # Global renaming happens here
207
+ new_path = new_path.replace("middle_block.0", "mid_block.resnets.0")
208
+ new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")
209
+ new_path = new_path.replace("middle_block.2", "mid_block.resnets.1")
210
+
211
+ if additional_replacements is not None:
212
+ for replacement in additional_replacements:
213
+ new_path = new_path.replace(replacement["old"], replacement["new"])
214
+
215
+ # proj_attn.weight has to be converted from conv 1D to linear
216
+ is_attn_weight = "proj_attn.weight" in new_path or ("attentions" in new_path and "to_" in new_path)
217
+ shape = old_checkpoint[path["old"]].shape
218
+ if is_attn_weight and len(shape) == 3:
219
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]
220
+ elif is_attn_weight and len(shape) == 4:
221
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0, 0]
222
+ else:
223
+ checkpoint[new_path] = old_checkpoint[path["old"]]
224
+
225
+
226
+ def conv_attn_to_linear(checkpoint):
227
+ keys = list(checkpoint.keys())
228
+ attn_keys = ["query.weight", "key.weight", "value.weight"]
229
+ for key in keys:
230
+ if ".".join(key.split(".")[-2:]) in attn_keys:
231
+ if checkpoint[key].ndim > 2:
232
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
233
+ elif "proj_attn.weight" in key:
234
+ if checkpoint[key].ndim > 2:
235
+ checkpoint[key] = checkpoint[key][:, :, 0]
236
+
237
+
238
+ def create_unet_diffusers_config(original_config, image_size: int, controlnet=False):
239
+ """
240
+ Creates a config for the diffusers based on the config of the LDM model.
241
+ """
242
+ if controlnet:
243
+ unet_params = original_config["model"]["params"]["control_stage_config"]["params"]
244
+ else:
245
+ if (
246
+ "unet_config" in original_config["model"]["params"]
247
+ and original_config["model"]["params"]["unet_config"] is not None
248
+ ):
249
+ unet_params = original_config["model"]["params"]["unet_config"]["params"]
250
+ else:
251
+ unet_params = original_config["model"]["params"]["network_config"]["params"]
252
+
253
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
254
+
255
+ block_out_channels = [unet_params["model_channels"] * mult for mult in unet_params["channel_mult"]]
256
+
257
+ down_block_types = []
258
+ resolution = 1
259
+ for i in range(len(block_out_channels)):
260
+ block_type = "CrossAttnDownBlock2D" if resolution in unet_params["attention_resolutions"] else "DownBlock2D"
261
+ down_block_types.append(block_type)
262
+ if i != len(block_out_channels) - 1:
263
+ resolution *= 2
264
+
265
+ up_block_types = []
266
+ for i in range(len(block_out_channels)):
267
+ block_type = "CrossAttnUpBlock2D" if resolution in unet_params["attention_resolutions"] else "UpBlock2D"
268
+ up_block_types.append(block_type)
269
+ resolution //= 2
270
+
271
+ if unet_params["transformer_depth"] is not None:
272
+ transformer_layers_per_block = (
273
+ unet_params["transformer_depth"]
274
+ if isinstance(unet_params["transformer_depth"], int)
275
+ else list(unet_params["transformer_depth"])
276
+ )
277
+ else:
278
+ transformer_layers_per_block = 1
279
+
280
+ vae_scale_factor = 2 ** (len(vae_params["ch_mult"]) - 1)
281
+
282
+ head_dim = unet_params["num_heads"] if "num_heads" in unet_params else None
283
+ use_linear_projection = (
284
+ unet_params["use_linear_in_transformer"] if "use_linear_in_transformer" in unet_params else False
285
+ )
286
+ if use_linear_projection:
287
+ # stable diffusion 2-base-512 and 2-768
288
+ if head_dim is None:
289
+ head_dim_mult = unet_params["model_channels"] // unet_params["num_head_channels"]
290
+ head_dim = [head_dim_mult * c for c in list(unet_params["channel_mult"])]
291
+
292
+ class_embed_type = None
293
+ addition_embed_type = None
294
+ addition_time_embed_dim = None
295
+ projection_class_embeddings_input_dim = None
296
+ context_dim = None
297
+
298
+ if unet_params["context_dim"] is not None:
299
+ context_dim = (
300
+ unet_params["context_dim"]
301
+ if isinstance(unet_params["context_dim"], int)
302
+ else unet_params["context_dim"][0]
303
+ )
304
+
305
+ if "num_classes" in unet_params:
306
+ if unet_params["num_classes"] == "sequential":
307
+ if context_dim in [2048, 1280]:
308
+ # SDXL
309
+ addition_embed_type = "text_time"
310
+ addition_time_embed_dim = 256
311
+ else:
312
+ class_embed_type = "projection"
313
+ assert "adm_in_channels" in unet_params
314
+ projection_class_embeddings_input_dim = unet_params["adm_in_channels"]
315
+
316
+ config = {
317
+ "sample_size": image_size // vae_scale_factor,
318
+ "in_channels": unet_params["in_channels"],
319
+ "down_block_types": tuple(down_block_types),
320
+ "block_out_channels": tuple(block_out_channels),
321
+ "layers_per_block": unet_params["num_res_blocks"],
322
+ "cross_attention_dim": context_dim,
323
+ "attention_head_dim": head_dim,
324
+ "use_linear_projection": use_linear_projection,
325
+ "class_embed_type": class_embed_type,
326
+ "addition_embed_type": addition_embed_type,
327
+ "addition_time_embed_dim": addition_time_embed_dim,
328
+ "projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
329
+ "transformer_layers_per_block": transformer_layers_per_block,
330
+ }
331
+
332
+ if "disable_self_attentions" in unet_params:
333
+ config["only_cross_attention"] = unet_params["disable_self_attentions"]
334
+
335
+ if "num_classes" in unet_params and isinstance(unet_params["num_classes"], int):
336
+ config["num_class_embeds"] = unet_params["num_classes"]
337
+
338
+ if controlnet:
339
+ config["conditioning_channels"] = unet_params["hint_channels"]
340
+ else:
341
+ config["out_channels"] = unet_params["out_channels"]
342
+ config["up_block_types"] = tuple(up_block_types)
343
+
344
+ return config
345
+
346
+
347
+ def create_vae_diffusers_config(original_config, image_size: int):
348
+ """
349
+ Creates a config for the diffusers based on the config of the LDM model.
350
+ """
351
+ vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
352
+ _ = original_config["model"]["params"]["first_stage_config"]["params"]["embed_dim"]
353
+
354
+ block_out_channels = [vae_params["ch"] * mult for mult in vae_params["ch_mult"]]
355
+ down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
356
+ up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
357
+
358
+ config = {
359
+ "sample_size": image_size,
360
+ "in_channels": vae_params["in_channels"],
361
+ "out_channels": vae_params["out_ch"],
362
+ "down_block_types": tuple(down_block_types),
363
+ "up_block_types": tuple(up_block_types),
364
+ "block_out_channels": tuple(block_out_channels),
365
+ "latent_channels": vae_params["z_channels"],
366
+ "layers_per_block": vae_params["num_res_blocks"],
367
+ }
368
+ return config
369
+
370
+
371
+ def create_diffusers_schedular(original_config):
372
+ schedular = DDIMScheduler(
373
+ num_train_timesteps=original_config["model"]["params"]["timesteps"],
374
+ beta_start=original_config["model"]["params"]["linear_start"],
375
+ beta_end=original_config["model"]["params"]["linear_end"],
376
+ beta_schedule="scaled_linear",
377
+ )
378
+ return schedular
379
+
380
+
381
+ def create_ldm_bert_config(original_config):
382
+ bert_params = original_config["model"]["params"]["cond_stage_config"]["params"]
383
+ config = LDMBertConfig(
384
+ d_model=bert_params.n_embed,
385
+ encoder_layers=bert_params.n_layer,
386
+ encoder_ffn_dim=bert_params.n_embed * 4,
387
+ )
388
+ return config
389
+
390
+
391
+ def convert_ldm_unet_checkpoint(
392
+ checkpoint,
393
+ config,
394
+ path=None,
395
+ extract_ema=False,
396
+ controlnet=False,
397
+ skip_extract_state_dict=False,
398
+ promptdiffusion=False,
399
+ ):
400
+ """
401
+ Takes a state dict and a config, and returns a converted checkpoint.
402
+ """
403
+
404
+ if skip_extract_state_dict:
405
+ unet_state_dict = checkpoint
406
+ else:
407
+ # extract state_dict for UNet
408
+ unet_state_dict = {}
409
+ keys = list(checkpoint.keys())
410
+
411
+ if controlnet:
412
+ unet_key = "control_model."
413
+ else:
414
+ unet_key = "model.diffusion_model."
415
+
416
+ # at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
417
+ if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
418
+ logger.warning(f"Checkpoint {path} has both EMA and non-EMA weights.")
419
+ logger.warning(
420
+ "In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
421
+ " weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
422
+ )
423
+ for key in keys:
424
+ if key.startswith("model.diffusion_model"):
425
+ flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
426
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
427
+ else:
428
+ if sum(k.startswith("model_ema") for k in keys) > 100:
429
+ logger.warning(
430
+ "In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
431
+ " weights (usually better for inference), please make sure to add the `--extract_ema` flag."
432
+ )
433
+
434
+ for key in keys:
435
+ if key.startswith(unet_key):
436
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
437
+
438
+ new_checkpoint = {}
439
+
440
+ new_checkpoint["time_embedding.linear_1.weight"] = unet_state_dict["time_embed.0.weight"]
441
+ new_checkpoint["time_embedding.linear_1.bias"] = unet_state_dict["time_embed.0.bias"]
442
+ new_checkpoint["time_embedding.linear_2.weight"] = unet_state_dict["time_embed.2.weight"]
443
+ new_checkpoint["time_embedding.linear_2.bias"] = unet_state_dict["time_embed.2.bias"]
444
+
445
+ if config["class_embed_type"] is None:
446
+ # No parameters to port
447
+ ...
448
+ elif config["class_embed_type"] == "timestep" or config["class_embed_type"] == "projection":
449
+ new_checkpoint["class_embedding.linear_1.weight"] = unet_state_dict["label_emb.0.0.weight"]
450
+ new_checkpoint["class_embedding.linear_1.bias"] = unet_state_dict["label_emb.0.0.bias"]
451
+ new_checkpoint["class_embedding.linear_2.weight"] = unet_state_dict["label_emb.0.2.weight"]
452
+ new_checkpoint["class_embedding.linear_2.bias"] = unet_state_dict["label_emb.0.2.bias"]
453
+ else:
454
+ raise NotImplementedError(f"Not implemented `class_embed_type`: {config['class_embed_type']}")
455
+
456
+ if config["addition_embed_type"] == "text_time":
457
+ new_checkpoint["add_embedding.linear_1.weight"] = unet_state_dict["label_emb.0.0.weight"]
458
+ new_checkpoint["add_embedding.linear_1.bias"] = unet_state_dict["label_emb.0.0.bias"]
459
+ new_checkpoint["add_embedding.linear_2.weight"] = unet_state_dict["label_emb.0.2.weight"]
460
+ new_checkpoint["add_embedding.linear_2.bias"] = unet_state_dict["label_emb.0.2.bias"]
461
+
462
+ # Relevant to StableDiffusionUpscalePipeline
463
+ if "num_class_embeds" in config:
464
+ if (config["num_class_embeds"] is not None) and ("label_emb.weight" in unet_state_dict):
465
+ new_checkpoint["class_embedding.weight"] = unet_state_dict["label_emb.weight"]
466
+
467
+ new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]
468
+ new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]
469
+
470
+ if not controlnet:
471
+ new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]
472
+ new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]
473
+ new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]
474
+ new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]
475
+
476
+ # Retrieves the keys for the input blocks only
477
+ num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
478
+ input_blocks = {
479
+ layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
480
+ for layer_id in range(num_input_blocks)
481
+ }
482
+
483
+ # Retrieves the keys for the middle blocks only
484
+ num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
485
+ middle_blocks = {
486
+ layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
487
+ for layer_id in range(num_middle_blocks)
488
+ }
489
+
490
+ # Retrieves the keys for the output blocks only
491
+ num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
492
+ output_blocks = {
493
+ layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
494
+ for layer_id in range(num_output_blocks)
495
+ }
496
+
497
+ for i in range(1, num_input_blocks):
498
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
499
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
500
+
501
+ resnets = [
502
+ key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
503
+ ]
504
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
505
+
506
+ if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
507
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
508
+ f"input_blocks.{i}.0.op.weight"
509
+ )
510
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
511
+ f"input_blocks.{i}.0.op.bias"
512
+ )
513
+
514
+ paths = renew_resnet_paths(resnets)
515
+ meta_path = {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"}
516
+ assign_to_checkpoint(
517
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
518
+ )
519
+
520
+ if len(attentions):
521
+ paths = renew_attention_paths(attentions)
522
+
523
+ meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}
524
+ assign_to_checkpoint(
525
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
526
+ )
527
+
528
+ resnet_0 = middle_blocks[0]
529
+ attentions = middle_blocks[1]
530
+ resnet_1 = middle_blocks[2]
531
+
532
+ resnet_0_paths = renew_resnet_paths(resnet_0)
533
+ assign_to_checkpoint(resnet_0_paths, new_checkpoint, unet_state_dict, config=config)
534
+
535
+ resnet_1_paths = renew_resnet_paths(resnet_1)
536
+ assign_to_checkpoint(resnet_1_paths, new_checkpoint, unet_state_dict, config=config)
537
+
538
+ attentions_paths = renew_attention_paths(attentions)
539
+ meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}
540
+ assign_to_checkpoint(
541
+ attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
542
+ )
543
+
544
+ for i in range(num_output_blocks):
545
+ block_id = i // (config["layers_per_block"] + 1)
546
+ layer_in_block_id = i % (config["layers_per_block"] + 1)
547
+ output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]
548
+ output_block_list = {}
549
+
550
+ for layer in output_block_layers:
551
+ layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)
552
+ if layer_id in output_block_list:
553
+ output_block_list[layer_id].append(layer_name)
554
+ else:
555
+ output_block_list[layer_id] = [layer_name]
556
+
557
+ if len(output_block_list) > 1:
558
+ resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0" in key]
559
+ attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key]
560
+
561
+ resnet_0_paths = renew_resnet_paths(resnets)
562
+ paths = renew_resnet_paths(resnets)
563
+
564
+ meta_path = {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"}
565
+ assign_to_checkpoint(
566
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
567
+ )
568
+
569
+ output_block_list = {k: sorted(v) for k, v in output_block_list.items()}
570
+ if ["conv.bias", "conv.weight"] in output_block_list.values():
571
+ index = list(output_block_list.values()).index(["conv.bias", "conv.weight"])
572
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
573
+ f"output_blocks.{i}.{index}.conv.weight"
574
+ ]
575
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
576
+ f"output_blocks.{i}.{index}.conv.bias"
577
+ ]
578
+
579
+ # Clear attentions as they have been attributed above.
580
+ if len(attentions) == 2:
581
+ attentions = []
582
+
583
+ if len(attentions):
584
+ paths = renew_attention_paths(attentions)
585
+ meta_path = {
586
+ "old": f"output_blocks.{i}.1",
587
+ "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",
588
+ }
589
+ assign_to_checkpoint(
590
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
591
+ )
592
+ else:
593
+ resnet_0_paths = renew_resnet_paths(output_block_layers, n_shave_prefix_segments=1)
594
+ for path in resnet_0_paths:
595
+ old_path = ".".join(["output_blocks", str(i), path["old"]])
596
+ new_path = ".".join(["up_blocks", str(block_id), "resnets", str(layer_in_block_id), path["new"]])
597
+
598
+ new_checkpoint[new_path] = unet_state_dict[old_path]
599
+
600
+ if controlnet and not promptdiffusion:
601
+ # conditioning embedding
602
+
603
+ orig_index = 0
604
+
605
+ new_checkpoint["controlnet_cond_embedding.conv_in.weight"] = unet_state_dict.pop(
606
+ f"input_hint_block.{orig_index}.weight"
607
+ )
608
+ new_checkpoint["controlnet_cond_embedding.conv_in.bias"] = unet_state_dict.pop(
609
+ f"input_hint_block.{orig_index}.bias"
610
+ )
611
+
612
+ orig_index += 2
613
+
614
+ diffusers_index = 0
615
+
616
+ while diffusers_index < 6:
617
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_index}.weight"] = unet_state_dict.pop(
618
+ f"input_hint_block.{orig_index}.weight"
619
+ )
620
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_index}.bias"] = unet_state_dict.pop(
621
+ f"input_hint_block.{orig_index}.bias"
622
+ )
623
+ diffusers_index += 1
624
+ orig_index += 2
625
+
626
+ new_checkpoint["controlnet_cond_embedding.conv_out.weight"] = unet_state_dict.pop(
627
+ f"input_hint_block.{orig_index}.weight"
628
+ )
629
+ new_checkpoint["controlnet_cond_embedding.conv_out.bias"] = unet_state_dict.pop(
630
+ f"input_hint_block.{orig_index}.bias"
631
+ )
632
+
633
+ # down blocks
634
+ for i in range(num_input_blocks):
635
+ new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = unet_state_dict.pop(f"zero_convs.{i}.0.weight")
636
+ new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = unet_state_dict.pop(f"zero_convs.{i}.0.bias")
637
+
638
+ # mid block
639
+ new_checkpoint["controlnet_mid_block.weight"] = unet_state_dict.pop("middle_block_out.0.weight")
640
+ new_checkpoint["controlnet_mid_block.bias"] = unet_state_dict.pop("middle_block_out.0.bias")
641
+
642
+ if promptdiffusion:
643
+ # conditioning embedding
644
+
645
+ orig_index = 0
646
+
647
+ new_checkpoint["controlnet_cond_embedding.conv_in.weight"] = unet_state_dict.pop(
648
+ f"input_hint_block.{orig_index}.weight"
649
+ )
650
+ new_checkpoint["controlnet_cond_embedding.conv_in.bias"] = unet_state_dict.pop(
651
+ f"input_hint_block.{orig_index}.bias"
652
+ )
653
+
654
+ new_checkpoint["controlnet_query_cond_embedding.conv_in.weight"] = unet_state_dict.pop(
655
+ f"input_cond_block.{orig_index}.weight"
656
+ )
657
+ new_checkpoint["controlnet_query_cond_embedding.conv_in.bias"] = unet_state_dict.pop(
658
+ f"input_cond_block.{orig_index}.bias"
659
+ )
660
+ orig_index += 2
661
+
662
+ diffusers_index = 0
663
+
664
+ while diffusers_index < 6:
665
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_index}.weight"] = unet_state_dict.pop(
666
+ f"input_hint_block.{orig_index}.weight"
667
+ )
668
+ new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_index}.bias"] = unet_state_dict.pop(
669
+ f"input_hint_block.{orig_index}.bias"
670
+ )
671
+ new_checkpoint[f"controlnet_query_cond_embedding.blocks.{diffusers_index}.weight"] = unet_state_dict.pop(
672
+ f"input_cond_block.{orig_index}.weight"
673
+ )
674
+ new_checkpoint[f"controlnet_query_cond_embedding.blocks.{diffusers_index}.bias"] = unet_state_dict.pop(
675
+ f"input_cond_block.{orig_index}.bias"
676
+ )
677
+ diffusers_index += 1
678
+ orig_index += 2
679
+
680
+ new_checkpoint["controlnet_cond_embedding.conv_out.weight"] = unet_state_dict.pop(
681
+ f"input_hint_block.{orig_index}.weight"
682
+ )
683
+ new_checkpoint["controlnet_cond_embedding.conv_out.bias"] = unet_state_dict.pop(
684
+ f"input_hint_block.{orig_index}.bias"
685
+ )
686
+
687
+ new_checkpoint["controlnet_query_cond_embedding.conv_out.weight"] = unet_state_dict.pop(
688
+ f"input_cond_block.{orig_index}.weight"
689
+ )
690
+ new_checkpoint["controlnet_query_cond_embedding.conv_out.bias"] = unet_state_dict.pop(
691
+ f"input_cond_block.{orig_index}.bias"
692
+ )
693
+ # down blocks
694
+ for i in range(num_input_blocks):
695
+ new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = unet_state_dict.pop(f"zero_convs.{i}.0.weight")
696
+ new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = unet_state_dict.pop(f"zero_convs.{i}.0.bias")
697
+
698
+ # mid block
699
+ new_checkpoint["controlnet_mid_block.weight"] = unet_state_dict.pop("middle_block_out.0.weight")
700
+ new_checkpoint["controlnet_mid_block.bias"] = unet_state_dict.pop("middle_block_out.0.bias")
701
+
702
+ return new_checkpoint
703
+
704
+
705
+ def convert_ldm_vae_checkpoint(checkpoint, config):
706
+ # extract state dict for VAE
707
+ vae_state_dict = {}
708
+ keys = list(checkpoint.keys())
709
+ vae_key = "first_stage_model." if any(k.startswith("first_stage_model.") for k in keys) else ""
710
+ for key in keys:
711
+ if key.startswith(vae_key):
712
+ vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
713
+
714
+ new_checkpoint = {}
715
+
716
+ new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]
717
+ new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]
718
+ new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]
719
+ new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]
720
+ new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]
721
+ new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]
722
+
723
+ new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]
724
+ new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]
725
+ new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]
726
+ new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]
727
+ new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]
728
+ new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]
729
+
730
+ new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
731
+ new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
732
+ new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]
733
+ new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]
734
+
735
+ # Retrieves the keys for the encoder down blocks only
736
+ num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})
737
+ down_blocks = {
738
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
739
+ }
740
+
741
+ # Retrieves the keys for the decoder up blocks only
742
+ num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})
743
+ up_blocks = {
744
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
745
+ }
746
+
747
+ for i in range(num_down_blocks):
748
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
749
+
750
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
751
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
752
+ f"encoder.down.{i}.downsample.conv.weight"
753
+ )
754
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
755
+ f"encoder.down.{i}.downsample.conv.bias"
756
+ )
757
+
758
+ paths = renew_vae_resnet_paths(resnets)
759
+ meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}
760
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
761
+
762
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
763
+ num_mid_res_blocks = 2
764
+ for i in range(1, num_mid_res_blocks + 1):
765
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
766
+
767
+ paths = renew_vae_resnet_paths(resnets)
768
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
769
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
770
+
771
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
772
+ paths = renew_vae_attention_paths(mid_attentions)
773
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
774
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
775
+ conv_attn_to_linear(new_checkpoint)
776
+
777
+ for i in range(num_up_blocks):
778
+ block_id = num_up_blocks - 1 - i
779
+ resnets = [
780
+ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
781
+ ]
782
+
783
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
784
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
785
+ f"decoder.up.{block_id}.upsample.conv.weight"
786
+ ]
787
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
788
+ f"decoder.up.{block_id}.upsample.conv.bias"
789
+ ]
790
+
791
+ paths = renew_vae_resnet_paths(resnets)
792
+ meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}
793
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
794
+
795
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
796
+ num_mid_res_blocks = 2
797
+ for i in range(1, num_mid_res_blocks + 1):
798
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
799
+
800
+ paths = renew_vae_resnet_paths(resnets)
801
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
802
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
803
+
804
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
805
+ paths = renew_vae_attention_paths(mid_attentions)
806
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
807
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
808
+ conv_attn_to_linear(new_checkpoint)
809
+ return new_checkpoint
810
+
811
+
812
+ def convert_ldm_bert_checkpoint(checkpoint, config):
813
+ def _copy_attn_layer(hf_attn_layer, pt_attn_layer):
814
+ hf_attn_layer.q_proj.weight.data = pt_attn_layer.to_q.weight
815
+ hf_attn_layer.k_proj.weight.data = pt_attn_layer.to_k.weight
816
+ hf_attn_layer.v_proj.weight.data = pt_attn_layer.to_v.weight
817
+
818
+ hf_attn_layer.out_proj.weight = pt_attn_layer.to_out.weight
819
+ hf_attn_layer.out_proj.bias = pt_attn_layer.to_out.bias
820
+
821
+ def _copy_linear(hf_linear, pt_linear):
822
+ hf_linear.weight = pt_linear.weight
823
+ hf_linear.bias = pt_linear.bias
824
+
825
+ def _copy_layer(hf_layer, pt_layer):
826
+ # copy layer norms
827
+ _copy_linear(hf_layer.self_attn_layer_norm, pt_layer[0][0])
828
+ _copy_linear(hf_layer.final_layer_norm, pt_layer[1][0])
829
+
830
+ # copy attn
831
+ _copy_attn_layer(hf_layer.self_attn, pt_layer[0][1])
832
+
833
+ # copy MLP
834
+ pt_mlp = pt_layer[1][1]
835
+ _copy_linear(hf_layer.fc1, pt_mlp.net[0][0])
836
+ _copy_linear(hf_layer.fc2, pt_mlp.net[2])
837
+
838
+ def _copy_layers(hf_layers, pt_layers):
839
+ for i, hf_layer in enumerate(hf_layers):
840
+ if i != 0:
841
+ i += i
842
+ pt_layer = pt_layers[i : i + 2]
843
+ _copy_layer(hf_layer, pt_layer)
844
+
845
+ hf_model = LDMBertModel(config).eval()
846
+
847
+ # copy embeds
848
+ hf_model.model.embed_tokens.weight = checkpoint.transformer.token_emb.weight
849
+ hf_model.model.embed_positions.weight.data = checkpoint.transformer.pos_emb.emb.weight
850
+
851
+ # copy layer norm
852
+ _copy_linear(hf_model.model.layer_norm, checkpoint.transformer.norm)
853
+
854
+ # copy hidden layers
855
+ _copy_layers(hf_model.model.layers, checkpoint.transformer.attn_layers.layers)
856
+
857
+ _copy_linear(hf_model.to_logits, checkpoint.transformer.to_logits)
858
+
859
+ return hf_model
860
+
861
+
862
+ def convert_ldm_clip_checkpoint(checkpoint, local_files_only=False, text_encoder=None):
863
+ if text_encoder is None:
864
+ config_name = "openai/clip-vit-large-patch14"
865
+ try:
866
+ config = CLIPTextConfig.from_pretrained(config_name, local_files_only=local_files_only)
867
+ except Exception:
868
+ raise ValueError(
869
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: 'openai/clip-vit-large-patch14'."
870
+ )
871
+
872
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
873
+ with ctx():
874
+ text_model = CLIPTextModel(config)
875
+ else:
876
+ text_model = text_encoder
877
+
878
+ keys = list(checkpoint.keys())
879
+
880
+ text_model_dict = {}
881
+
882
+ remove_prefixes = ["cond_stage_model.transformer", "conditioner.embedders.0.transformer"]
883
+
884
+ for key in keys:
885
+ for prefix in remove_prefixes:
886
+ if key.startswith(prefix):
887
+ text_model_dict[key[len(prefix + ".") :]] = checkpoint[key]
888
+
889
+ if is_accelerate_available():
890
+ for param_name, param in text_model_dict.items():
891
+ set_module_tensor_to_device(text_model, param_name, "cpu", value=param)
892
+ else:
893
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
894
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
895
+
896
+ text_model.load_state_dict(text_model_dict)
897
+
898
+ return text_model
899
+
900
+
901
+ textenc_conversion_lst = [
902
+ ("positional_embedding", "text_model.embeddings.position_embedding.weight"),
903
+ ("token_embedding.weight", "text_model.embeddings.token_embedding.weight"),
904
+ ("ln_final.weight", "text_model.final_layer_norm.weight"),
905
+ ("ln_final.bias", "text_model.final_layer_norm.bias"),
906
+ ("text_projection", "text_projection.weight"),
907
+ ]
908
+ textenc_conversion_map = {x[0]: x[1] for x in textenc_conversion_lst}
909
+
910
+ textenc_transformer_conversion_lst = [
911
+ # (stable-diffusion, HF Diffusers)
912
+ ("resblocks.", "text_model.encoder.layers."),
913
+ ("ln_1", "layer_norm1"),
914
+ ("ln_2", "layer_norm2"),
915
+ (".c_fc.", ".fc1."),
916
+ (".c_proj.", ".fc2."),
917
+ (".attn", ".self_attn"),
918
+ ("ln_final.", "transformer.text_model.final_layer_norm."),
919
+ ("token_embedding.weight", "transformer.text_model.embeddings.token_embedding.weight"),
920
+ ("positional_embedding", "transformer.text_model.embeddings.position_embedding.weight"),
921
+ ]
922
+ protected = {re.escape(x[0]): x[1] for x in textenc_transformer_conversion_lst}
923
+ textenc_pattern = re.compile("|".join(protected.keys()))
924
+
925
+
926
+ def convert_paint_by_example_checkpoint(checkpoint, local_files_only=False):
927
+ config = CLIPVisionConfig.from_pretrained("openai/clip-vit-large-patch14", local_files_only=local_files_only)
928
+ model = PaintByExampleImageEncoder(config)
929
+
930
+ keys = list(checkpoint.keys())
931
+
932
+ text_model_dict = {}
933
+
934
+ for key in keys:
935
+ if key.startswith("cond_stage_model.transformer"):
936
+ text_model_dict[key[len("cond_stage_model.transformer.") :]] = checkpoint[key]
937
+
938
+ # load clip vision
939
+ model.model.load_state_dict(text_model_dict)
940
+
941
+ # load mapper
942
+ keys_mapper = {
943
+ k[len("cond_stage_model.mapper.res") :]: v
944
+ for k, v in checkpoint.items()
945
+ if k.startswith("cond_stage_model.mapper")
946
+ }
947
+
948
+ MAPPING = {
949
+ "attn.c_qkv": ["attn1.to_q", "attn1.to_k", "attn1.to_v"],
950
+ "attn.c_proj": ["attn1.to_out.0"],
951
+ "ln_1": ["norm1"],
952
+ "ln_2": ["norm3"],
953
+ "mlp.c_fc": ["ff.net.0.proj"],
954
+ "mlp.c_proj": ["ff.net.2"],
955
+ }
956
+
957
+ mapped_weights = {}
958
+ for key, value in keys_mapper.items():
959
+ prefix = key[: len("blocks.i")]
960
+ suffix = key.split(prefix)[-1].split(".")[-1]
961
+ name = key.split(prefix)[-1].split(suffix)[0][1:-1]
962
+ mapped_names = MAPPING[name]
963
+
964
+ num_splits = len(mapped_names)
965
+ for i, mapped_name in enumerate(mapped_names):
966
+ new_name = ".".join([prefix, mapped_name, suffix])
967
+ shape = value.shape[0] // num_splits
968
+ mapped_weights[new_name] = value[i * shape : (i + 1) * shape]
969
+
970
+ model.mapper.load_state_dict(mapped_weights)
971
+
972
+ # load final layer norm
973
+ model.final_layer_norm.load_state_dict(
974
+ {
975
+ "bias": checkpoint["cond_stage_model.final_ln.bias"],
976
+ "weight": checkpoint["cond_stage_model.final_ln.weight"],
977
+ }
978
+ )
979
+
980
+ # load final proj
981
+ model.proj_out.load_state_dict(
982
+ {
983
+ "bias": checkpoint["proj_out.bias"],
984
+ "weight": checkpoint["proj_out.weight"],
985
+ }
986
+ )
987
+
988
+ # load uncond vector
989
+ model.uncond_vector.data = torch.nn.Parameter(checkpoint["learnable_vector"])
990
+ return model
991
+
992
+
993
+ def convert_open_clip_checkpoint(
994
+ checkpoint,
995
+ config_name,
996
+ prefix="cond_stage_model.model.",
997
+ has_projection=False,
998
+ local_files_only=False,
999
+ **config_kwargs,
1000
+ ):
1001
+ # text_model = CLIPTextModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="text_encoder")
1002
+ # text_model = CLIPTextModelWithProjection.from_pretrained(
1003
+ # "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280
1004
+ # )
1005
+ try:
1006
+ config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs, local_files_only=local_files_only)
1007
+ except Exception:
1008
+ raise ValueError(
1009
+ f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: '{config_name}'."
1010
+ )
1011
+
1012
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1013
+ with ctx():
1014
+ text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config)
1015
+
1016
+ keys = list(checkpoint.keys())
1017
+
1018
+ keys_to_ignore = []
1019
+ if config_name == "stabilityai/stable-diffusion-2" and config.num_hidden_layers == 23:
1020
+ # make sure to remove all keys > 22
1021
+ keys_to_ignore += [k for k in keys if k.startswith("cond_stage_model.model.transformer.resblocks.23")]
1022
+ keys_to_ignore += ["cond_stage_model.model.text_projection"]
1023
+
1024
+ text_model_dict = {}
1025
+
1026
+ if prefix + "text_projection" in checkpoint:
1027
+ d_model = int(checkpoint[prefix + "text_projection"].shape[0])
1028
+ else:
1029
+ d_model = 1024
1030
+
1031
+ text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids")
1032
+
1033
+ for key in keys:
1034
+ if key in keys_to_ignore:
1035
+ continue
1036
+ if key[len(prefix) :] in textenc_conversion_map:
1037
+ if key.endswith("text_projection"):
1038
+ value = checkpoint[key].T.contiguous()
1039
+ else:
1040
+ value = checkpoint[key]
1041
+
1042
+ text_model_dict[textenc_conversion_map[key[len(prefix) :]]] = value
1043
+
1044
+ if key.startswith(prefix + "transformer."):
1045
+ new_key = key[len(prefix + "transformer.") :]
1046
+ if new_key.endswith(".in_proj_weight"):
1047
+ new_key = new_key[: -len(".in_proj_weight")]
1048
+ new_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], new_key)
1049
+ text_model_dict[new_key + ".q_proj.weight"] = checkpoint[key][:d_model, :]
1050
+ text_model_dict[new_key + ".k_proj.weight"] = checkpoint[key][d_model : d_model * 2, :]
1051
+ text_model_dict[new_key + ".v_proj.weight"] = checkpoint[key][d_model * 2 :, :]
1052
+ elif new_key.endswith(".in_proj_bias"):
1053
+ new_key = new_key[: -len(".in_proj_bias")]
1054
+ new_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], new_key)
1055
+ text_model_dict[new_key + ".q_proj.bias"] = checkpoint[key][:d_model]
1056
+ text_model_dict[new_key + ".k_proj.bias"] = checkpoint[key][d_model : d_model * 2]
1057
+ text_model_dict[new_key + ".v_proj.bias"] = checkpoint[key][d_model * 2 :]
1058
+ else:
1059
+ new_key = textenc_pattern.sub(lambda m: protected[re.escape(m.group(0))], new_key)
1060
+
1061
+ text_model_dict[new_key] = checkpoint[key]
1062
+
1063
+ if is_accelerate_available():
1064
+ for param_name, param in text_model_dict.items():
1065
+ set_module_tensor_to_device(text_model, param_name, "cpu", value=param)
1066
+ else:
1067
+ if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1068
+ text_model_dict.pop("text_model.embeddings.position_ids", None)
1069
+
1070
+ text_model.load_state_dict(text_model_dict)
1071
+
1072
+ return text_model
1073
+
1074
+
1075
+ def stable_unclip_image_encoder(original_config, local_files_only=False):
1076
+ """
1077
+ Returns the image processor and clip image encoder for the img2img unclip pipeline.
1078
+
1079
+ We currently know of two types of stable unclip models which separately use the clip and the openclip image
1080
+ encoders.
1081
+ """
1082
+
1083
+ image_embedder_config = original_config["model"]["params"]["embedder_config"]
1084
+
1085
+ sd_clip_image_embedder_class = image_embedder_config["target"]
1086
+ sd_clip_image_embedder_class = sd_clip_image_embedder_class.split(".")[-1]
1087
+
1088
+ if sd_clip_image_embedder_class == "ClipImageEmbedder":
1089
+ clip_model_name = image_embedder_config.params.model
1090
+
1091
+ if clip_model_name == "ViT-L/14":
1092
+ feature_extractor = CLIPImageProcessor()
1093
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
1094
+ "openai/clip-vit-large-patch14", local_files_only=local_files_only
1095
+ )
1096
+ else:
1097
+ raise NotImplementedError(f"Unknown CLIP checkpoint name in stable diffusion checkpoint {clip_model_name}")
1098
+
1099
+ elif sd_clip_image_embedder_class == "FrozenOpenCLIPImageEmbedder":
1100
+ feature_extractor = CLIPImageProcessor()
1101
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
1102
+ "laion/CLIP-ViT-H-14-laion2B-s32B-b79K", local_files_only=local_files_only
1103
+ )
1104
+ else:
1105
+ raise NotImplementedError(
1106
+ f"Unknown CLIP image embedder class in stable diffusion checkpoint {sd_clip_image_embedder_class}"
1107
+ )
1108
+
1109
+ return feature_extractor, image_encoder
1110
+
1111
+
1112
+ def stable_unclip_image_noising_components(
1113
+ original_config, clip_stats_path: Optional[str] = None, device: Optional[str] = None
1114
+ ):
1115
+ """
1116
+ Returns the noising components for the img2img and txt2img unclip pipelines.
1117
+
1118
+ Converts the stability noise augmentor into
1119
+ 1. a `StableUnCLIPImageNormalizer` for holding the CLIP stats
1120
+ 2. a `DDPMScheduler` for holding the noise schedule
1121
+
1122
+ If the noise augmentor config specifies a clip stats path, the `clip_stats_path` must be provided.
1123
+ """
1124
+ noise_aug_config = original_config["model"]["params"]["noise_aug_config"]
1125
+ noise_aug_class = noise_aug_config["target"]
1126
+ noise_aug_class = noise_aug_class.split(".")[-1]
1127
+
1128
+ if noise_aug_class == "CLIPEmbeddingNoiseAugmentation":
1129
+ noise_aug_config = noise_aug_config.params
1130
+ embedding_dim = noise_aug_config.timestep_dim
1131
+ max_noise_level = noise_aug_config.noise_schedule_config.timesteps
1132
+ beta_schedule = noise_aug_config.noise_schedule_config.beta_schedule
1133
+
1134
+ image_normalizer = StableUnCLIPImageNormalizer(embedding_dim=embedding_dim)
1135
+ image_noising_scheduler = DDPMScheduler(num_train_timesteps=max_noise_level, beta_schedule=beta_schedule)
1136
+
1137
+ if "clip_stats_path" in noise_aug_config:
1138
+ if clip_stats_path is None:
1139
+ raise ValueError("This stable unclip config requires a `clip_stats_path`")
1140
+
1141
+ clip_mean, clip_std = torch.load(clip_stats_path, map_location=device)
1142
+ clip_mean = clip_mean[None, :]
1143
+ clip_std = clip_std[None, :]
1144
+
1145
+ clip_stats_state_dict = {
1146
+ "mean": clip_mean,
1147
+ "std": clip_std,
1148
+ }
1149
+
1150
+ image_normalizer.load_state_dict(clip_stats_state_dict)
1151
+ else:
1152
+ raise NotImplementedError(f"Unknown noise augmentor class: {noise_aug_class}")
1153
+
1154
+ return image_normalizer, image_noising_scheduler
1155
+
1156
+
1157
+ def convert_controlnet_checkpoint(
1158
+ checkpoint,
1159
+ original_config,
1160
+ checkpoint_path,
1161
+ image_size,
1162
+ upcast_attention,
1163
+ extract_ema,
1164
+ use_linear_projection=None,
1165
+ cross_attention_dim=None,
1166
+ ):
1167
+ ctrlnet_config = create_unet_diffusers_config(original_config, image_size=image_size, controlnet=True)
1168
+ ctrlnet_config["upcast_attention"] = upcast_attention
1169
+
1170
+ ctrlnet_config.pop("sample_size")
1171
+
1172
+ if use_linear_projection is not None:
1173
+ ctrlnet_config["use_linear_projection"] = use_linear_projection
1174
+
1175
+ if cross_attention_dim is not None:
1176
+ ctrlnet_config["cross_attention_dim"] = cross_attention_dim
1177
+
1178
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1179
+ with ctx():
1180
+ controlnet = ControlNetModel(**ctrlnet_config)
1181
+
1182
+ # Some controlnet ckpt files are distributed independently from the rest of the
1183
+ # model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
1184
+ if "time_embed.0.weight" in checkpoint:
1185
+ skip_extract_state_dict = True
1186
+ else:
1187
+ skip_extract_state_dict = False
1188
+
1189
+ converted_ctrl_checkpoint = convert_ldm_unet_checkpoint(
1190
+ checkpoint,
1191
+ ctrlnet_config,
1192
+ path=checkpoint_path,
1193
+ extract_ema=extract_ema,
1194
+ controlnet=True,
1195
+ skip_extract_state_dict=skip_extract_state_dict,
1196
+ )
1197
+
1198
+ if is_accelerate_available():
1199
+ for param_name, param in converted_ctrl_checkpoint.items():
1200
+ set_module_tensor_to_device(controlnet, param_name, "cpu", value=param)
1201
+ else:
1202
+ controlnet.load_state_dict(converted_ctrl_checkpoint)
1203
+
1204
+ return controlnet
1205
+
1206
+
1207
+ def convert_promptdiffusion_checkpoint(
1208
+ checkpoint,
1209
+ original_config,
1210
+ checkpoint_path,
1211
+ image_size,
1212
+ upcast_attention,
1213
+ extract_ema,
1214
+ use_linear_projection=None,
1215
+ cross_attention_dim=None,
1216
+ ):
1217
+ ctrlnet_config = create_unet_diffusers_config(original_config, image_size=image_size, controlnet=True)
1218
+ ctrlnet_config["upcast_attention"] = upcast_attention
1219
+
1220
+ ctrlnet_config.pop("sample_size")
1221
+
1222
+ if use_linear_projection is not None:
1223
+ ctrlnet_config["use_linear_projection"] = use_linear_projection
1224
+
1225
+ if cross_attention_dim is not None:
1226
+ ctrlnet_config["cross_attention_dim"] = cross_attention_dim
1227
+
1228
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1229
+ with ctx():
1230
+ controlnet = PromptDiffusionControlNetModel(**ctrlnet_config)
1231
+
1232
+ # Some controlnet ckpt files are distributed independently from the rest of the
1233
+ # model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
1234
+ if "time_embed.0.weight" in checkpoint:
1235
+ skip_extract_state_dict = True
1236
+ else:
1237
+ skip_extract_state_dict = False
1238
+
1239
+ converted_ctrl_checkpoint = convert_ldm_unet_checkpoint(
1240
+ checkpoint,
1241
+ ctrlnet_config,
1242
+ path=checkpoint_path,
1243
+ extract_ema=extract_ema,
1244
+ promptdiffusion=True,
1245
+ controlnet=True,
1246
+ skip_extract_state_dict=skip_extract_state_dict,
1247
+ )
1248
+
1249
+ if is_accelerate_available():
1250
+ for param_name, param in converted_ctrl_checkpoint.items():
1251
+ set_module_tensor_to_device(controlnet, param_name, "cpu", value=param)
1252
+ else:
1253
+ controlnet.load_state_dict(converted_ctrl_checkpoint)
1254
+
1255
+ return controlnet
1256
+
1257
+
1258
+ def download_from_original_stable_diffusion_ckpt(
1259
+ checkpoint_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1260
+ original_config_file: str = None,
1261
+ image_size: Optional[int] = None,
1262
+ prediction_type: str = None,
1263
+ model_type: str = None,
1264
+ extract_ema: bool = False,
1265
+ scheduler_type: str = "pndm",
1266
+ num_in_channels: Optional[int] = None,
1267
+ upcast_attention: Optional[bool] = None,
1268
+ device: str = None,
1269
+ from_safetensors: bool = False,
1270
+ stable_unclip: Optional[str] = None,
1271
+ stable_unclip_prior: Optional[str] = None,
1272
+ clip_stats_path: Optional[str] = None,
1273
+ controlnet: Optional[bool] = None,
1274
+ adapter: Optional[bool] = None,
1275
+ load_safety_checker: bool = True,
1276
+ pipeline_class: DiffusionPipeline = None,
1277
+ local_files_only=False,
1278
+ vae_path=None,
1279
+ vae=None,
1280
+ text_encoder=None,
1281
+ text_encoder_2=None,
1282
+ tokenizer=None,
1283
+ tokenizer_2=None,
1284
+ config_files=None,
1285
+ ) -> DiffusionPipeline:
1286
+ """
1287
+ Load a Stable Diffusion pipeline object from a CompVis-style `.ckpt`/`.safetensors` file and (ideally) a `.yaml`
1288
+ config file.
1289
+
1290
+ Although many of the arguments can be automatically inferred, some of these rely on brittle checks against the
1291
+ global step count, which will likely fail for models that have undergone further fine-tuning. Therefore, it is
1292
+ recommended that you override the default values and/or supply an `original_config_file` wherever possible.
1293
+
1294
+ Args:
1295
+ checkpoint_path_or_dict (`str` or `dict`): Path to `.ckpt` file, or the state dict.
1296
+ original_config_file (`str`):
1297
+ Path to `.yaml` config file corresponding to the original architecture. If `None`, will be automatically
1298
+ inferred by looking for a key that only exists in SD2.0 models.
1299
+ image_size (`int`, *optional*, defaults to 512):
1300
+ The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Diffusion v2
1301
+ Base. Use 768 for Stable Diffusion v2.
1302
+ prediction_type (`str`, *optional*):
1303
+ The prediction type that the model was trained on. Use `'epsilon'` for Stable Diffusion v1.X and Stable
1304
+ Diffusion v2 Base. Use `'v_prediction'` for Stable Diffusion v2.
1305
+ num_in_channels (`int`, *optional*, defaults to None):
1306
+ The number of input channels. If `None`, it will be automatically inferred.
1307
+ scheduler_type (`str`, *optional*, defaults to 'pndm'):
1308
+ Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm",
1309
+ "ddim"]`.
1310
+ model_type (`str`, *optional*, defaults to `None`):
1311
+ The pipeline type. `None` to automatically infer, or one of `["FrozenOpenCLIPEmbedder",
1312
+ "FrozenCLIPEmbedder", "PaintByExample"]`.
1313
+ is_img2img (`bool`, *optional*, defaults to `False`):
1314
+ Whether the model should be loaded as an img2img pipeline.
1315
+ extract_ema (`bool`, *optional*, defaults to `False`): Only relevant for
1316
+ checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights or not. Defaults to
1317
+ `False`. Pass `True` to extract the EMA weights. EMA weights usually yield higher quality images for
1318
+ inference. Non-EMA weights are usually better to continue fine-tuning.
1319
+ upcast_attention (`bool`, *optional*, defaults to `None`):
1320
+ Whether the attention computation should always be upcasted. This is necessary when running stable
1321
+ diffusion 2.1.
1322
+ device (`str`, *optional*, defaults to `None`):
1323
+ The device to use. Pass `None` to determine automatically.
1324
+ from_safetensors (`str`, *optional*, defaults to `False`):
1325
+ If `checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.
1326
+ load_safety_checker (`bool`, *optional*, defaults to `True`):
1327
+ Whether to load the safety checker or not. Defaults to `True`.
1328
+ pipeline_class (`str`, *optional*, defaults to `None`):
1329
+ The pipeline class to use. Pass `None` to determine automatically.
1330
+ local_files_only (`bool`, *optional*, defaults to `False`):
1331
+ Whether or not to only look at local files (i.e., do not try to download the model).
1332
+ vae (`AutoencoderKL`, *optional*, defaults to `None`):
1333
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. If
1334
+ this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
1335
+ text_encoder (`CLIPTextModel`, *optional*, defaults to `None`):
1336
+ An instance of [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)
1337
+ to use, specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)
1338
+ variant. If this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
1339
+ tokenizer (`CLIPTokenizer`, *optional*, defaults to `None`):
1340
+ An instance of
1341
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer)
1342
+ to use. If this parameter is `None`, the function will load a new instance of [CLIPTokenizer] by itself, if
1343
+ needed.
1344
+ config_files (`Dict[str, str]`, *optional*, defaults to `None`):
1345
+ A dictionary mapping from config file names to their contents. If this parameter is `None`, the function
1346
+ will load the config files by itself, if needed. Valid keys are:
1347
+ - `v1`: Config file for Stable Diffusion v1
1348
+ - `v2`: Config file for Stable Diffusion v2
1349
+ - `xl`: Config file for Stable Diffusion XL
1350
+ - `xl_refiner`: Config file for Stable Diffusion XL Refiner
1351
+ return: A StableDiffusionPipeline object representing the passed-in `.ckpt`/`.safetensors` file.
1352
+ """
1353
+
1354
+ # import pipelines here to avoid circular import error when using from_single_file method
1355
+ from diffusers import (
1356
+ LDMTextToImagePipeline,
1357
+ PaintByExamplePipeline,
1358
+ StableDiffusionControlNetPipeline,
1359
+ StableDiffusionInpaintPipeline,
1360
+ StableDiffusionPipeline,
1361
+ StableDiffusionUpscalePipeline,
1362
+ StableDiffusionXLControlNetInpaintPipeline,
1363
+ StableDiffusionXLImg2ImgPipeline,
1364
+ StableDiffusionXLInpaintPipeline,
1365
+ StableDiffusionXLPipeline,
1366
+ StableUnCLIPImg2ImgPipeline,
1367
+ StableUnCLIPPipeline,
1368
+ )
1369
+
1370
+ if prediction_type == "v-prediction":
1371
+ prediction_type = "v_prediction"
1372
+
1373
+ if isinstance(checkpoint_path_or_dict, str):
1374
+ if from_safetensors:
1375
+ from safetensors.torch import load_file as safe_load
1376
+
1377
+ checkpoint = safe_load(checkpoint_path_or_dict, device="cpu")
1378
+ else:
1379
+ if device is None:
1380
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1381
+ checkpoint = torch.load(checkpoint_path_or_dict, map_location=device)
1382
+ else:
1383
+ checkpoint = torch.load(checkpoint_path_or_dict, map_location=device)
1384
+ elif isinstance(checkpoint_path_or_dict, dict):
1385
+ checkpoint = checkpoint_path_or_dict
1386
+
1387
+ # Sometimes models don't have the global_step item
1388
+ if "global_step" in checkpoint:
1389
+ global_step = checkpoint["global_step"]
1390
+ else:
1391
+ logger.debug("global_step key not found in model")
1392
+ global_step = None
1393
+
1394
+ # NOTE: this while loop isn't great but this controlnet checkpoint has one additional
1395
+ # "state_dict" key https://huggingface.co/thibaud/controlnet-canny-sd21
1396
+ while "state_dict" in checkpoint:
1397
+ checkpoint = checkpoint["state_dict"]
1398
+
1399
+ if original_config_file is None:
1400
+ key_name_v2_1 = "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight"
1401
+ key_name_sd_xl_base = "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias"
1402
+ key_name_sd_xl_refiner = "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias"
1403
+ is_upscale = pipeline_class == StableDiffusionUpscalePipeline
1404
+
1405
+ config_url = None
1406
+
1407
+ # model_type = "v1"
1408
+ if config_files is not None and "v1" in config_files:
1409
+ original_config_file = config_files["v1"]
1410
+ else:
1411
+ config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
1412
+
1413
+ if key_name_v2_1 in checkpoint and checkpoint[key_name_v2_1].shape[-1] == 1024:
1414
+ # model_type = "v2"
1415
+ if config_files is not None and "v2" in config_files:
1416
+ original_config_file = config_files["v2"]
1417
+ else:
1418
+ config_url = "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml"
1419
+ if global_step == 110000:
1420
+ # v2.1 needs to upcast attention
1421
+ upcast_attention = True
1422
+ elif key_name_sd_xl_base in checkpoint:
1423
+ # only base xl has two text embedders
1424
+ if config_files is not None and "xl" in config_files:
1425
+ original_config_file = config_files["xl"]
1426
+ else:
1427
+ config_url = "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml"
1428
+ elif key_name_sd_xl_refiner in checkpoint:
1429
+ # only refiner xl has embedder and one text embedders
1430
+ if config_files is not None and "xl_refiner" in config_files:
1431
+ original_config_file = config_files["xl_refiner"]
1432
+ else:
1433
+ config_url = "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml"
1434
+
1435
+ if is_upscale:
1436
+ config_url = "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml"
1437
+
1438
+ if config_url is not None:
1439
+ original_config_file = BytesIO(requests.get(config_url, timeout=DIFFUSERS_REQUEST_TIMEOUT).content)
1440
+ else:
1441
+ with open(original_config_file, "r") as f:
1442
+ original_config_file = f.read()
1443
+
1444
+ original_config = yaml.safe_load(original_config_file)
1445
+
1446
+ # Convert the text model.
1447
+ if (
1448
+ model_type is None
1449
+ and "cond_stage_config" in original_config["model"]["params"]
1450
+ and original_config["model"]["params"]["cond_stage_config"] is not None
1451
+ ):
1452
+ model_type = original_config["model"]["params"]["cond_stage_config"]["target"].split(".")[-1]
1453
+ logger.debug(f"no `model_type` given, `model_type` inferred as: {model_type}")
1454
+ elif model_type is None and original_config["model"]["params"]["network_config"] is not None:
1455
+ if original_config["model"]["params"]["network_config"]["params"]["context_dim"] == 2048:
1456
+ model_type = "SDXL"
1457
+ else:
1458
+ model_type = "SDXL-Refiner"
1459
+ if image_size is None:
1460
+ image_size = 1024
1461
+
1462
+ if pipeline_class is None:
1463
+ # Check if we have a SDXL or SD model and initialize default pipeline
1464
+ if model_type not in ["SDXL", "SDXL-Refiner"]:
1465
+ pipeline_class = StableDiffusionPipeline if not controlnet else StableDiffusionControlNetPipeline
1466
+ else:
1467
+ pipeline_class = StableDiffusionXLPipeline if model_type == "SDXL" else StableDiffusionXLImg2ImgPipeline
1468
+
1469
+ if num_in_channels is None and pipeline_class in [
1470
+ StableDiffusionInpaintPipeline,
1471
+ StableDiffusionXLInpaintPipeline,
1472
+ StableDiffusionXLControlNetInpaintPipeline,
1473
+ ]:
1474
+ num_in_channels = 9
1475
+ if num_in_channels is None and pipeline_class == StableDiffusionUpscalePipeline:
1476
+ num_in_channels = 7
1477
+ elif num_in_channels is None:
1478
+ num_in_channels = 4
1479
+
1480
+ if "unet_config" in original_config["model"]["params"]:
1481
+ original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels
1482
+
1483
+ if (
1484
+ "parameterization" in original_config["model"]["params"]
1485
+ and original_config["model"]["params"]["parameterization"] == "v"
1486
+ ):
1487
+ if prediction_type is None:
1488
+ # NOTE: For stable diffusion 2 base it is recommended to pass `prediction_type=="epsilon"`
1489
+ # as it relies on a brittle global step parameter here
1490
+ prediction_type = "epsilon" if global_step == 875000 else "v_prediction"
1491
+ if image_size is None:
1492
+ # NOTE: For stable diffusion 2 base one has to pass `image_size==512`
1493
+ # as it relies on a brittle global step parameter here
1494
+ image_size = 512 if global_step == 875000 else 768
1495
+ else:
1496
+ if prediction_type is None:
1497
+ prediction_type = "epsilon"
1498
+ if image_size is None:
1499
+ image_size = 512
1500
+
1501
+ if controlnet is None and "control_stage_config" in original_config["model"]["params"]:
1502
+ path = checkpoint_path_or_dict if isinstance(checkpoint_path_or_dict, str) else ""
1503
+ controlnet = convert_controlnet_checkpoint(
1504
+ checkpoint, original_config, path, image_size, upcast_attention, extract_ema
1505
+ )
1506
+
1507
+ if "timesteps" in original_config["model"]["params"]:
1508
+ num_train_timesteps = original_config["model"]["params"]["timesteps"]
1509
+ else:
1510
+ num_train_timesteps = 1000
1511
+
1512
+ if model_type in ["SDXL", "SDXL-Refiner"]:
1513
+ scheduler_dict = {
1514
+ "beta_schedule": "scaled_linear",
1515
+ "beta_start": 0.00085,
1516
+ "beta_end": 0.012,
1517
+ "interpolation_type": "linear",
1518
+ "num_train_timesteps": num_train_timesteps,
1519
+ "prediction_type": "epsilon",
1520
+ "sample_max_value": 1.0,
1521
+ "set_alpha_to_one": False,
1522
+ "skip_prk_steps": True,
1523
+ "steps_offset": 1,
1524
+ "timestep_spacing": "leading",
1525
+ }
1526
+ scheduler = EulerDiscreteScheduler.from_config(scheduler_dict)
1527
+ scheduler_type = "euler"
1528
+ else:
1529
+ if "linear_start" in original_config["model"]["params"]:
1530
+ beta_start = original_config["model"]["params"]["linear_start"]
1531
+ else:
1532
+ beta_start = 0.02
1533
+
1534
+ if "linear_end" in original_config["model"]["params"]:
1535
+ beta_end = original_config["model"]["params"]["linear_end"]
1536
+ else:
1537
+ beta_end = 0.085
1538
+ scheduler = DDIMScheduler(
1539
+ beta_end=beta_end,
1540
+ beta_schedule="scaled_linear",
1541
+ beta_start=beta_start,
1542
+ num_train_timesteps=num_train_timesteps,
1543
+ steps_offset=1,
1544
+ clip_sample=False,
1545
+ set_alpha_to_one=False,
1546
+ prediction_type=prediction_type,
1547
+ )
1548
+ # make sure scheduler works correctly with DDIM
1549
+ scheduler.register_to_config(clip_sample=False)
1550
+
1551
+ if scheduler_type == "pndm":
1552
+ config = dict(scheduler.config)
1553
+ config["skip_prk_steps"] = True
1554
+ scheduler = PNDMScheduler.from_config(config)
1555
+ elif scheduler_type == "lms":
1556
+ scheduler = LMSDiscreteScheduler.from_config(scheduler.config)
1557
+ elif scheduler_type == "heun":
1558
+ scheduler = HeunDiscreteScheduler.from_config(scheduler.config)
1559
+ elif scheduler_type == "euler":
1560
+ scheduler = EulerDiscreteScheduler.from_config(scheduler.config)
1561
+ elif scheduler_type == "euler-ancestral":
1562
+ scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler.config)
1563
+ elif scheduler_type == "dpm":
1564
+ scheduler = DPMSolverMultistepScheduler.from_config(scheduler.config)
1565
+ elif scheduler_type == "ddim":
1566
+ scheduler = scheduler
1567
+ else:
1568
+ raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")
1569
+
1570
+ if pipeline_class == StableDiffusionUpscalePipeline:
1571
+ image_size = original_config["model"]["params"]["unet_config"]["params"]["image_size"]
1572
+
1573
+ # Convert the UNet2DConditionModel model.
1574
+ unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
1575
+ unet_config["upcast_attention"] = upcast_attention
1576
+
1577
+ path = checkpoint_path_or_dict if isinstance(checkpoint_path_or_dict, str) else ""
1578
+ converted_unet_checkpoint = convert_ldm_unet_checkpoint(
1579
+ checkpoint, unet_config, path=path, extract_ema=extract_ema
1580
+ )
1581
+
1582
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1583
+ with ctx():
1584
+ unet = UNet2DConditionModel(**unet_config)
1585
+
1586
+ if is_accelerate_available():
1587
+ if model_type not in ["SDXL", "SDXL-Refiner"]: # SBM Delay this.
1588
+ for param_name, param in converted_unet_checkpoint.items():
1589
+ set_module_tensor_to_device(unet, param_name, "cpu", value=param)
1590
+ else:
1591
+ unet.load_state_dict(converted_unet_checkpoint)
1592
+
1593
+ # Convert the VAE model.
1594
+ if vae_path is None and vae is None:
1595
+ vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
1596
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
1597
+
1598
+ if (
1599
+ "model" in original_config
1600
+ and "params" in original_config["model"]
1601
+ and "scale_factor" in original_config["model"]["params"]
1602
+ ):
1603
+ vae_scaling_factor = original_config["model"]["params"]["scale_factor"]
1604
+ else:
1605
+ vae_scaling_factor = 0.18215 # default SD scaling factor
1606
+
1607
+ vae_config["scaling_factor"] = vae_scaling_factor
1608
+
1609
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
1610
+ with ctx():
1611
+ vae = AutoencoderKL(**vae_config)
1612
+
1613
+ if is_accelerate_available():
1614
+ for param_name, param in converted_vae_checkpoint.items():
1615
+ set_module_tensor_to_device(vae, param_name, "cpu", value=param)
1616
+ else:
1617
+ vae.load_state_dict(converted_vae_checkpoint)
1618
+ elif vae is None:
1619
+ vae = AutoencoderKL.from_pretrained(vae_path, local_files_only=local_files_only)
1620
+
1621
+ if model_type == "FrozenOpenCLIPEmbedder":
1622
+ config_name = "stabilityai/stable-diffusion-2"
1623
+ config_kwargs = {"subfolder": "text_encoder"}
1624
+
1625
+ if text_encoder is None:
1626
+ text_model = convert_open_clip_checkpoint(
1627
+ checkpoint, config_name, local_files_only=local_files_only, **config_kwargs
1628
+ )
1629
+ else:
1630
+ text_model = text_encoder
1631
+
1632
+ try:
1633
+ tokenizer = CLIPTokenizer.from_pretrained(
1634
+ "stabilityai/stable-diffusion-2", subfolder="tokenizer", local_files_only=local_files_only
1635
+ )
1636
+ except Exception:
1637
+ raise ValueError(
1638
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'stabilityai/stable-diffusion-2'."
1639
+ )
1640
+
1641
+ if stable_unclip is None:
1642
+ if controlnet:
1643
+ pipe = pipeline_class(
1644
+ vae=vae,
1645
+ text_encoder=text_model,
1646
+ tokenizer=tokenizer,
1647
+ unet=unet,
1648
+ scheduler=scheduler,
1649
+ controlnet=controlnet,
1650
+ safety_checker=None,
1651
+ feature_extractor=None,
1652
+ )
1653
+ if hasattr(pipe, "requires_safety_checker"):
1654
+ pipe.requires_safety_checker = False
1655
+
1656
+ elif pipeline_class == StableDiffusionUpscalePipeline:
1657
+ scheduler = DDIMScheduler.from_pretrained(
1658
+ "stabilityai/stable-diffusion-x4-upscaler", subfolder="scheduler"
1659
+ )
1660
+ low_res_scheduler = DDPMScheduler.from_pretrained(
1661
+ "stabilityai/stable-diffusion-x4-upscaler", subfolder="low_res_scheduler"
1662
+ )
1663
+
1664
+ pipe = pipeline_class(
1665
+ vae=vae,
1666
+ text_encoder=text_model,
1667
+ tokenizer=tokenizer,
1668
+ unet=unet,
1669
+ scheduler=scheduler,
1670
+ low_res_scheduler=low_res_scheduler,
1671
+ safety_checker=None,
1672
+ feature_extractor=None,
1673
+ )
1674
+
1675
+ else:
1676
+ pipe = pipeline_class(
1677
+ vae=vae,
1678
+ text_encoder=text_model,
1679
+ tokenizer=tokenizer,
1680
+ unet=unet,
1681
+ scheduler=scheduler,
1682
+ safety_checker=None,
1683
+ feature_extractor=None,
1684
+ )
1685
+ if hasattr(pipe, "requires_safety_checker"):
1686
+ pipe.requires_safety_checker = False
1687
+
1688
+ else:
1689
+ image_normalizer, image_noising_scheduler = stable_unclip_image_noising_components(
1690
+ original_config, clip_stats_path=clip_stats_path, device=device
1691
+ )
1692
+
1693
+ if stable_unclip == "img2img":
1694
+ feature_extractor, image_encoder = stable_unclip_image_encoder(original_config)
1695
+
1696
+ pipe = StableUnCLIPImg2ImgPipeline(
1697
+ # image encoding components
1698
+ feature_extractor=feature_extractor,
1699
+ image_encoder=image_encoder,
1700
+ # image noising components
1701
+ image_normalizer=image_normalizer,
1702
+ image_noising_scheduler=image_noising_scheduler,
1703
+ # regular denoising components
1704
+ tokenizer=tokenizer,
1705
+ text_encoder=text_model,
1706
+ unet=unet,
1707
+ scheduler=scheduler,
1708
+ # vae
1709
+ vae=vae,
1710
+ )
1711
+ elif stable_unclip == "txt2img":
1712
+ if stable_unclip_prior is None or stable_unclip_prior == "karlo":
1713
+ karlo_model = "kakaobrain/karlo-v1-alpha"
1714
+ prior = PriorTransformer.from_pretrained(
1715
+ karlo_model, subfolder="prior", local_files_only=local_files_only
1716
+ )
1717
+
1718
+ try:
1719
+ prior_tokenizer = CLIPTokenizer.from_pretrained(
1720
+ "openai/clip-vit-large-patch14", local_files_only=local_files_only
1721
+ )
1722
+ except Exception:
1723
+ raise ValueError(
1724
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1725
+ )
1726
+ prior_text_model = CLIPTextModelWithProjection.from_pretrained(
1727
+ "openai/clip-vit-large-patch14", local_files_only=local_files_only
1728
+ )
1729
+
1730
+ prior_scheduler = UnCLIPScheduler.from_pretrained(
1731
+ karlo_model, subfolder="prior_scheduler", local_files_only=local_files_only
1732
+ )
1733
+ prior_scheduler = DDPMScheduler.from_config(prior_scheduler.config)
1734
+ else:
1735
+ raise NotImplementedError(f"unknown prior for stable unclip model: {stable_unclip_prior}")
1736
+
1737
+ pipe = StableUnCLIPPipeline(
1738
+ # prior components
1739
+ prior_tokenizer=prior_tokenizer,
1740
+ prior_text_encoder=prior_text_model,
1741
+ prior=prior,
1742
+ prior_scheduler=prior_scheduler,
1743
+ # image noising components
1744
+ image_normalizer=image_normalizer,
1745
+ image_noising_scheduler=image_noising_scheduler,
1746
+ # regular denoising components
1747
+ tokenizer=tokenizer,
1748
+ text_encoder=text_model,
1749
+ unet=unet,
1750
+ scheduler=scheduler,
1751
+ # vae
1752
+ vae=vae,
1753
+ )
1754
+ else:
1755
+ raise NotImplementedError(f"unknown `stable_unclip` type: {stable_unclip}")
1756
+ elif model_type == "PaintByExample":
1757
+ vision_model = convert_paint_by_example_checkpoint(checkpoint)
1758
+ try:
1759
+ tokenizer = CLIPTokenizer.from_pretrained(
1760
+ "openai/clip-vit-large-patch14", local_files_only=local_files_only
1761
+ )
1762
+ except Exception:
1763
+ raise ValueError(
1764
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1765
+ )
1766
+ try:
1767
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
1768
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
1769
+ )
1770
+ except Exception:
1771
+ raise ValueError(
1772
+ f"With local_files_only set to {local_files_only}, you must first locally save the feature_extractor in the following path: 'CompVis/stable-diffusion-safety-checker'."
1773
+ )
1774
+ pipe = PaintByExamplePipeline(
1775
+ vae=vae,
1776
+ image_encoder=vision_model,
1777
+ unet=unet,
1778
+ scheduler=scheduler,
1779
+ safety_checker=None,
1780
+ feature_extractor=feature_extractor,
1781
+ )
1782
+ elif model_type == "FrozenCLIPEmbedder":
1783
+ text_model = convert_ldm_clip_checkpoint(
1784
+ checkpoint, local_files_only=local_files_only, text_encoder=text_encoder
1785
+ )
1786
+ try:
1787
+ tokenizer = (
1788
+ CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14", local_files_only=local_files_only)
1789
+ if tokenizer is None
1790
+ else tokenizer
1791
+ )
1792
+ except Exception:
1793
+ raise ValueError(
1794
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1795
+ )
1796
+
1797
+ if load_safety_checker:
1798
+ safety_checker = StableDiffusionSafetyChecker.from_pretrained(
1799
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
1800
+ )
1801
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
1802
+ "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
1803
+ )
1804
+ else:
1805
+ safety_checker = None
1806
+ feature_extractor = None
1807
+
1808
+ if controlnet:
1809
+ pipe = pipeline_class(
1810
+ vae=vae,
1811
+ text_encoder=text_model,
1812
+ tokenizer=tokenizer,
1813
+ unet=unet,
1814
+ controlnet=controlnet,
1815
+ scheduler=scheduler,
1816
+ safety_checker=safety_checker,
1817
+ feature_extractor=feature_extractor,
1818
+ )
1819
+ else:
1820
+ pipe = pipeline_class(
1821
+ vae=vae,
1822
+ text_encoder=text_model,
1823
+ tokenizer=tokenizer,
1824
+ unet=unet,
1825
+ scheduler=scheduler,
1826
+ safety_checker=safety_checker,
1827
+ feature_extractor=feature_extractor,
1828
+ )
1829
+ elif model_type in ["SDXL", "SDXL-Refiner"]:
1830
+ is_refiner = model_type == "SDXL-Refiner"
1831
+
1832
+ if (is_refiner is False) and (tokenizer is None):
1833
+ try:
1834
+ tokenizer = CLIPTokenizer.from_pretrained(
1835
+ "openai/clip-vit-large-patch14", local_files_only=local_files_only
1836
+ )
1837
+ except Exception:
1838
+ raise ValueError(
1839
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1840
+ )
1841
+
1842
+ if (is_refiner is False) and (text_encoder is None):
1843
+ text_encoder = convert_ldm_clip_checkpoint(checkpoint, local_files_only=local_files_only)
1844
+
1845
+ if tokenizer_2 is None:
1846
+ try:
1847
+ tokenizer_2 = CLIPTokenizer.from_pretrained(
1848
+ "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", pad_token="!", local_files_only=local_files_only
1849
+ )
1850
+ except Exception:
1851
+ raise ValueError(
1852
+ f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: 'laion/CLIP-ViT-bigG-14-laion2B-39B-b160k' with `pad_token` set to '!'."
1853
+ )
1854
+
1855
+ if text_encoder_2 is None:
1856
+ config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1857
+ config_kwargs = {"projection_dim": 1280}
1858
+ prefix = "conditioner.embedders.0.model." if is_refiner else "conditioner.embedders.1.model."
1859
+
1860
+ text_encoder_2 = convert_open_clip_checkpoint(
1861
+ checkpoint,
1862
+ config_name,
1863
+ prefix=prefix,
1864
+ has_projection=True,
1865
+ local_files_only=local_files_only,
1866
+ **config_kwargs,
1867
+ )
1868
+
1869
+ if is_accelerate_available(): # SBM Now move model to cpu.
1870
+ for param_name, param in converted_unet_checkpoint.items():
1871
+ set_module_tensor_to_device(unet, param_name, "cpu", value=param)
1872
+
1873
+ if controlnet:
1874
+ pipe = pipeline_class(
1875
+ vae=vae,
1876
+ text_encoder=text_encoder,
1877
+ tokenizer=tokenizer,
1878
+ text_encoder_2=text_encoder_2,
1879
+ tokenizer_2=tokenizer_2,
1880
+ unet=unet,
1881
+ controlnet=controlnet,
1882
+ scheduler=scheduler,
1883
+ force_zeros_for_empty_prompt=True,
1884
+ )
1885
+ elif adapter:
1886
+ pipe = pipeline_class(
1887
+ vae=vae,
1888
+ text_encoder=text_encoder,
1889
+ tokenizer=tokenizer,
1890
+ text_encoder_2=text_encoder_2,
1891
+ tokenizer_2=tokenizer_2,
1892
+ unet=unet,
1893
+ adapter=adapter,
1894
+ scheduler=scheduler,
1895
+ force_zeros_for_empty_prompt=True,
1896
+ )
1897
+
1898
+ else:
1899
+ pipeline_kwargs = {
1900
+ "vae": vae,
1901
+ "text_encoder": text_encoder,
1902
+ "tokenizer": tokenizer,
1903
+ "text_encoder_2": text_encoder_2,
1904
+ "tokenizer_2": tokenizer_2,
1905
+ "unet": unet,
1906
+ "scheduler": scheduler,
1907
+ }
1908
+
1909
+ if (pipeline_class == StableDiffusionXLImg2ImgPipeline) or (
1910
+ pipeline_class == StableDiffusionXLInpaintPipeline
1911
+ ):
1912
+ pipeline_kwargs.update({"requires_aesthetics_score": is_refiner})
1913
+
1914
+ if is_refiner:
1915
+ pipeline_kwargs.update({"force_zeros_for_empty_prompt": False})
1916
+
1917
+ pipe = pipeline_class(**pipeline_kwargs)
1918
+ else:
1919
+ text_config = create_ldm_bert_config(original_config)
1920
+ text_model = convert_ldm_bert_checkpoint(checkpoint, text_config)
1921
+ tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased", local_files_only=local_files_only)
1922
+ pipe = LDMTextToImagePipeline(vqvae=vae, bert=text_model, tokenizer=tokenizer, unet=unet, scheduler=scheduler)
1923
+
1924
+ return pipe
1925
+
1926
+
1927
+ def download_controlnet_from_original_ckpt(
1928
+ checkpoint_path: str,
1929
+ original_config_file: str,
1930
+ image_size: int = 512,
1931
+ extract_ema: bool = False,
1932
+ num_in_channels: Optional[int] = None,
1933
+ upcast_attention: Optional[bool] = None,
1934
+ device: str = None,
1935
+ from_safetensors: bool = False,
1936
+ use_linear_projection: Optional[bool] = None,
1937
+ cross_attention_dim: Optional[bool] = None,
1938
+ ) -> DiffusionPipeline:
1939
+ if from_safetensors:
1940
+ from safetensors import safe_open
1941
+
1942
+ checkpoint = {}
1943
+ with safe_open(checkpoint_path, framework="pt", device="cpu") as f:
1944
+ for key in f.keys():
1945
+ checkpoint[key] = f.get_tensor(key)
1946
+ else:
1947
+ if device is None:
1948
+ device = "cuda" if torch.cuda.is_available() else "cpu"
1949
+ checkpoint = torch.load(checkpoint_path, map_location=device)
1950
+ else:
1951
+ checkpoint = torch.load(checkpoint_path, map_location=device)
1952
+
1953
+ # NOTE: this while loop isn't great but this controlnet checkpoint has one additional
1954
+ # "state_dict" key https://huggingface.co/thibaud/controlnet-canny-sd21
1955
+ while "state_dict" in checkpoint:
1956
+ checkpoint = checkpoint["state_dict"]
1957
+
1958
+ original_config = yaml.safe_load(original_config_file)
1959
+
1960
+ if num_in_channels is not None:
1961
+ original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels
1962
+
1963
+ if "control_stage_config" not in original_config["model"]["params"]:
1964
+ raise ValueError("`control_stage_config` not present in original config")
1965
+
1966
+ controlnet = convert_controlnet_checkpoint(
1967
+ checkpoint,
1968
+ original_config,
1969
+ checkpoint_path,
1970
+ image_size,
1971
+ upcast_attention,
1972
+ extract_ema,
1973
+ use_linear_projection=use_linear_projection,
1974
+ cross_attention_dim=cross_attention_dim,
1975
+ )
1976
+
1977
+ return controlnet
1978
+
1979
+
1980
+ def download_promptdiffusion_from_original_ckpt(
1981
+ checkpoint_path: str,
1982
+ original_config_file: str,
1983
+ image_size: int = 512,
1984
+ extract_ema: bool = False,
1985
+ num_in_channels: Optional[int] = None,
1986
+ upcast_attention: Optional[bool] = None,
1987
+ device: str = None,
1988
+ from_safetensors: bool = False,
1989
+ use_linear_projection: Optional[bool] = None,
1990
+ cross_attention_dim: Optional[bool] = None,
1991
+ ) -> DiffusionPipeline:
1992
+ if from_safetensors:
1993
+ from safetensors import safe_open
1994
+
1995
+ checkpoint = {}
1996
+ with safe_open(checkpoint_path, framework="pt", device="cpu") as f:
1997
+ for key in f.keys():
1998
+ checkpoint[key] = f.get_tensor(key)
1999
+ else:
2000
+ if device is None:
2001
+ device = "cuda" if torch.cuda.is_available() else "cpu"
2002
+ checkpoint = torch.load(checkpoint_path, map_location=device)
2003
+ else:
2004
+ checkpoint = torch.load(checkpoint_path, map_location=device)
2005
+
2006
+ # NOTE: this while loop isn't great but this controlnet checkpoint has one additional
2007
+ # "state_dict" key https://huggingface.co/thibaud/controlnet-canny-sd21
2008
+ while "state_dict" in checkpoint:
2009
+ checkpoint = checkpoint["state_dict"]
2010
+
2011
+ original_config = yaml.safe_load(open(original_config_file))
2012
+
2013
+ if num_in_channels is not None:
2014
+ original_config["model"]["params"]["unet_config"]["params"]["in_channels"] = num_in_channels
2015
+ if "control_stage_config" not in original_config["model"]["params"]:
2016
+ raise ValueError("`control_stage_config` not present in original config")
2017
+
2018
+ controlnet = convert_promptdiffusion_checkpoint(
2019
+ checkpoint,
2020
+ original_config,
2021
+ checkpoint_path,
2022
+ image_size,
2023
+ upcast_attention,
2024
+ extract_ema,
2025
+ use_linear_projection=use_linear_projection,
2026
+ cross_attention_dim=cross_attention_dim,
2027
+ )
2028
+
2029
+ return controlnet
2030
+
2031
+
2032
+ if __name__ == "__main__":
2033
+ parser = argparse.ArgumentParser()
2034
+
2035
+ parser.add_argument(
2036
+ "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
2037
+ )
2038
+ parser.add_argument(
2039
+ "--original_config_file",
2040
+ type=str,
2041
+ required=True,
2042
+ help="The YAML config file corresponding to the original architecture.",
2043
+ )
2044
+ parser.add_argument(
2045
+ "--num_in_channels",
2046
+ default=None,
2047
+ type=int,
2048
+ help="The number of input channels. If `None` number of input channels will be automatically inferred.",
2049
+ )
2050
+ parser.add_argument(
2051
+ "--image_size",
2052
+ default=512,
2053
+ type=int,
2054
+ help=(
2055
+ "The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Diffusion v2"
2056
+ " Base. Use 768 for Stable Diffusion v2."
2057
+ ),
2058
+ )
2059
+ parser.add_argument(
2060
+ "--extract_ema",
2061
+ action="store_true",
2062
+ help=(
2063
+ "Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"
2064
+ " or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"
2065
+ " higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."
2066
+ ),
2067
+ )
2068
+ parser.add_argument(
2069
+ "--upcast_attention",
2070
+ action="store_true",
2071
+ help=(
2072
+ "Whether the attention computation should always be upcasted. This is necessary when running stable"
2073
+ " diffusion 2.1."
2074
+ ),
2075
+ )
2076
+ parser.add_argument(
2077
+ "--from_safetensors",
2078
+ action="store_true",
2079
+ help="If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.",
2080
+ )
2081
+ parser.add_argument(
2082
+ "--to_safetensors",
2083
+ action="store_true",
2084
+ help="Whether to store pipeline in safetensors format or not.",
2085
+ )
2086
+ parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
2087
+ parser.add_argument("--device", type=str, help="Device to use (e.g. cpu, cuda:0, cuda:1, etc.)")
2088
+
2089
+ # small workaround to get argparser to parse a boolean input as either true _or_ false
2090
+ def parse_bool(string):
2091
+ if string == "True":
2092
+ return True
2093
+ elif string == "False":
2094
+ return False
2095
+ else:
2096
+ raise ValueError(f"could not parse string as bool {string}")
2097
+
2098
+ parser.add_argument(
2099
+ "--use_linear_projection", help="Override for use linear projection", required=False, type=parse_bool
2100
+ )
2101
+
2102
+ parser.add_argument("--cross_attention_dim", help="Override for cross attention_dim", required=False, type=int)
2103
+
2104
+ args = parser.parse_args()
2105
+
2106
+ controlnet = download_promptdiffusion_from_original_ckpt(
2107
+ checkpoint_path=args.checkpoint_path,
2108
+ original_config_file=args.original_config_file,
2109
+ image_size=args.image_size,
2110
+ extract_ema=args.extract_ema,
2111
+ num_in_channels=args.num_in_channels,
2112
+ upcast_attention=args.upcast_attention,
2113
+ from_safetensors=args.from_safetensors,
2114
+ device=args.device,
2115
+ use_linear_projection=args.use_linear_projection,
2116
+ cross_attention_dim=args.cross_attention_dim,
2117
+ )
2118
+
2119
+ controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/pipeline_prompt_diffusion.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ # Based on [In-Context Learning Unlocked for Diffusion Models](https://huggingface.co/papers/2305.01115)
16
+ # Authors: Zhendong Wang, Yifan Jiang, Yadong Lu, Yelong Shen, Pengcheng He, Weizhu Chen, Zhangyang Wang, Mingyuan Zhou
17
+ # Project Page: https://zhendong-wang.github.io/prompt-diffusion.github.io/
18
+ # Code: https://github.com/Zhendong-Wang/Prompt-Diffusion
19
+ #
20
+ # Adapted to Diffusers by [iczaw](https://github.com/iczaw).
21
+ import inspect
22
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import PIL.Image
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
29
+
30
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
31
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
32
+ from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
33
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
34
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
35
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
36
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
37
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
38
+ from diffusers.schedulers import KarrasDiffusionSchedulers
39
+ from diffusers.utils import (
40
+ USE_PEFT_BACKEND,
41
+ deprecate,
42
+ logging,
43
+ replace_example_docstring,
44
+ scale_lora_layers,
45
+ unscale_lora_layers,
46
+ )
47
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
48
+
49
+
50
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
51
+
52
+
53
+ EXAMPLE_DOC_STRING = """
54
+ Examples:
55
+ ```py
56
+ >>> # !pip install opencv-python transformers accelerate
57
+ >>> from promptdiffusioncontrolnet import PromptDiffusionControlNetModel
58
+ >>> from diffusers.utils import load_image
59
+ >>> import torch
60
+
61
+ >>> from diffusers.pipelines.pipeline_utils import DiffusionPipeline
62
+ >>> from diffusers import UniPCMultistepScheduler
63
+ >>> from PIL import ImageOps
64
+
65
+ >>> # download an image
66
+ >>> image_a = ImageOps.invert(load_image(
67
+ ... "https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/house_line.png?raw=true"
68
+ ... ))
69
+
70
+ >>> # download an image
71
+ >>> image_b = load_image(
72
+ ... "https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/house.png?raw=true"
73
+ ... )
74
+
75
+ >>> # download an image
76
+ >>> query = ImageOps.invert(load_image(
77
+ ... "https://github.com/Zhendong-Wang/Prompt-Diffusion/blob/main/images_to_try/new_01.png?raw=true"
78
+ ... ))
79
+
80
+ >>> # load prompt diffusion control net and prompt diffusion
81
+ >>> controlnet = PromptDiffusionControlNetModel.from_pretrained("path-to-converted-promptdiffusion-controlnet", torch_dtype=torch.float16)
82
+ >>> pipe = DiffusionPipeline.from_pretrained(model_id, controlnet=controlnet, torch_dtype=torch.float16, variant="fp16", custom_pipeline="pipeline_prompt_diffusion")
83
+
84
+ >>> # speed up diffusion process with faster scheduler and memory optimization
85
+ >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
86
+ >>> # remove following line if xformers is not installed
87
+ >>> pipe.enable_xformers_memory_efficient_attention()
88
+
89
+ >>> pipe.enable_model_cpu_offload()
90
+
91
+ >>> # generate image
92
+ >>> generator = torch.manual_seed(0)
93
+ >>> image = pipe(
94
+ ... "a tortoise", num_inference_steps=20, generator=generator, image_pair=[image_a,image_b], image=query
95
+ ... ).images[0]
96
+ ```
97
+ """
98
+
99
+
100
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
101
+ def retrieve_timesteps(
102
+ scheduler,
103
+ num_inference_steps: Optional[int] = None,
104
+ device: Optional[Union[str, torch.device]] = None,
105
+ timesteps: Optional[List[int]] = None,
106
+ **kwargs,
107
+ ):
108
+ """
109
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
110
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
111
+
112
+ Args:
113
+ scheduler (`SchedulerMixin`):
114
+ The scheduler to get timesteps from.
115
+ num_inference_steps (`int`):
116
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
117
+ `timesteps` must be `None`.
118
+ device (`str` or `torch.device`, *optional*):
119
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
120
+ timesteps (`List[int]`, *optional*):
121
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
122
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
123
+ must be `None`.
124
+
125
+ Returns:
126
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
127
+ second element is the number of inference steps.
128
+ """
129
+ if timesteps is not None:
130
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
131
+ if not accepts_timesteps:
132
+ raise ValueError(
133
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
134
+ f" timestep schedules. Please check whether you are using the correct scheduler."
135
+ )
136
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
137
+ timesteps = scheduler.timesteps
138
+ num_inference_steps = len(timesteps)
139
+ else:
140
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
141
+ timesteps = scheduler.timesteps
142
+ return timesteps, num_inference_steps
143
+
144
+
145
+ class PromptDiffusionPipeline(
146
+ DiffusionPipeline, TextualInversionLoaderMixin, StableDiffusionLoraLoaderMixin, FromSingleFileMixin
147
+ ):
148
+ r"""
149
+ Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
150
+
151
+ This pipeline also adds experimental support for [Prompt Diffusion](https://huggingface.co/papers/2305.01115).
152
+
153
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
154
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
155
+
156
+ The pipeline also inherits the following loading methods:
157
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
158
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
159
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
160
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
161
+
162
+ Args:
163
+ vae ([`AutoencoderKL`]):
164
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
165
+ text_encoder ([`~transformers.CLIPTextModel`]):
166
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
167
+ tokenizer ([`~transformers.CLIPTokenizer`]):
168
+ A `CLIPTokenizer` to tokenize text.
169
+ unet ([`UNet2DConditionModel`]):
170
+ A `UNet2DConditionModel` to denoise the encoded image latents.
171
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
172
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
173
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
174
+ additional conditioning.
175
+ scheduler ([`SchedulerMixin`]):
176
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
177
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
178
+ safety_checker ([`StableDiffusionSafetyChecker`]):
179
+ Classification module that estimates whether generated images could be considered offensive or harmful.
180
+ Please refer to the [model card](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) for more details
181
+ about a model's potential harms.
182
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
183
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
184
+ """
185
+
186
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
187
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
188
+ _exclude_from_cpu_offload = ["safety_checker"]
189
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
190
+
191
+ def __init__(
192
+ self,
193
+ vae: AutoencoderKL,
194
+ text_encoder: CLIPTextModel,
195
+ tokenizer: CLIPTokenizer,
196
+ unet: UNet2DConditionModel,
197
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
198
+ scheduler: KarrasDiffusionSchedulers,
199
+ safety_checker: StableDiffusionSafetyChecker,
200
+ feature_extractor: CLIPImageProcessor,
201
+ image_encoder: CLIPVisionModelWithProjection = None,
202
+ requires_safety_checker: bool = True,
203
+ ):
204
+ super().__init__()
205
+
206
+ if safety_checker is None and requires_safety_checker:
207
+ logger.warning(
208
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
209
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
210
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
211
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
212
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
213
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
214
+ )
215
+
216
+ if safety_checker is not None and feature_extractor is None:
217
+ raise ValueError(
218
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
219
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
220
+ )
221
+
222
+ if isinstance(controlnet, (list, tuple)):
223
+ controlnet = MultiControlNetModel(controlnet)
224
+
225
+ self.register_modules(
226
+ vae=vae,
227
+ text_encoder=text_encoder,
228
+ tokenizer=tokenizer,
229
+ unet=unet,
230
+ controlnet=controlnet,
231
+ scheduler=scheduler,
232
+ safety_checker=safety_checker,
233
+ feature_extractor=feature_extractor,
234
+ image_encoder=image_encoder,
235
+ )
236
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
237
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
238
+ self.control_image_processor = VaeImageProcessor(
239
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
240
+ )
241
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
242
+
243
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
244
+ def enable_vae_slicing(self):
245
+ r"""
246
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
247
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
248
+ """
249
+ self.vae.enable_slicing()
250
+
251
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
252
+ def disable_vae_slicing(self):
253
+ r"""
254
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
255
+ computing decoding in one step.
256
+ """
257
+ self.vae.disable_slicing()
258
+
259
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
260
+ def enable_vae_tiling(self):
261
+ r"""
262
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
263
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
264
+ processing larger images.
265
+ """
266
+ depr_message = f"Calling `enable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.enable_tiling()`."
267
+ deprecate(
268
+ "enable_vae_tiling",
269
+ "0.40.0",
270
+ depr_message,
271
+ )
272
+ self.vae.enable_tiling()
273
+
274
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
275
+ def disable_vae_tiling(self):
276
+ r"""
277
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
278
+ computing decoding in one step.
279
+ """
280
+ depr_message = f"Calling `disable_vae_tiling()` on a `{self.__class__.__name__}` is deprecated and this method will be removed in a future version. Please use `pipe.vae.disable_tiling()`."
281
+ deprecate(
282
+ "disable_vae_tiling",
283
+ "0.40.0",
284
+ depr_message,
285
+ )
286
+ self.vae.disable_tiling()
287
+
288
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
289
+ def _encode_prompt(
290
+ self,
291
+ prompt,
292
+ device,
293
+ num_images_per_prompt,
294
+ do_classifier_free_guidance,
295
+ negative_prompt=None,
296
+ prompt_embeds: Optional[torch.Tensor] = None,
297
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
298
+ lora_scale: Optional[float] = None,
299
+ **kwargs,
300
+ ):
301
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
302
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
303
+
304
+ prompt_embeds_tuple = self.encode_prompt(
305
+ prompt=prompt,
306
+ device=device,
307
+ num_images_per_prompt=num_images_per_prompt,
308
+ do_classifier_free_guidance=do_classifier_free_guidance,
309
+ negative_prompt=negative_prompt,
310
+ prompt_embeds=prompt_embeds,
311
+ negative_prompt_embeds=negative_prompt_embeds,
312
+ lora_scale=lora_scale,
313
+ **kwargs,
314
+ )
315
+
316
+ # concatenate for backwards comp
317
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
318
+
319
+ return prompt_embeds
320
+
321
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
322
+ def encode_prompt(
323
+ self,
324
+ prompt,
325
+ device,
326
+ num_images_per_prompt,
327
+ do_classifier_free_guidance,
328
+ negative_prompt=None,
329
+ prompt_embeds: Optional[torch.Tensor] = None,
330
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
331
+ lora_scale: Optional[float] = None,
332
+ clip_skip: Optional[int] = None,
333
+ ):
334
+ r"""
335
+ Encodes the prompt into text encoder hidden states.
336
+
337
+ Args:
338
+ prompt (`str` or `List[str]`, *optional*):
339
+ prompt to be encoded
340
+ device: (`torch.device`):
341
+ torch device
342
+ num_images_per_prompt (`int`):
343
+ number of images that should be generated per prompt
344
+ do_classifier_free_guidance (`bool`):
345
+ whether to use classifier free guidance or not
346
+ negative_prompt (`str` or `List[str]`, *optional*):
347
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
348
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
349
+ less than `1`).
350
+ prompt_embeds (`torch.Tensor`, *optional*):
351
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
352
+ provided, text embeddings will be generated from `prompt` input argument.
353
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
354
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
355
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
356
+ argument.
357
+ lora_scale (`float`, *optional*):
358
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
359
+ clip_skip (`int`, *optional*):
360
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
361
+ the output of the pre-final layer will be used for computing the prompt embeddings.
362
+ """
363
+ # set lora scale so that monkey patched LoRA
364
+ # function of text encoder can correctly access it
365
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
366
+ self._lora_scale = lora_scale
367
+
368
+ # dynamically adjust the LoRA scale
369
+ if not USE_PEFT_BACKEND:
370
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
371
+ else:
372
+ scale_lora_layers(self.text_encoder, lora_scale)
373
+
374
+ if prompt is not None and isinstance(prompt, str):
375
+ batch_size = 1
376
+ elif prompt is not None and isinstance(prompt, list):
377
+ batch_size = len(prompt)
378
+ else:
379
+ batch_size = prompt_embeds.shape[0]
380
+
381
+ if prompt_embeds is None:
382
+ # textual inversion: procecss multi-vector tokens if necessary
383
+ if isinstance(self, TextualInversionLoaderMixin):
384
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
385
+
386
+ text_inputs = self.tokenizer(
387
+ prompt,
388
+ padding="max_length",
389
+ max_length=self.tokenizer.model_max_length,
390
+ truncation=True,
391
+ return_tensors="pt",
392
+ )
393
+ text_input_ids = text_inputs.input_ids
394
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
395
+
396
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
397
+ text_input_ids, untruncated_ids
398
+ ):
399
+ removed_text = self.tokenizer.batch_decode(
400
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
401
+ )
402
+ logger.warning(
403
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
404
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
405
+ )
406
+
407
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
408
+ attention_mask = text_inputs.attention_mask.to(device)
409
+ else:
410
+ attention_mask = None
411
+
412
+ if clip_skip is None:
413
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
414
+ prompt_embeds = prompt_embeds[0]
415
+ else:
416
+ prompt_embeds = self.text_encoder(
417
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
418
+ )
419
+ # Access the `hidden_states` first, that contains a tuple of
420
+ # all the hidden states from the encoder layers. Then index into
421
+ # the tuple to access the hidden states from the desired layer.
422
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
423
+ # We also need to apply the final LayerNorm here to not mess with the
424
+ # representations. The `last_hidden_states` that we typically use for
425
+ # obtaining the final prompt representations passes through the LayerNorm
426
+ # layer.
427
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
428
+
429
+ if self.text_encoder is not None:
430
+ prompt_embeds_dtype = self.text_encoder.dtype
431
+ elif self.unet is not None:
432
+ prompt_embeds_dtype = self.unet.dtype
433
+ else:
434
+ prompt_embeds_dtype = prompt_embeds.dtype
435
+
436
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
437
+
438
+ bs_embed, seq_len, _ = prompt_embeds.shape
439
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
440
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
441
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
442
+
443
+ # get unconditional embeddings for classifier free guidance
444
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
445
+ uncond_tokens: List[str]
446
+ if negative_prompt is None:
447
+ uncond_tokens = [""] * batch_size
448
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
449
+ raise TypeError(
450
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
451
+ f" {type(prompt)}."
452
+ )
453
+ elif isinstance(negative_prompt, str):
454
+ uncond_tokens = [negative_prompt]
455
+ elif batch_size != len(negative_prompt):
456
+ raise ValueError(
457
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
458
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
459
+ " the batch size of `prompt`."
460
+ )
461
+ else:
462
+ uncond_tokens = negative_prompt
463
+
464
+ # textual inversion: procecss multi-vector tokens if necessary
465
+ if isinstance(self, TextualInversionLoaderMixin):
466
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
467
+
468
+ max_length = prompt_embeds.shape[1]
469
+ uncond_input = self.tokenizer(
470
+ uncond_tokens,
471
+ padding="max_length",
472
+ max_length=max_length,
473
+ truncation=True,
474
+ return_tensors="pt",
475
+ )
476
+
477
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
478
+ attention_mask = uncond_input.attention_mask.to(device)
479
+ else:
480
+ attention_mask = None
481
+
482
+ negative_prompt_embeds = self.text_encoder(
483
+ uncond_input.input_ids.to(device),
484
+ attention_mask=attention_mask,
485
+ )
486
+ negative_prompt_embeds = negative_prompt_embeds[0]
487
+
488
+ if do_classifier_free_guidance:
489
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
490
+ seq_len = negative_prompt_embeds.shape[1]
491
+
492
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
493
+
494
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
495
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
496
+
497
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
498
+ # Retrieve the original scale by scaling back the LoRA layers
499
+ unscale_lora_layers(self.text_encoder, lora_scale)
500
+
501
+ return prompt_embeds, negative_prompt_embeds
502
+
503
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
504
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
505
+ dtype = next(self.image_encoder.parameters()).dtype
506
+
507
+ if not isinstance(image, torch.Tensor):
508
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
509
+
510
+ image = image.to(device=device, dtype=dtype)
511
+ if output_hidden_states:
512
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
513
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
514
+ uncond_image_enc_hidden_states = self.image_encoder(
515
+ torch.zeros_like(image), output_hidden_states=True
516
+ ).hidden_states[-2]
517
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
518
+ num_images_per_prompt, dim=0
519
+ )
520
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
521
+ else:
522
+ image_embeds = self.image_encoder(image).image_embeds
523
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
524
+ uncond_image_embeds = torch.zeros_like(image_embeds)
525
+
526
+ return image_embeds, uncond_image_embeds
527
+
528
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
529
+ def run_safety_checker(self, image, device, dtype):
530
+ if self.safety_checker is None:
531
+ has_nsfw_concept = None
532
+ else:
533
+ if torch.is_tensor(image):
534
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
535
+ else:
536
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
537
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
538
+ image, has_nsfw_concept = self.safety_checker(
539
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
540
+ )
541
+ return image, has_nsfw_concept
542
+
543
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
544
+ def decode_latents(self, latents):
545
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
546
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
547
+
548
+ latents = 1 / self.vae.config.scaling_factor * latents
549
+ image = self.vae.decode(latents, return_dict=False)[0]
550
+ image = (image / 2 + 0.5).clamp(0, 1)
551
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
552
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
553
+ return image
554
+
555
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
556
+ def prepare_extra_step_kwargs(self, generator, eta):
557
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
558
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
559
+ # eta corresponds to η in DDIM paper: https://huggingface.co/papers/2010.02502
560
+ # and should be between [0, 1]
561
+
562
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
563
+ extra_step_kwargs = {}
564
+ if accepts_eta:
565
+ extra_step_kwargs["eta"] = eta
566
+
567
+ # check if the scheduler accepts generator
568
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
569
+ if accepts_generator:
570
+ extra_step_kwargs["generator"] = generator
571
+ return extra_step_kwargs
572
+
573
+ def check_inputs(
574
+ self,
575
+ prompt,
576
+ image,
577
+ image_pair,
578
+ callback_steps,
579
+ negative_prompt=None,
580
+ prompt_embeds=None,
581
+ negative_prompt_embeds=None,
582
+ controlnet_conditioning_scale=1.0,
583
+ control_guidance_start=0.0,
584
+ control_guidance_end=1.0,
585
+ callback_on_step_end_tensor_inputs=None,
586
+ ):
587
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
588
+ raise ValueError(
589
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
590
+ f" {type(callback_steps)}."
591
+ )
592
+
593
+ if callback_on_step_end_tensor_inputs is not None and not all(
594
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
595
+ ):
596
+ raise ValueError(
597
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
598
+ )
599
+
600
+ if prompt is not None and prompt_embeds is not None:
601
+ raise ValueError(
602
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
603
+ " only forward one of the two."
604
+ )
605
+ elif prompt is None and prompt_embeds is None:
606
+ raise ValueError(
607
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
608
+ )
609
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
610
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
611
+
612
+ if negative_prompt is not None and negative_prompt_embeds is not None:
613
+ raise ValueError(
614
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
615
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
616
+ )
617
+
618
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
619
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
620
+ raise ValueError(
621
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
622
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
623
+ f" {negative_prompt_embeds.shape}."
624
+ )
625
+
626
+ # `prompt` needs more sophisticated handling when there are multiple
627
+ # conditionings.
628
+ if isinstance(self.controlnet, MultiControlNetModel):
629
+ if isinstance(prompt, list):
630
+ logger.warning(
631
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
632
+ " prompts. The conditionings will be fixed across the prompts."
633
+ )
634
+
635
+ # Check `image`
636
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
637
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
638
+ )
639
+ if (
640
+ isinstance(self.controlnet, ControlNetModel)
641
+ or is_compiled
642
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
643
+ ):
644
+ self.check_image(image, prompt, prompt_embeds)
645
+ elif (
646
+ isinstance(self.controlnet, MultiControlNetModel)
647
+ or is_compiled
648
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
649
+ ):
650
+ if not isinstance(image, list):
651
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
652
+
653
+ # When `image` is a nested list:
654
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
655
+ elif any(isinstance(i, list) for i in image):
656
+ raise ValueError("A single batch of multiple conditionings is not supported at the moment.")
657
+ elif len(image) != len(self.controlnet.nets):
658
+ raise ValueError(
659
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
660
+ )
661
+
662
+ for image_ in image:
663
+ self.check_image(image_, prompt, prompt_embeds)
664
+ else:
665
+ assert False
666
+
667
+ # Check `image_pair`
668
+ if len(image_pair) == 2:
669
+ for image in image_pair:
670
+ if (
671
+ isinstance(self.controlnet, ControlNetModel)
672
+ or is_compiled
673
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
674
+ ):
675
+ self.check_image(image, prompt, prompt_embeds)
676
+ else:
677
+ raise ValueError(
678
+ f"You have passed a list of images of length {len(image_pair)}.Make sure the list size equals to two."
679
+ )
680
+
681
+ # Check `controlnet_conditioning_scale`
682
+ if (
683
+ isinstance(self.controlnet, ControlNetModel)
684
+ or is_compiled
685
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
686
+ ):
687
+ if not isinstance(controlnet_conditioning_scale, float):
688
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
689
+ elif (
690
+ isinstance(self.controlnet, MultiControlNetModel)
691
+ or is_compiled
692
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
693
+ ):
694
+ if isinstance(controlnet_conditioning_scale, list):
695
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
696
+ raise ValueError("A single batch of multiple conditionings is not supported at the moment.")
697
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
698
+ self.controlnet.nets
699
+ ):
700
+ raise ValueError(
701
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
702
+ " the same length as the number of controlnets"
703
+ )
704
+ else:
705
+ assert False
706
+
707
+ if not isinstance(control_guidance_start, (tuple, list)):
708
+ control_guidance_start = [control_guidance_start]
709
+
710
+ if not isinstance(control_guidance_end, (tuple, list)):
711
+ control_guidance_end = [control_guidance_end]
712
+
713
+ if len(control_guidance_start) != len(control_guidance_end):
714
+ raise ValueError(
715
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
716
+ )
717
+
718
+ if isinstance(self.controlnet, MultiControlNetModel):
719
+ if len(control_guidance_start) != len(self.controlnet.nets):
720
+ raise ValueError(
721
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
722
+ )
723
+
724
+ for start, end in zip(control_guidance_start, control_guidance_end):
725
+ if start >= end:
726
+ raise ValueError(
727
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
728
+ )
729
+ if start < 0.0:
730
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
731
+ if end > 1.0:
732
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
733
+
734
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
735
+ def check_image(self, image, prompt, prompt_embeds):
736
+ image_is_pil = isinstance(image, PIL.Image.Image)
737
+ image_is_tensor = isinstance(image, torch.Tensor)
738
+ image_is_np = isinstance(image, np.ndarray)
739
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
740
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
741
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
742
+
743
+ if (
744
+ not image_is_pil
745
+ and not image_is_tensor
746
+ and not image_is_np
747
+ and not image_is_pil_list
748
+ and not image_is_tensor_list
749
+ and not image_is_np_list
750
+ ):
751
+ raise TypeError(
752
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
753
+ )
754
+
755
+ if image_is_pil:
756
+ image_batch_size = 1
757
+ else:
758
+ image_batch_size = len(image)
759
+
760
+ if prompt is not None and isinstance(prompt, str):
761
+ prompt_batch_size = 1
762
+ elif prompt is not None and isinstance(prompt, list):
763
+ prompt_batch_size = len(prompt)
764
+ elif prompt_embeds is not None:
765
+ prompt_batch_size = prompt_embeds.shape[0]
766
+
767
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
768
+ raise ValueError(
769
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
770
+ )
771
+
772
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
773
+ def prepare_image(
774
+ self,
775
+ image,
776
+ width,
777
+ height,
778
+ batch_size,
779
+ num_images_per_prompt,
780
+ device,
781
+ dtype,
782
+ do_classifier_free_guidance=False,
783
+ guess_mode=False,
784
+ ):
785
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
786
+ image_batch_size = image.shape[0]
787
+
788
+ if image_batch_size == 1:
789
+ repeat_by = batch_size
790
+ else:
791
+ # image batch size is the same as prompt batch size
792
+ repeat_by = num_images_per_prompt
793
+
794
+ image = image.repeat_interleave(repeat_by, dim=0)
795
+
796
+ image = image.to(device=device, dtype=dtype)
797
+
798
+ if do_classifier_free_guidance and not guess_mode:
799
+ image = torch.cat([image] * 2)
800
+
801
+ return image
802
+
803
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
804
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
805
+ shape = (
806
+ batch_size,
807
+ num_channels_latents,
808
+ int(height) // self.vae_scale_factor,
809
+ int(width) // self.vae_scale_factor,
810
+ )
811
+ if isinstance(generator, list) and len(generator) != batch_size:
812
+ raise ValueError(
813
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
814
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
815
+ )
816
+
817
+ if latents is None:
818
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
819
+ else:
820
+ latents = latents.to(device)
821
+
822
+ # scale the initial noise by the standard deviation required by the scheduler
823
+ latents = latents * self.scheduler.init_noise_sigma
824
+ return latents
825
+
826
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
827
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
828
+ r"""Enables the FreeU mechanism as in https://huggingface.co/papers/2309.11497.
829
+
830
+ The suffixes after the scaling factors represent the stages where they are being applied.
831
+
832
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
833
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
834
+
835
+ Args:
836
+ s1 (`float`):
837
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
838
+ mitigate "oversmoothing effect" in the enhanced denoising process.
839
+ s2 (`float`):
840
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
841
+ mitigate "oversmoothing effect" in the enhanced denoising process.
842
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
843
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
844
+ """
845
+ if not hasattr(self, "unet"):
846
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
847
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
848
+
849
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
850
+ def disable_freeu(self):
851
+ """Disables the FreeU mechanism if enabled."""
852
+ self.unet.disable_freeu()
853
+
854
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
855
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
856
+ """
857
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
858
+
859
+ Args:
860
+ timesteps (`torch.Tensor`):
861
+ generate embedding vectors at these timesteps
862
+ embedding_dim (`int`, *optional*, defaults to 512):
863
+ dimension of the embeddings to generate
864
+ dtype:
865
+ data type of the generated embeddings
866
+
867
+ Returns:
868
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
869
+ """
870
+ assert len(w.shape) == 1
871
+ w = w * 1000.0
872
+
873
+ half_dim = embedding_dim // 2
874
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
875
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
876
+ emb = w.to(dtype)[:, None] * emb[None, :]
877
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
878
+ if embedding_dim % 2 == 1: # zero pad
879
+ emb = torch.nn.functional.pad(emb, (0, 1))
880
+ assert emb.shape == (w.shape[0], embedding_dim)
881
+ return emb
882
+
883
+ @property
884
+ def guidance_scale(self):
885
+ return self._guidance_scale
886
+
887
+ @property
888
+ def clip_skip(self):
889
+ return self._clip_skip
890
+
891
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
892
+ # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
893
+ # corresponds to doing no classifier free guidance.
894
+ @property
895
+ def do_classifier_free_guidance(self):
896
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
897
+
898
+ @property
899
+ def cross_attention_kwargs(self):
900
+ return self._cross_attention_kwargs
901
+
902
+ @property
903
+ def num_timesteps(self):
904
+ return self._num_timesteps
905
+
906
+ @torch.no_grad()
907
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
908
+ def __call__(
909
+ self,
910
+ prompt: Union[str, List[str]] = None,
911
+ image: PipelineImageInput = None,
912
+ image_pair: List[PipelineImageInput] = None,
913
+ height: Optional[int] = None,
914
+ width: Optional[int] = None,
915
+ num_inference_steps: int = 50,
916
+ timesteps: List[int] = None,
917
+ guidance_scale: float = 7.5,
918
+ negative_prompt: Optional[Union[str, List[str]]] = None,
919
+ num_images_per_prompt: Optional[int] = 1,
920
+ eta: float = 0.0,
921
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
922
+ latents: Optional[torch.Tensor] = None,
923
+ prompt_embeds: Optional[torch.Tensor] = None,
924
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
925
+ ip_adapter_image: Optional[PipelineImageInput] = None,
926
+ output_type: Optional[str] = "pil",
927
+ return_dict: bool = True,
928
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
929
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
930
+ guess_mode: bool = False,
931
+ control_guidance_start: Union[float, List[float]] = 0.0,
932
+ control_guidance_end: Union[float, List[float]] = 1.0,
933
+ clip_skip: Optional[int] = None,
934
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
935
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
936
+ **kwargs,
937
+ ):
938
+ r"""
939
+ The call function to the pipeline for generation.
940
+
941
+ Args:
942
+ prompt (`str` or `List[str]`, *optional*):
943
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
944
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
945
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
946
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
947
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
948
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
949
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
950
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
951
+ input to a single ControlNet.
952
+ image_pair `List[PIL.Image.Image]`:
953
+ a pair of task-specific example images
954
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
955
+ The height in pixels of the generated image.
956
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
957
+ The width in pixels of the generated image.
958
+ num_inference_steps (`int`, *optional*, defaults to 50):
959
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
960
+ expense of slower inference.
961
+ timesteps (`List[int]`, *optional*):
962
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
963
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
964
+ passed will be used. Must be in descending order.
965
+ guidance_scale (`float`, *optional*, defaults to 7.5):
966
+ A higher guidance scale value encourages the model to generate images closely linked to the text
967
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
968
+ negative_prompt (`str` or `List[str]`, *optional*):
969
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
970
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
971
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
972
+ The number of images to generate per prompt.
973
+ eta (`float`, *optional*, defaults to 0.0):
974
+ Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only applies
975
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
976
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
977
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
978
+ generation deterministic.
979
+ latents (`torch.Tensor`, *optional*):
980
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
981
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
982
+ tensor is generated by sampling using the supplied random `generator`.
983
+ prompt_embeds (`torch.Tensor`, *optional*):
984
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
985
+ provided, text embeddings are generated from the `prompt` input argument.
986
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
987
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
988
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
989
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
990
+ output_type (`str`, *optional*, defaults to `"pil"`):
991
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
992
+ return_dict (`bool`, *optional*, defaults to `True`):
993
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
994
+ plain tuple.
995
+ callback (`Callable`, *optional*):
996
+ A function that calls every `callback_steps` steps during inference. The function is called with the
997
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
998
+ callback_steps (`int`, *optional*, defaults to 1):
999
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
1000
+ every step.
1001
+ cross_attention_kwargs (`dict`, *optional*):
1002
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1003
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1004
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1005
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1006
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
1007
+ the corresponding scale as a list.
1008
+ guess_mode (`bool`, *optional*, defaults to `False`):
1009
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
1010
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
1011
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1012
+ The percentage of total steps at which the ControlNet starts applying.
1013
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1014
+ The percentage of total steps at which the ControlNet stops applying.
1015
+ clip_skip (`int`, *optional*):
1016
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1017
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1018
+ callback_on_step_end (`Callable`, *optional*):
1019
+ A function that calls at the end of each denoising steps during the inference. The function is called
1020
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1021
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1022
+ `callback_on_step_end_tensor_inputs`.
1023
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1024
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1025
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1026
+ `._callback_tensor_inputs` attribute of your pipeline class.
1027
+
1028
+ Examples:
1029
+
1030
+ Returns:
1031
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1032
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1033
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1034
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1035
+ "not-safe-for-work" (nsfw) content.
1036
+ """
1037
+
1038
+ callback = kwargs.pop("callback", None)
1039
+ callback_steps = kwargs.pop("callback_steps", None)
1040
+
1041
+ if callback is not None:
1042
+ deprecate(
1043
+ "callback",
1044
+ "1.0.0",
1045
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1046
+ )
1047
+ if callback_steps is not None:
1048
+ deprecate(
1049
+ "callback_steps",
1050
+ "1.0.0",
1051
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1052
+ )
1053
+
1054
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1055
+
1056
+ # align format for control guidance
1057
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1058
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1059
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1060
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1061
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1062
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1063
+ control_guidance_start, control_guidance_end = (
1064
+ mult * [control_guidance_start],
1065
+ mult * [control_guidance_end],
1066
+ )
1067
+
1068
+ # 1. Check inputs. Raise error if not correct
1069
+ self.check_inputs(
1070
+ prompt,
1071
+ image,
1072
+ image_pair,
1073
+ callback_steps,
1074
+ negative_prompt,
1075
+ prompt_embeds,
1076
+ negative_prompt_embeds,
1077
+ controlnet_conditioning_scale,
1078
+ control_guidance_start,
1079
+ control_guidance_end,
1080
+ callback_on_step_end_tensor_inputs,
1081
+ )
1082
+
1083
+ self._guidance_scale = guidance_scale
1084
+ self._clip_skip = clip_skip
1085
+ self._cross_attention_kwargs = cross_attention_kwargs
1086
+
1087
+ # 2. Define call parameters
1088
+ if prompt is not None and isinstance(prompt, str):
1089
+ batch_size = 1
1090
+ elif prompt is not None and isinstance(prompt, list):
1091
+ batch_size = len(prompt)
1092
+ else:
1093
+ batch_size = prompt_embeds.shape[0]
1094
+
1095
+ device = self._execution_device
1096
+
1097
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1098
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1099
+
1100
+ global_pool_conditions = (
1101
+ controlnet.config.global_pool_conditions
1102
+ if isinstance(controlnet, ControlNetModel)
1103
+ else controlnet.nets[0].config.global_pool_conditions
1104
+ )
1105
+ guess_mode = guess_mode or global_pool_conditions
1106
+
1107
+ # 3. Encode input prompt
1108
+ text_encoder_lora_scale = (
1109
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1110
+ )
1111
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1112
+ prompt,
1113
+ device,
1114
+ num_images_per_prompt,
1115
+ self.do_classifier_free_guidance,
1116
+ negative_prompt,
1117
+ prompt_embeds=prompt_embeds,
1118
+ negative_prompt_embeds=negative_prompt_embeds,
1119
+ lora_scale=text_encoder_lora_scale,
1120
+ clip_skip=self.clip_skip,
1121
+ )
1122
+ # For classifier free guidance, we need to do two forward passes.
1123
+ # Here we concatenate the unconditional and text embeddings into a single batch
1124
+ # to avoid doing two forward passes
1125
+ if self.do_classifier_free_guidance:
1126
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1127
+
1128
+ # 3.1 Prepare image pair
1129
+
1130
+ if isinstance(controlnet, ControlNetModel):
1131
+ image_pair = torch.cat(
1132
+ [
1133
+ self.prepare_image(
1134
+ image=im,
1135
+ width=width,
1136
+ height=height,
1137
+ batch_size=batch_size * num_images_per_prompt,
1138
+ num_images_per_prompt=num_images_per_prompt,
1139
+ device=device,
1140
+ dtype=controlnet.dtype,
1141
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1142
+ guess_mode=guess_mode,
1143
+ )
1144
+ for im in image_pair
1145
+ ],
1146
+ 1,
1147
+ )
1148
+ # 4. Prepare image
1149
+ if isinstance(controlnet, ControlNetModel):
1150
+ image = self.prepare_image(
1151
+ image=image,
1152
+ width=width,
1153
+ height=height,
1154
+ batch_size=batch_size * num_images_per_prompt,
1155
+ num_images_per_prompt=num_images_per_prompt,
1156
+ device=device,
1157
+ dtype=controlnet.dtype,
1158
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1159
+ guess_mode=guess_mode,
1160
+ )
1161
+ height, width = image.shape[-2:]
1162
+ elif isinstance(controlnet, MultiControlNetModel):
1163
+ images = []
1164
+
1165
+ for image_ in image:
1166
+ image_ = self.prepare_image(
1167
+ image=image_,
1168
+ width=width,
1169
+ height=height,
1170
+ batch_size=batch_size * num_images_per_prompt,
1171
+ num_images_per_prompt=num_images_per_prompt,
1172
+ device=device,
1173
+ dtype=controlnet.dtype,
1174
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1175
+ guess_mode=guess_mode,
1176
+ )
1177
+
1178
+ images.append(image_)
1179
+
1180
+ image = images
1181
+ height, width = image[0].shape[-2:]
1182
+ else:
1183
+ assert False
1184
+
1185
+ # 5. Prepare timesteps
1186
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1187
+ self._num_timesteps = len(timesteps)
1188
+
1189
+ # 6. Prepare latent variables
1190
+ num_channels_latents = self.unet.config.in_channels
1191
+ latents = self.prepare_latents(
1192
+ batch_size * num_images_per_prompt,
1193
+ num_channels_latents,
1194
+ height,
1195
+ width,
1196
+ prompt_embeds.dtype,
1197
+ device,
1198
+ generator,
1199
+ latents,
1200
+ )
1201
+
1202
+ # 6.5 Optionally get Guidance Scale Embedding
1203
+ timestep_cond = None
1204
+ if self.unet.config.time_cond_proj_dim is not None:
1205
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1206
+ timestep_cond = self.get_guidance_scale_embedding(
1207
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1208
+ ).to(device=device, dtype=latents.dtype)
1209
+
1210
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1211
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1212
+
1213
+ # 7.2 Create tensor stating which controlnets to keep
1214
+ controlnet_keep = []
1215
+ for i in range(len(timesteps)):
1216
+ keeps = [
1217
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1218
+ for s, e in zip(control_guidance_start, control_guidance_end)
1219
+ ]
1220
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1221
+
1222
+ # 8. Denoising loop
1223
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1224
+ is_unet_compiled = is_compiled_module(self.unet)
1225
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1226
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1227
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1228
+ for i, t in enumerate(timesteps):
1229
+ # Relevant thread:
1230
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1231
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1232
+ torch._inductor.cudagraph_mark_step_begin()
1233
+ # expand the latents if we are doing classifier free guidance
1234
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1235
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1236
+
1237
+ # controlnet(s) inference
1238
+ if guess_mode and self.do_classifier_free_guidance:
1239
+ # Infer ControlNet only for the conditional batch.
1240
+ control_model_input = latents
1241
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1242
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1243
+ else:
1244
+ control_model_input = latent_model_input
1245
+ controlnet_prompt_embeds = prompt_embeds
1246
+
1247
+ if isinstance(controlnet_keep[i], list):
1248
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1249
+ else:
1250
+ controlnet_cond_scale = controlnet_conditioning_scale
1251
+ if isinstance(controlnet_cond_scale, list):
1252
+ controlnet_cond_scale = controlnet_cond_scale[0]
1253
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1254
+
1255
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1256
+ control_model_input,
1257
+ t,
1258
+ encoder_hidden_states=controlnet_prompt_embeds,
1259
+ controlnet_query_cond=image,
1260
+ controlnet_cond=image_pair,
1261
+ conditioning_scale=cond_scale,
1262
+ guess_mode=guess_mode,
1263
+ return_dict=False,
1264
+ )
1265
+
1266
+ if guess_mode and self.do_classifier_free_guidance:
1267
+ # Inferred ControlNet only for the conditional batch.
1268
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1269
+ # add 0 to the unconditional batch to keep it unchanged.
1270
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1271
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1272
+
1273
+ # predict the noise residual
1274
+ noise_pred = self.unet(
1275
+ latent_model_input,
1276
+ t,
1277
+ encoder_hidden_states=prompt_embeds,
1278
+ timestep_cond=timestep_cond,
1279
+ cross_attention_kwargs=self.cross_attention_kwargs,
1280
+ down_block_additional_residuals=down_block_res_samples,
1281
+ mid_block_additional_residual=mid_block_res_sample,
1282
+ return_dict=False,
1283
+ )[0]
1284
+
1285
+ # perform guidance
1286
+ if self.do_classifier_free_guidance:
1287
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1288
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1289
+
1290
+ # compute the previous noisy sample x_t -> x_t-1
1291
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1292
+
1293
+ if callback_on_step_end is not None:
1294
+ callback_kwargs = {}
1295
+ for k in callback_on_step_end_tensor_inputs:
1296
+ callback_kwargs[k] = locals()[k]
1297
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1298
+
1299
+ latents = callback_outputs.pop("latents", latents)
1300
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1301
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1302
+
1303
+ # call the callback, if provided
1304
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1305
+ progress_bar.update()
1306
+ if callback is not None and i % callback_steps == 0:
1307
+ step_idx = i // getattr(self.scheduler, "order", 1)
1308
+ callback(step_idx, t, latents)
1309
+
1310
+ # If we do sequential model offloading, let's offload unet and controlnet
1311
+ # manually for max memory savings
1312
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1313
+ self.unet.to("cpu")
1314
+ self.controlnet.to("cpu")
1315
+ torch.cuda.empty_cache()
1316
+
1317
+ if not output_type == "latent":
1318
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1319
+ 0
1320
+ ]
1321
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1322
+ else:
1323
+ image = latents
1324
+ has_nsfw_concept = None
1325
+
1326
+ if has_nsfw_concept is None:
1327
+ do_denormalize = [True] * image.shape[0]
1328
+ else:
1329
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1330
+
1331
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1332
+
1333
+ # Offload all models
1334
+ self.maybe_free_model_hooks()
1335
+
1336
+ if not return_dict:
1337
+ return (image, has_nsfw_concept)
1338
+
1339
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/promptdiffusion/promptdiffusioncontrolnet.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ from typing import Any, Dict, Optional, Tuple, Union
15
+
16
+ import torch
17
+
18
+ from diffusers.configuration_utils import register_to_config
19
+ from diffusers.models.controlnet import (
20
+ ControlNetConditioningEmbedding,
21
+ ControlNetModel,
22
+ ControlNetOutput,
23
+ )
24
+ from diffusers.utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ class PromptDiffusionControlNetModel(ControlNetModel):
31
+ """
32
+ A PromptDiffusionControlNet model.
33
+
34
+ Args:
35
+ in_channels (`int`, defaults to 4):
36
+ The number of channels in the input sample.
37
+ flip_sin_to_cos (`bool`, defaults to `True`):
38
+ Whether to flip the sin to cos in the time embedding.
39
+ freq_shift (`int`, defaults to 0):
40
+ The frequency shift to apply to the time embedding.
41
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
42
+ The tuple of downsample blocks to use.
43
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
44
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
45
+ The tuple of output channels for each block.
46
+ layers_per_block (`int`, defaults to 2):
47
+ The number of layers per block.
48
+ downsample_padding (`int`, defaults to 1):
49
+ The padding to use for the downsampling convolution.
50
+ mid_block_scale_factor (`float`, defaults to 1):
51
+ The scale factor to use for the mid block.
52
+ act_fn (`str`, defaults to "silu"):
53
+ The activation function to use.
54
+ norm_num_groups (`int`, *optional*, defaults to 32):
55
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
56
+ in post-processing.
57
+ norm_eps (`float`, defaults to 1e-5):
58
+ The epsilon to use for the normalization.
59
+ cross_attention_dim (`int`, defaults to 1280):
60
+ The dimension of the cross attention features.
61
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
62
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
63
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
64
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
65
+ encoder_hid_dim (`int`, *optional*, defaults to None):
66
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
67
+ dimension to `cross_attention_dim`.
68
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
69
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
70
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
71
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
72
+ The dimension of the attention heads.
73
+ use_linear_projection (`bool`, defaults to `False`):
74
+ class_embed_type (`str`, *optional*, defaults to `None`):
75
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
76
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
77
+ addition_embed_type (`str`, *optional*, defaults to `None`):
78
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
79
+ "text". "text" will use the `TextTimeEmbedding` layer.
80
+ num_class_embeds (`int`, *optional*, defaults to 0):
81
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
82
+ class conditioning with `class_embed_type` equal to `None`.
83
+ upcast_attention (`bool`, defaults to `False`):
84
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
85
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
86
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
87
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
88
+ `class_embed_type="projection"`.
89
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
90
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
91
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
92
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
93
+ global_pool_conditions (`bool`, defaults to `False`):
94
+ TODO(Patrick) - unused parameter.
95
+ addition_embed_type_num_heads (`int`, defaults to 64):
96
+ The number of heads to use for the `TextTimeEmbedding` layer.
97
+ """
98
+
99
+ _supports_gradient_checkpointing = True
100
+
101
+ @register_to_config
102
+ def __init__(
103
+ self,
104
+ in_channels: int = 4,
105
+ conditioning_channels: int = 3,
106
+ flip_sin_to_cos: bool = True,
107
+ freq_shift: int = 0,
108
+ down_block_types: Tuple[str, ...] = (
109
+ "CrossAttnDownBlock2D",
110
+ "CrossAttnDownBlock2D",
111
+ "CrossAttnDownBlock2D",
112
+ "DownBlock2D",
113
+ ),
114
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
115
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
116
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
117
+ layers_per_block: int = 2,
118
+ downsample_padding: int = 1,
119
+ mid_block_scale_factor: float = 1,
120
+ act_fn: str = "silu",
121
+ norm_num_groups: Optional[int] = 32,
122
+ norm_eps: float = 1e-5,
123
+ cross_attention_dim: int = 1280,
124
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
125
+ encoder_hid_dim: Optional[int] = None,
126
+ encoder_hid_dim_type: Optional[str] = None,
127
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
128
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
129
+ use_linear_projection: bool = False,
130
+ class_embed_type: Optional[str] = None,
131
+ addition_embed_type: Optional[str] = None,
132
+ addition_time_embed_dim: Optional[int] = None,
133
+ num_class_embeds: Optional[int] = None,
134
+ upcast_attention: bool = False,
135
+ resnet_time_scale_shift: str = "default",
136
+ projection_class_embeddings_input_dim: Optional[int] = None,
137
+ controlnet_conditioning_channel_order: str = "rgb",
138
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
139
+ global_pool_conditions: bool = False,
140
+ addition_embed_type_num_heads: int = 64,
141
+ ):
142
+ super().__init__(
143
+ in_channels,
144
+ conditioning_channels,
145
+ flip_sin_to_cos,
146
+ freq_shift,
147
+ down_block_types,
148
+ mid_block_type,
149
+ only_cross_attention,
150
+ block_out_channels,
151
+ layers_per_block,
152
+ downsample_padding,
153
+ mid_block_scale_factor,
154
+ act_fn,
155
+ norm_num_groups,
156
+ norm_eps,
157
+ cross_attention_dim,
158
+ transformer_layers_per_block,
159
+ encoder_hid_dim,
160
+ encoder_hid_dim_type,
161
+ attention_head_dim,
162
+ num_attention_heads,
163
+ use_linear_projection,
164
+ class_embed_type,
165
+ addition_embed_type,
166
+ addition_time_embed_dim,
167
+ num_class_embeds,
168
+ upcast_attention,
169
+ resnet_time_scale_shift,
170
+ projection_class_embeddings_input_dim,
171
+ controlnet_conditioning_channel_order,
172
+ conditioning_embedding_out_channels,
173
+ global_pool_conditions,
174
+ addition_embed_type_num_heads,
175
+ )
176
+ self.controlnet_query_cond_embedding = ControlNetConditioningEmbedding(
177
+ conditioning_embedding_channels=block_out_channels[0],
178
+ block_out_channels=conditioning_embedding_out_channels,
179
+ conditioning_channels=3,
180
+ )
181
+
182
+ def forward(
183
+ self,
184
+ sample: torch.Tensor,
185
+ timestep: Union[torch.Tensor, float, int],
186
+ encoder_hidden_states: torch.Tensor,
187
+ controlnet_cond: torch.Tensor,
188
+ controlnet_query_cond: torch.Tensor,
189
+ conditioning_scale: float = 1.0,
190
+ class_labels: Optional[torch.Tensor] = None,
191
+ timestep_cond: Optional[torch.Tensor] = None,
192
+ attention_mask: Optional[torch.Tensor] = None,
193
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
194
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
195
+ guess_mode: bool = False,
196
+ return_dict: bool = True,
197
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
198
+ """
199
+ The [`~PromptDiffusionControlNetModel`] forward method.
200
+
201
+ Args:
202
+ sample (`torch.Tensor`):
203
+ The noisy input tensor.
204
+ timestep (`Union[torch.Tensor, float, int]`):
205
+ The number of timesteps to denoise an input.
206
+ encoder_hidden_states (`torch.Tensor`):
207
+ The encoder hidden states.
208
+ controlnet_cond (`torch.Tensor`):
209
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
210
+ controlnet_query_cond (`torch.Tensor`):
211
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
212
+ conditioning_scale (`float`, defaults to `1.0`):
213
+ The scale factor for ControlNet outputs.
214
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
215
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
216
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
217
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
218
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
219
+ embeddings.
220
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
221
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
222
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
223
+ negative values to the attention scores corresponding to "discard" tokens.
224
+ added_cond_kwargs (`dict`):
225
+ Additional conditions for the Stable Diffusion XL UNet.
226
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
227
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
228
+ guess_mode (`bool`, defaults to `False`):
229
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
230
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
231
+ return_dict (`bool`, defaults to `True`):
232
+ Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain tuple.
233
+
234
+ Returns:
235
+ [`~models.controlnets.controlnet.ControlNetOutput`] **or** `tuple`:
236
+ If `return_dict` is `True`, a [`~models.controlnets.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
237
+ returned where the first element is the sample tensor.
238
+ """
239
+ # check channel order
240
+ channel_order = self.config.controlnet_conditioning_channel_order
241
+
242
+ if channel_order == "rgb":
243
+ # in rgb order by default
244
+ ...
245
+ elif channel_order == "bgr":
246
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
247
+ else:
248
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
249
+
250
+ # prepare attention_mask
251
+ if attention_mask is not None:
252
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
253
+ attention_mask = attention_mask.unsqueeze(1)
254
+
255
+ # 1. time
256
+ timesteps = timestep
257
+ if not torch.is_tensor(timesteps):
258
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
259
+ # This would be a good case for the `match` statement (Python 3.10+)
260
+ is_mps = sample.device.type == "mps"
261
+ is_npu = sample.device.type == "npu"
262
+ if isinstance(timestep, float):
263
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
264
+ else:
265
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
266
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
267
+ elif len(timesteps.shape) == 0:
268
+ timesteps = timesteps[None].to(sample.device)
269
+
270
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
271
+ timesteps = timesteps.expand(sample.shape[0])
272
+
273
+ t_emb = self.time_proj(timesteps)
274
+
275
+ # timesteps does not contain any weights and will always return f32 tensors
276
+ # but time_embedding might actually be running in fp16. so we need to cast here.
277
+ # there might be better ways to encapsulate this.
278
+ t_emb = t_emb.to(dtype=sample.dtype)
279
+
280
+ emb = self.time_embedding(t_emb, timestep_cond)
281
+ aug_emb = None
282
+
283
+ if self.class_embedding is not None:
284
+ if class_labels is None:
285
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
286
+
287
+ if self.config.class_embed_type == "timestep":
288
+ class_labels = self.time_proj(class_labels)
289
+
290
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
291
+ emb = emb + class_emb
292
+
293
+ if self.config.addition_embed_type is not None:
294
+ if self.config.addition_embed_type == "text":
295
+ aug_emb = self.add_embedding(encoder_hidden_states)
296
+
297
+ elif self.config.addition_embed_type == "text_time":
298
+ if "text_embeds" not in added_cond_kwargs:
299
+ raise ValueError(
300
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
301
+ )
302
+ text_embeds = added_cond_kwargs.get("text_embeds")
303
+ if "time_ids" not in added_cond_kwargs:
304
+ raise ValueError(
305
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
306
+ )
307
+ time_ids = added_cond_kwargs.get("time_ids")
308
+ time_embeds = self.add_time_proj(time_ids.flatten())
309
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
310
+
311
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
312
+ add_embeds = add_embeds.to(emb.dtype)
313
+ aug_emb = self.add_embedding(add_embeds)
314
+
315
+ emb = emb + aug_emb if aug_emb is not None else emb
316
+
317
+ # 2. pre-process
318
+ sample = self.conv_in(sample)
319
+
320
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
321
+ controlnet_query_cond = self.controlnet_query_cond_embedding(controlnet_query_cond)
322
+ sample = sample + controlnet_cond + controlnet_query_cond
323
+
324
+ # 3. down
325
+ down_block_res_samples = (sample,)
326
+ for downsample_block in self.down_blocks:
327
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
328
+ sample, res_samples = downsample_block(
329
+ hidden_states=sample,
330
+ temb=emb,
331
+ encoder_hidden_states=encoder_hidden_states,
332
+ attention_mask=attention_mask,
333
+ cross_attention_kwargs=cross_attention_kwargs,
334
+ )
335
+ else:
336
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
337
+
338
+ down_block_res_samples += res_samples
339
+
340
+ # 4. mid
341
+ if self.mid_block is not None:
342
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
343
+ sample = self.mid_block(
344
+ sample,
345
+ emb,
346
+ encoder_hidden_states=encoder_hidden_states,
347
+ attention_mask=attention_mask,
348
+ cross_attention_kwargs=cross_attention_kwargs,
349
+ )
350
+ else:
351
+ sample = self.mid_block(sample, emb)
352
+
353
+ # 5. Control net blocks
354
+
355
+ controlnet_down_block_res_samples = ()
356
+
357
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
358
+ down_block_res_sample = controlnet_block(down_block_res_sample)
359
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
360
+
361
+ down_block_res_samples = controlnet_down_block_res_samples
362
+
363
+ mid_block_res_sample = self.controlnet_mid_block(sample)
364
+
365
+ # 6. scaling
366
+ if guess_mode and not self.config.global_pool_conditions:
367
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
368
+ scales = scales * conditioning_scale
369
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
370
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
371
+ else:
372
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
373
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
374
+
375
+ if self.config.global_pool_conditions:
376
+ down_block_res_samples = [
377
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
378
+ ]
379
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
380
+
381
+ if not return_dict:
382
+ return (down_block_res_samples, mid_block_res_sample)
383
+
384
+ return ControlNetOutput(
385
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
386
+ )
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/inference/flux/README.md ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generating images using Flux and PyTorch/XLA
2
+
3
+ The `flux_inference` script shows how to do image generation using Flux on TPU devices using PyTorch/XLA. It uses the pallas kernel for flash attention for faster generation using custom flash block sizes for better performance on [Trillium](https://cloud.google.com/blog/products/compute/introducing-trillium-6th-gen-tpus) TPU versions. No other TPU types have been tested.
4
+
5
+ ## Create TPU
6
+
7
+ To create a TPU on Google Cloud, follow [this guide](https://cloud.google.com/tpu/docs/v6e)
8
+
9
+ ## Setup TPU environment
10
+
11
+ SSH into the VM and install Pytorch, Pytorch/XLA
12
+
13
+ ```bash
14
+ pip install torch~=2.5.0 torch_xla[tpu]~=2.5.0 -f https://storage.googleapis.com/libtpu-releases/index.html -f https://storage.googleapis.com/libtpu-wheels/index.html
15
+ pip install torch_xla[pallas] -f https://storage.googleapis.com/jax-releases/jax_nightly_releases.html -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_releases.html
16
+ ```
17
+
18
+ Verify that PyTorch and PyTorch/XLA were installed correctly:
19
+
20
+ ```bash
21
+ python3 -c "import torch; import torch_xla;"
22
+ ```
23
+
24
+ Clone the diffusers repo and install dependencies
25
+
26
+ ```bash
27
+ git clone https://github.com/huggingface/diffusers.git
28
+ cd diffusers
29
+ pip install transformers accelerate sentencepiece structlog
30
+ pip install .
31
+ cd examples/research_projects/pytorch_xla/inference/flux/
32
+ ```
33
+
34
+ ## Run the inference job
35
+
36
+ ### Authenticate
37
+
38
+ **Gated Model**
39
+
40
+ As the model is gated, before using it with diffusers you first need to go to the [FLUX.1 [dev] Hugging Face page](https://huggingface.co/black-forest-labs/FLUX.1-dev), fill in the form and accept the gate. Once you are in, you need to log in so that your system knows you’ve accepted the gate. Use the command below to log in:
41
+
42
+ ```bash
43
+ hf auth login
44
+ ```
45
+
46
+ Then run:
47
+
48
+ ```bash
49
+ python flux_inference.py
50
+ ```
51
+
52
+ The script loads the text encoders onto the CPU and the Flux transformer and VAE models onto the TPU. The first time the script runs, the compilation time is longer, while the cache stores the compiled programs. On subsequent runs, compilation is much faster and the subsequent passes being the fastest.
53
+
54
+ On a Trillium v6e-4, you should expect ~6 sec / 4 images or 1.5 sec / image (as devices run generation in parallel):
55
+
56
+ ```bash
57
+ WARNING:root:libtpu.so and TPU device found. Setting PJRT_DEVICE=TPU.
58
+ Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 7.06it/s]
59
+ Loading pipeline components...: 60%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ | 3/5 [00:00<00:00, 6.80it/s]You set `add_prefix_space`. The tokenizer needs to be converted from the slow tokenizers
60
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 5/5 [00:00<00:00, 6.28it/s]
61
+ 2025-03-14 21:17:53 [info ] loading flux from black-forest-labs/FLUX.1-dev
62
+ 2025-03-14 21:17:53 [info ] loading flux from black-forest-labs/FLUX.1-dev
63
+ Loading pipeline components...: 0%| | 0/3 [00:00<?, ?it/s]2025-03-14 21:17:53 [info ] loading flux from black-forest-labs/FLUX.1-dev
64
+ 2025-03-14 21:17:53 [info ] loading flux from black-forest-labs/FLUX.1-dev
65
+ Loading pipeline components...: 0%| | 0/3 [00:00<?, ?it/s]2025-03-14 21:17:54 [info ] loading flux from black-forest-labs/FLUX.1-dev
66
+ 2025-03-14 21:17:54 [info ] loading flux from black-forest-labs/FLUX.1-dev
67
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.66it/s]
68
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 4.48it/s]
69
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.32it/s]
70
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.69it/s]
71
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.74it/s]
72
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████���███████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.10it/s]
73
+ 2025-03-14 21:17:56 [info ] loading flux from black-forest-labs/FLUX.1-dev
74
+ Loading pipeline components...: 0%| | 0/3 [00:00<?, ?it/s]2025-03-14 21:17:56 [info ] loading flux from black-forest-labs/FLUX.1-dev
75
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:00<00:00, 3.55it/s]
76
+ Loading pipeline components...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3/3 [00:02<00:00, 1.46it/s]
77
+ 2025-03-14 21:18:34 [info ] starting compilation run...
78
+ 2025-03-14 21:18:37 [info ] starting compilation run...
79
+ 2025-03-14 21:18:38 [info ] starting compilation run...
80
+ 2025-03-14 21:18:39 [info ] starting compilation run...
81
+ 2025-03-14 21:18:41 [info ] starting compilation run...
82
+ 2025-03-14 21:18:41 [info ] starting compilation run...
83
+ 2025-03-14 21:18:42 [info ] starting compilation run...
84
+ 2025-03-14 21:18:43 [info ] starting compilation run...
85
+ 82%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 23/28 [13:35<03:04, 36.80s/it]2025-03-14 21:33:42.057559: W torch_xla/csrc/runtime/pjrt_computation_client.cc:667] Failed to deserialize executable: INTERNAL: TfrtTpuExecutable proto deserialization failed while parsing core program!
86
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:27<00:00, 35.28s/it]
87
+ 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████��█████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:27<00:00, 35.26s/it]
88
+ 2025-03-14 21:36:38 [info ] compilation took 1079.3314765350078 sec.
89
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:12<00:00, 34.73s/it]
90
+ 2025-03-14 21:36:38 [info ] starting inference run...
91
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:12<00:00, 34.73s/it]
92
+ 2025-03-14 21:36:38 [info ] compilation took 1081.89390801001 sec.
93
+ 2025-03-14 21:36:39 [info ] starting inference run...
94
+ 2025-03-14 21:36:39 [info ] compilation took 1077.1543154849933 sec.
95
+ 2025-03-14 21:36:39 [info ] compilation took 1075.7239800530078 sec.
96
+ 2025-03-14 21:36:39 [info ] starting inference run...
97
+ 2025-03-14 21:36:40 [info ] starting inference run...
98
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:22<00:00, 35.10s/it]
99
+ 2025-03-14 21:36:50 [info ] compilation took 1088.1632604240003 sec.
100
+ 2025-03-14 21:36:50 [info ] starting inference run...
101
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:28<00:00, 35.32s/it]
102
+ 2025-03-14 21:36:55 [info ] compilation took 1096.8027802760043 sec.
103
+ 2025-03-14 21:36:56 [info ] starting inference run...
104
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:59<00:00, 36.40s/it]
105
+ 2025-03-14 21:37:08 [info ] compilation took 1113.8591305939917 sec.
106
+ 2025-03-14 21:37:08 [info ] starting inference run...
107
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [16:55<00:00, 36.26s/it]
108
+ 2025-03-14 21:37:22 [info ] compilation took 1120.5590810020076 sec.
109
+ 2025-03-14 21:37:22 [info ] starting inference run...
110
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 5.00it/s]
111
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:09<00:00, 2.98it/s]
112
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:06<00:00, 4.08it/s]
113
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:09<00:00, 2.82it/s]
114
+ 100%|█████████████████████████████████████████████████████████████████████████████████████████████████��████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:08<00:00, 3.34it/s]
115
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:06<00:00, 4.22it/s]
116
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:06<00:00, 4.09it/s]
117
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:11<00:00, 2.41it/s]
118
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:06<00:00, 4.50it/s]
119
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 5.10it/s]
120
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████���███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 5.27it/s]
121
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 4.80it/s]
122
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 5.39it/s]
123
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:05<00:00, 5.39it/s]
124
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.67it/s]
125
+ 29%|█████████████████████████████████████████████████████████████████████████████▍ | 8/28 [00:01<00:03, 6.08it/s]/home/jfacevedo_google_com/diffusers/src/diffusers/image_processor.py:147: RuntimeWarning: invalid value encountered in cast
126
+ images = (images * 255).round().astype("uint8")
127
+ 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████��█████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.82it/s]
128
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.93it/s]
129
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.02it/s]
130
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.02it/s]
131
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.98it/s]
132
+ 71%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 20/28 [00:03<00:01, 6.03it/s]2025-03-14 21:38:32 [info ] inference time: 5.962021178987925
133
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.89it/s]
134
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.09it/s]
135
+ 2025-03-14 21:38:32 [info ] avg. inference over 5 iterations took 7.2685392687970305 sec.
136
+ 2025-03-14 21:38:32 [info ] avg. inference over 5 iterations took 7.402720856998348 sec.
137
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.01it/s]
138
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.89it/s]
139
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.96it/s]
140
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.06it/s]
141
+ 71%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████��███████████████████████▊ | 20/28 [00:03<00:01, 6.01it/s]2025-03-14 21:38:38 [info ] inference time: 5.950578948002658
142
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.87it/s]
143
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.09it/s]
144
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.00it/s]
145
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.86it/s]
146
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.99it/s]
147
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.05it/s]
148
+ 2025-03-14 21:38:43 [info ] avg. inference over 5 iterations took 6.763298449796276 sec.
149
+ 71%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▊ | 20/28 [00:03<00:01, 6.04it/s]2025-03-14 21:38:44 [info ] inference time: 5.949129879008979
150
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.92it/s]
151
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.10it/s]
152
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.02it/s]
153
+ 39%|██████████████████████████████████████████████████████████████████████████████████████████████████████████ | 11/28 [00:01<00:02, 5.98it/s]2025-03-14 21:38:46 [info ] avg. inference over 5 iterations took 7.221068455604836 sec.
154
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.96it/s]
155
+ 100%|█████████��████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.08it/s]
156
+ 93%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▋ | 26/28 [00:04<00:00, 5.92it/s]2025-03-14 21:38:50 [info ] inference time: 5.954778069004533
157
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.90it/s]
158
+ 11%|█████████████████████████████ | 3/28 [00:00<00:04, 6.03it/s]2025-03-14 21:38:50 [info ] avg. inference over 5 iterations took 6.05970350120042 sec.
159
+ 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 6.02it/s]
160
+ 32%|███████████████████████████████████████████████████████████████████████████████████████ | 9/28 [00:01<00:03, 5.99it/s]2025-03-14 21:38:51 [info ] avg. inference over 5 iterations took 6.018543455796316 sec.
161
+ 54%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▋ | 15/28 [00:02<00:02, 6.00it/s]2025-03-14 21:38:52 [info ] avg. inference over 5 iterations took 5.9609976705978625 sec.
162
+ 100%|���█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 28/28 [00:04<00:00, 5.97it/s]
163
+ 2025-03-14 21:38:56 [info ] inference time: 5.944058528999449
164
+ 2025-03-14 21:38:56 [info ] avg. inference over 5 iterations took 5.952113320800708 sec.
165
+ 2025-03-14 21:38:56 [info ] saved metric information as /tmp/metrics_report.txt
166
+ ```
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/inference/flux/flux_inference.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import ArgumentParser
2
+ from pathlib import Path
3
+ from time import perf_counter
4
+
5
+ import structlog
6
+ import torch
7
+ import torch_xla.core.xla_model as xm
8
+ import torch_xla.debug.metrics as met
9
+ import torch_xla.debug.profiler as xp
10
+ import torch_xla.distributed.xla_multiprocessing as xmp
11
+ import torch_xla.runtime as xr
12
+ from torch_xla.experimental.custom_kernel import FlashAttention
13
+
14
+ from diffusers import FluxPipeline
15
+
16
+
17
+ logger = structlog.get_logger()
18
+ metrics_filepath = "/tmp/metrics_report.txt"
19
+
20
+
21
+ def _main(index, args, text_pipe, ckpt_id):
22
+ cache_path = Path("/tmp/data/compiler_cache_tRiLlium_eXp")
23
+ cache_path.mkdir(parents=True, exist_ok=True)
24
+ xr.initialize_cache(str(cache_path), readonly=False)
25
+
26
+ profile_path = Path("/tmp/data/profiler_out_tRiLlium_eXp")
27
+ profile_path.mkdir(parents=True, exist_ok=True)
28
+ profiler_port = 9012
29
+ profile_duration = args.profile_duration
30
+ if args.profile:
31
+ logger.info(f"starting profiler on port {profiler_port}")
32
+ _ = xp.start_server(profiler_port)
33
+ device0 = xm.xla_device()
34
+
35
+ logger.info(f"loading flux from {ckpt_id}")
36
+ flux_pipe = FluxPipeline.from_pretrained(
37
+ ckpt_id, text_encoder=None, tokenizer=None, text_encoder_2=None, tokenizer_2=None, torch_dtype=torch.bfloat16
38
+ ).to(device0)
39
+ flux_pipe.transformer.enable_xla_flash_attention(partition_spec=("data", None, None, None), is_flux=True)
40
+ FlashAttention.DEFAULT_BLOCK_SIZES = {
41
+ "block_q": 1536,
42
+ "block_k_major": 1536,
43
+ "block_k": 1536,
44
+ "block_b": 1536,
45
+ "block_q_major_dkv": 1536,
46
+ "block_k_major_dkv": 1536,
47
+ "block_q_dkv": 1536,
48
+ "block_k_dkv": 1536,
49
+ "block_q_dq": 1536,
50
+ "block_k_dq": 1536,
51
+ "block_k_major_dq": 1536,
52
+ }
53
+
54
+ prompt = "photograph of an electronics chip in the shape of a race car with trillium written on its side"
55
+ width = args.width
56
+ height = args.height
57
+ guidance = args.guidance
58
+ n_steps = 4 if args.schnell else 28
59
+
60
+ logger.info("starting compilation run...")
61
+ ts = perf_counter()
62
+ with torch.no_grad():
63
+ prompt_embeds, pooled_prompt_embeds, text_ids = text_pipe.encode_prompt(
64
+ prompt=prompt, prompt_2=None, max_sequence_length=512
65
+ )
66
+ prompt_embeds = prompt_embeds.to(device0)
67
+ pooled_prompt_embeds = pooled_prompt_embeds.to(device0)
68
+
69
+ image = flux_pipe(
70
+ prompt_embeds=prompt_embeds,
71
+ pooled_prompt_embeds=pooled_prompt_embeds,
72
+ num_inference_steps=28,
73
+ guidance_scale=guidance,
74
+ height=height,
75
+ width=width,
76
+ ).images[0]
77
+ logger.info(f"compilation took {perf_counter() - ts} sec.")
78
+ image.save("/tmp/compile_out.png")
79
+
80
+ base_seed = 4096 if args.seed is None else args.seed
81
+ seed_range = 1000
82
+ unique_seed = base_seed + index * seed_range
83
+ xm.set_rng_state(seed=unique_seed, device=device0)
84
+ times = []
85
+ logger.info("starting inference run...")
86
+ with torch.no_grad():
87
+ prompt_embeds, pooled_prompt_embeds, text_ids = text_pipe.encode_prompt(
88
+ prompt=prompt, prompt_2=None, max_sequence_length=512
89
+ )
90
+ prompt_embeds = prompt_embeds.to(device0)
91
+ pooled_prompt_embeds = pooled_prompt_embeds.to(device0)
92
+ for _ in range(args.itters):
93
+ ts = perf_counter()
94
+
95
+ if args.profile:
96
+ xp.trace_detached(f"localhost:{profiler_port}", str(profile_path), duration_ms=profile_duration)
97
+ image = flux_pipe(
98
+ prompt_embeds=prompt_embeds,
99
+ pooled_prompt_embeds=pooled_prompt_embeds,
100
+ num_inference_steps=n_steps,
101
+ guidance_scale=guidance,
102
+ height=height,
103
+ width=width,
104
+ ).images[0]
105
+ inference_time = perf_counter() - ts
106
+ if index == 0:
107
+ logger.info(f"inference time: {inference_time}")
108
+ times.append(inference_time)
109
+ logger.info(f"avg. inference over {args.itters} iterations took {sum(times) / len(times)} sec.")
110
+ image.save(f"/tmp/inference_out-{index}.png")
111
+ if index == 0:
112
+ metrics_report = met.metrics_report()
113
+ with open(metrics_filepath, "w+") as fout:
114
+ fout.write(metrics_report)
115
+ logger.info(f"saved metric information as {metrics_filepath}")
116
+
117
+
118
+ if __name__ == "__main__":
119
+ parser = ArgumentParser()
120
+ parser.add_argument("--schnell", action="store_true", help="run flux schnell instead of dev")
121
+ parser.add_argument("--width", type=int, default=1024, help="width of the image to generate")
122
+ parser.add_argument("--height", type=int, default=1024, help="height of the image to generate")
123
+ parser.add_argument("--guidance", type=float, default=3.5, help="guidance strength for dev")
124
+ parser.add_argument("--seed", type=int, default=None, help="seed for inference")
125
+ parser.add_argument("--profile", action="store_true", help="enable profiling")
126
+ parser.add_argument("--profile-duration", type=int, default=10000, help="duration for profiling in msec.")
127
+ parser.add_argument("--itters", type=int, default=15, help="items to run inference and get avg time in sec.")
128
+ args = parser.parse_args()
129
+ if args.schnell:
130
+ ckpt_id = "black-forest-labs/FLUX.1-schnell"
131
+ else:
132
+ ckpt_id = "black-forest-labs/FLUX.1-dev"
133
+ text_pipe = FluxPipeline.from_pretrained(ckpt_id, transformer=None, vae=None, torch_dtype=torch.bfloat16).to("cpu")
134
+ xmp.spawn(_main, args=(args, text_pipe, ckpt_id))
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/training/text_to_image/README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stable Diffusion text-to-image fine-tuning using PyTorch/XLA
2
+
3
+ The `train_text_to_image_xla.py` script shows how to fine-tune stable diffusion model on TPU devices using PyTorch/XLA.
4
+
5
+ It has been tested on v4 and v5p TPU versions. Training code has been tested on multi-host.
6
+
7
+ This script implements Distributed Data Parallel using GSPMD feature in XLA compiler
8
+ where we shard the input batches over the TPU devices.
9
+
10
+ As of 10-31-2024, these are some expected step times.
11
+
12
+ | accelerator | global batch size | step time (seconds) |
13
+ | ----------- | ----------------- | --------- |
14
+ | v5p-512 | 16384 | 1.01 |
15
+ | v5p-256 | 8192 | 1.01 |
16
+ | v5p-128 | 4096 | 1.0 |
17
+ | v5p-64 | 2048 | 1.01 |
18
+
19
+ ## Create TPU
20
+
21
+ To create a TPU on Google Cloud first set these environment variables:
22
+
23
+ ```bash
24
+ export TPU_NAME=<tpu-name>
25
+ export PROJECT_ID=<project-id>
26
+ export ZONE=<google-cloud-zone>
27
+ export ACCELERATOR_TYPE=<accelerator type like v5p-8>
28
+ export RUNTIME_VERSION=<runtime version like v2-alpha-tpuv5 for v5p>
29
+ ```
30
+
31
+ Then run the create TPU command:
32
+ ```bash
33
+ gcloud alpha compute tpus tpu-vm create ${TPU_NAME} --project ${PROJECT_ID}
34
+ --zone ${ZONE} --accelerator-type ${ACCELERATOR_TYPE} --version ${RUNTIME_VERSION}
35
+ --reserved
36
+ ```
37
+
38
+ You can also use other ways to reserve TPUs like GKE or queued resources.
39
+
40
+ ## Setup TPU environment
41
+
42
+ Install PyTorch and PyTorch/XLA nightly versions:
43
+ ```bash
44
+ gcloud compute tpus tpu-vm ssh ${TPU_NAME} \
45
+ --project=${PROJECT_ID} --zone=${ZONE} --worker=all \
46
+ --command='
47
+ pip3 install --pre torch==2.6.0.dev20241031+cpu torchvision --index-url https://download.pytorch.org/whl/nightly/cpu
48
+ pip3 install "torch_xla[tpu] @ https://storage.googleapis.com/pytorch-xla-releases/wheels/tpuvm/torch_xla-2.6.0.dev20241031.cxx11-cp310-cp310-linux_x86_64.whl" -f https://storage.googleapis.com/libtpu-releases/index.html
49
+ pip install torch_xla[pallas] -f https://storage.googleapis.com/jax-releases/jax_nightly_releases.html -f https://storage.googleapis.com/jax-releases/jaxlib_nightly_releases.html
50
+ '
51
+ ```
52
+
53
+ Verify that PyTorch and PyTorch/XLA were installed correctly:
54
+
55
+ ```bash
56
+ gcloud compute tpus tpu-vm ssh ${TPU_NAME} \
57
+ --project ${PROJECT_ID} --zone ${ZONE} --worker=all \
58
+ --command='python3 -c "import torch; import torch_xla;"'
59
+ ```
60
+
61
+ Install dependencies:
62
+ ```bash
63
+ gcloud compute tpus tpu-vm ssh ${TPU_NAME} \
64
+ --project=${PROJECT_ID} --zone=${ZONE} --worker=all \
65
+ --command='
66
+ git clone https://github.com/huggingface/diffusers.git
67
+ cd diffusers
68
+ git checkout main
69
+ cd examples/research_projects/pytorch_xla
70
+ pip3 install -r requirements.txt
71
+ pip3 install pillow --upgrade
72
+ cd ../../..
73
+ pip3 install .'
74
+ ```
75
+
76
+ ## Run the training job
77
+
78
+ ### Authenticate
79
+
80
+ Run the following command to authenticate your token.
81
+
82
+ ```bash
83
+ hf auth login
84
+ ```
85
+
86
+ This script only trains the unet part of the network. The VAE and text encoder
87
+ are fixed.
88
+
89
+ ```bash
90
+ gcloud compute tpus tpu-vm ssh ${TPU_NAME} \
91
+ --project=${PROJECT_ID} --zone=${ZONE} --worker=all \
92
+ --command='
93
+ export XLA_DISABLE_FUNCTIONALIZATION=0
94
+ export PROFILE_DIR=/tmp/
95
+ export CACHE_DIR=/tmp/
96
+ export DATASET_NAME=lambdalabs/naruto-blip-captions
97
+ export PER_HOST_BATCH_SIZE=32 # This is known to work on TPU v4. Can set this to 64 for TPU v5p
98
+ export TRAIN_STEPS=50
99
+ export OUTPUT_DIR=/tmp/trained-model/
100
+ python diffusers/examples/research_projects/pytorch_xla/train_text_to_image_xla.py --pretrained_model_name_or_path=stabilityai/stable-diffusion-2-base --dataset_name=$DATASET_NAME --resolution=512 --center_crop --random_flip --train_batch_size=$PER_HOST_BATCH_SIZE --max_train_steps=$TRAIN_STEPS --learning_rate=1e-06 --mixed_precision=bf16 --profile_duration=80000 --output_dir=$OUTPUT_DIR --dataloader_num_workers=8 --loader_prefetch_size=4 --device_prefetch_size=4'
101
+ ```
102
+
103
+ Pass `--print_loss` if you would like to see the loss printed at every step. Be aware that printing the loss at every step disrupts the optimized flow execution, thus the step time will be longer.
104
+
105
+ ### Environment Envs Explained
106
+
107
+ * `XLA_DISABLE_FUNCTIONALIZATION`: To optimize the performance for AdamW optimizer.
108
+ * `PROFILE_DIR`: Specify where to put the profiling results.
109
+ * `CACHE_DIR`: Directory to store XLA compiled graphs for persistent caching.
110
+ * `DATASET_NAME`: Dataset to train the model.
111
+ * `PER_HOST_BATCH_SIZE`: Size of the batch to load per CPU host. For e.g. for a v5p-16 with 2 CPU hosts, the global batch size will be 2xPER_HOST_BATCH_SIZE. The input batch is sharded along the batch axis.
112
+ * `TRAIN_STEPS`: Total number of training steps to run the training for.
113
+ * `OUTPUT_DIR`: Directory to store the fine-tuned model.
114
+
115
+ ## Run inference using the output model
116
+
117
+ To run inference using the output, you can simply load the model and pass it
118
+ input prompts. The first pass will compile the graph and takes longer with the following passes running much faster.
119
+
120
+ ```bash
121
+ export CACHE_DIR=/tmp/
122
+ ```
123
+
124
+ ```python
125
+ import torch
126
+ import os
127
+ import sys
128
+ import numpy as np
129
+
130
+ import torch_xla.core.xla_model as xm
131
+ from time import time
132
+ from diffusers import StableDiffusionPipeline
133
+ import torch_xla.runtime as xr
134
+
135
+ CACHE_DIR = os.environ.get("CACHE_DIR", None)
136
+ if CACHE_DIR:
137
+ xr.initialize_cache(CACHE_DIR, readonly=False)
138
+
139
+ def main():
140
+ device = xm.xla_device()
141
+ model_path = "jffacevedo/pxla_trained_model"
142
+ pipe = StableDiffusionPipeline.from_pretrained(
143
+ model_path,
144
+ torch_dtype=torch.bfloat16
145
+ )
146
+ pipe.to(device)
147
+ prompt = ["A naruto with green eyes and red legs."]
148
+ start = time()
149
+ print("compiling...")
150
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
151
+ print(f"compile time: {time() - start}")
152
+ print("generate...")
153
+ start = time()
154
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
155
+ print(f"generation time (after compile) : {time() - start}")
156
+ image.save("naruto.png")
157
+
158
+ if __name__ == '__main__':
159
+ main()
160
+ ```
161
+
162
+ Expected Results:
163
+
164
+ ```bash
165
+ compiling...
166
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 30/30 [10:03<00:00, 20.10s/it]
167
+ compile time: 720.656970500946
168
+ generate...
169
+ 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 30/30 [00:01<00:00, 17.65it/s]
170
+ generation time (after compile) : 1.8461642265319824
tasks/tasksmith-83a0918520ec/tests/source/examples/research_projects/pytorch_xla/training/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.7.0