AdithyaSK HF Staff commited on
Commit
dcfc5ae
·
verified ·
1 Parent(s): d379963

Stage Harbor release files 77001-77500

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-d977e5ab6579/tests/source/examples/research_projects/gligen/train_gligen_text.py +715 -0
  2. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/instructpix2pix_lora/README.md +106 -0
  3. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/instructpix2pix_lora/train_instruct_pix2pix_lora.py +1171 -0
  4. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/README.md +36 -0
  5. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/inference_bf16.py +56 -0
  6. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/README.md +68 -0
  7. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/requirements.txt +7 -0
  8. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py +646 -0
  9. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md +93 -0
  10. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt +7 -0
  11. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py +112 -0
  12. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py +996 -0
  13. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/README.md +226 -0
  14. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/requirements.txt +4 -0
  15. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py +415 -0
  16. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py +422 -0
  17. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py +445 -0
  18. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py +520 -0
  19. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lora/README.md +83 -0
  20. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lora/requirements.txt +8 -0
  21. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lora/train_text_to_image_lora.py +1026 -0
  22. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lpl/README.md +157 -0
  23. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lpl/lpl_loss.py +215 -0
  24. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lpl/train_sdxl_lpl.py +1622 -0
  25. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth/README.md +338 -0
  26. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth/requirements.txt +6 -0
  27. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py +1195 -0
  28. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/README.md +93 -0
  29. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/requirements.txt +8 -0
  30. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/train_multi_subject_dreambooth_inpainting.py +661 -0
  31. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/README.md +143 -0
  32. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/multi_token_clip.py +104 -0
  33. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/requirements.txt +6 -0
  34. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/requirements_flax.txt +8 -0
  35. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion.py +938 -0
  36. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion_flax.py +654 -0
  37. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/README.md +5 -0
  38. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/text_to_image/README.md +74 -0
  39. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/text_to_image/requirements.txt +7 -0
  40. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/text_to_image/train_text_to_image.py +955 -0
  41. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/textual_inversion/README.md +94 -0
  42. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/textual_inversion/requirements.txt +6 -0
  43. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/textual_inversion/textual_inversion.py +959 -0
  44. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/README.md +50 -0
  45. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/requirements.txt +4 -0
  46. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/onnxruntime/unconditional_image_generation/train_unconditional.py +697 -0
  47. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/pixart/.gitignore +2 -0
  48. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/pixart/controlnet_pixart_alpha.py +291 -0
  49. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/pixart/pipeline_pixart_alpha_controlnet.py +1098 -0
  50. tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/pixart/requirements.txt +6 -0
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/gligen/train_gligen_text.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from accelerate.utils import write_basic_config
2
+ #
3
+ # write_basic_config()
4
+ import argparse
5
+ import logging
6
+ import math
7
+ import os
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ import accelerate
12
+ import torch
13
+ import torch.nn.functional as F
14
+ import torch.utils.checkpoint
15
+ import transformers
16
+ from accelerate import Accelerator
17
+ from accelerate.logging import get_logger
18
+ from accelerate.utils import ProjectConfiguration, set_seed
19
+ from packaging import version
20
+ from tqdm.auto import tqdm
21
+
22
+ import diffusers
23
+ from diffusers import (
24
+ AutoencoderKL,
25
+ DDPMScheduler,
26
+ EulerDiscreteScheduler,
27
+ StableDiffusionGLIGENPipeline,
28
+ UNet2DConditionModel,
29
+ )
30
+ from diffusers.optimization import get_scheduler
31
+ from diffusers.utils import is_wandb_available, make_image_grid
32
+ from diffusers.utils.import_utils import is_xformers_available
33
+ from diffusers.utils.torch_utils import is_compiled_module
34
+
35
+
36
+ if is_wandb_available():
37
+ pass
38
+
39
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
40
+ # check_min_version("0.28.0.dev0")
41
+
42
+ logger = get_logger(__name__)
43
+
44
+
45
+ @torch.no_grad()
46
+ def log_validation(vae, text_encoder, tokenizer, unet, noise_scheduler, args, accelerator, step, weight_dtype):
47
+ if accelerator.is_main_process:
48
+ print("generate test images...")
49
+ unet = accelerator.unwrap_model(unet)
50
+ vae.to(accelerator.device, dtype=torch.float32)
51
+
52
+ pipeline = StableDiffusionGLIGENPipeline(
53
+ vae,
54
+ text_encoder,
55
+ tokenizer,
56
+ unet,
57
+ EulerDiscreteScheduler.from_config(noise_scheduler.config),
58
+ safety_checker=None,
59
+ feature_extractor=None,
60
+ )
61
+ pipeline = pipeline.to(accelerator.device)
62
+ pipeline.set_progress_bar_config(disable=not accelerator.is_main_process)
63
+ if args.enable_xformers_memory_efficient_attention:
64
+ pipeline.enable_xformers_memory_efficient_attention()
65
+
66
+ if args.seed is None:
67
+ generator = None
68
+ else:
69
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
70
+
71
+ prompt = "A realistic image of landscape scene depicting a green car parking on the left of a blue truck, with a red air balloon and a bird in the sky"
72
+ boxes = [
73
+ [0.041015625, 0.548828125, 0.453125, 0.859375],
74
+ [0.525390625, 0.552734375, 0.93359375, 0.865234375],
75
+ [0.12890625, 0.015625, 0.412109375, 0.279296875],
76
+ [0.578125, 0.08203125, 0.857421875, 0.27734375],
77
+ ]
78
+ gligen_phrases = ["a green car", "a blue truck", "a red air balloon", "a bird"]
79
+ images = pipeline(
80
+ prompt=prompt,
81
+ gligen_phrases=gligen_phrases,
82
+ gligen_boxes=boxes,
83
+ gligen_scheduled_sampling_beta=1.0,
84
+ output_type="pil",
85
+ num_inference_steps=50,
86
+ negative_prompt="artifacts, blurry, smooth texture, bad quality, distortions, unrealistic, distorted image, bad proportions, duplicate",
87
+ num_images_per_prompt=4,
88
+ generator=generator,
89
+ ).images
90
+ os.makedirs(os.path.join(args.output_dir, "images"), exist_ok=True)
91
+ make_image_grid(images, 1, 4).save(
92
+ os.path.join(args.output_dir, "images", f"generated-images-{step:06d}-{accelerator.process_index:02d}.png")
93
+ )
94
+
95
+ vae.to(accelerator.device, dtype=weight_dtype)
96
+
97
+
98
+ def parse_args(input_args=None):
99
+ parser = argparse.ArgumentParser(description="Simple example of a ControlNet training script.")
100
+ parser.add_argument(
101
+ "--data_path",
102
+ type=str,
103
+ default="coco_train2017.pth",
104
+ help="Path to training dataset.",
105
+ )
106
+ parser.add_argument(
107
+ "--image_path",
108
+ type=str,
109
+ default="coco_train2017.pth",
110
+ help="Path to training images.",
111
+ )
112
+ parser.add_argument(
113
+ "--output_dir",
114
+ type=str,
115
+ default="controlnet-model",
116
+ help="The output directory where the model predictions and checkpoints will be written.",
117
+ )
118
+ parser.add_argument("--seed", type=int, default=0, help="A seed for reproducible training.")
119
+ parser.add_argument(
120
+ "--resolution",
121
+ type=int,
122
+ default=512,
123
+ help=(
124
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
125
+ " resolution"
126
+ ),
127
+ )
128
+ parser.add_argument(
129
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
130
+ )
131
+ parser.add_argument("--num_train_epochs", type=int, default=1)
132
+ parser.add_argument(
133
+ "--max_train_steps",
134
+ type=int,
135
+ default=None,
136
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
137
+ )
138
+ parser.add_argument(
139
+ "--checkpointing_steps",
140
+ type=int,
141
+ default=500,
142
+ help=(
143
+ "Save a checkpoint of the training state every X updates. Checkpoints can be used for resuming training via `--resume_from_checkpoint`. "
144
+ "In the case that the checkpoint is better than the final trained model, the checkpoint can also be used for inference."
145
+ "Using a checkpoint for inference requires separate loading of the original pipeline and the individual checkpointed model components."
146
+ "See https://huggingface.co/docs/diffusers/main/en/training/dreambooth#performing-inference-using-a-saved-checkpoint for step by step"
147
+ "instructions."
148
+ ),
149
+ )
150
+ parser.add_argument(
151
+ "--checkpoints_total_limit",
152
+ type=int,
153
+ default=None,
154
+ help=("Max number of checkpoints to store."),
155
+ )
156
+ parser.add_argument(
157
+ "--resume_from_checkpoint",
158
+ type=str,
159
+ default=None,
160
+ help=(
161
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
162
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
163
+ ),
164
+ )
165
+ parser.add_argument(
166
+ "--gradient_accumulation_steps",
167
+ type=int,
168
+ default=1,
169
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
170
+ )
171
+ parser.add_argument(
172
+ "--gradient_checkpointing",
173
+ action="store_true",
174
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
175
+ )
176
+ parser.add_argument(
177
+ "--learning_rate",
178
+ type=float,
179
+ default=5e-6,
180
+ help="Initial learning rate (after the potential warmup period) to use.",
181
+ )
182
+ parser.add_argument(
183
+ "--scale_lr",
184
+ action="store_true",
185
+ default=False,
186
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
187
+ )
188
+ parser.add_argument(
189
+ "--lr_scheduler",
190
+ type=str,
191
+ default="constant",
192
+ help=(
193
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
194
+ ' "constant", "constant_with_warmup"]'
195
+ ),
196
+ )
197
+ parser.add_argument(
198
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
199
+ )
200
+ parser.add_argument(
201
+ "--lr_num_cycles",
202
+ type=int,
203
+ default=1,
204
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
205
+ )
206
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
207
+ parser.add_argument(
208
+ "--dataloader_num_workers",
209
+ type=int,
210
+ default=0,
211
+ help=(
212
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
213
+ ),
214
+ )
215
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
216
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
217
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
218
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
219
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
220
+ parser.add_argument(
221
+ "--logging_dir",
222
+ type=str,
223
+ default="logs",
224
+ help=(
225
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
226
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
227
+ ),
228
+ )
229
+ parser.add_argument(
230
+ "--allow_tf32",
231
+ action="store_true",
232
+ help=(
233
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
234
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
235
+ ),
236
+ )
237
+ parser.add_argument(
238
+ "--report_to",
239
+ type=str,
240
+ default="tensorboard",
241
+ help=(
242
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
243
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
244
+ ),
245
+ )
246
+ parser.add_argument(
247
+ "--mixed_precision",
248
+ type=str,
249
+ default=None,
250
+ choices=["no", "fp16", "bf16"],
251
+ help=(
252
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
253
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
254
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
255
+ ),
256
+ )
257
+ parser.add_argument(
258
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
259
+ )
260
+ parser.add_argument(
261
+ "--set_grads_to_none",
262
+ action="store_true",
263
+ help=(
264
+ "Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
265
+ " behaviors, so disable this argument if it causes any problems. More info:"
266
+ " https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
267
+ ),
268
+ )
269
+ parser.add_argument(
270
+ "--tracker_project_name",
271
+ type=str,
272
+ default="train_controlnet",
273
+ help=(
274
+ "The `project_name` argument passed to Accelerator.init_trackers for"
275
+ " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
276
+ ),
277
+ )
278
+ args = parser.parse_args()
279
+ return args
280
+
281
+
282
+ def main(args):
283
+ logging_dir = Path(args.output_dir, args.logging_dir)
284
+
285
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
286
+
287
+ accelerator = Accelerator(
288
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
289
+ mixed_precision=args.mixed_precision,
290
+ log_with=args.report_to,
291
+ project_config=accelerator_project_config,
292
+ )
293
+
294
+ # Disable AMP for MPS.
295
+ if torch.backends.mps.is_available():
296
+ accelerator.native_amp = False
297
+
298
+ # Make one log on every process with the configuration for debugging.
299
+ logging.basicConfig(
300
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
301
+ datefmt="%m/%d/%Y %H:%M:%S",
302
+ level=logging.INFO,
303
+ )
304
+ logger.info(accelerator.state, main_process_only=False)
305
+ if accelerator.is_local_main_process:
306
+ transformers.utils.logging.set_verbosity_warning()
307
+ diffusers.utils.logging.set_verbosity_info()
308
+ else:
309
+ transformers.utils.logging.set_verbosity_error()
310
+ diffusers.utils.logging.set_verbosity_error()
311
+
312
+ # If passed along, set the training seed now.
313
+ if args.seed is not None:
314
+ set_seed(args.seed)
315
+
316
+ # Handle the repository creation
317
+ if accelerator.is_main_process:
318
+ if args.output_dir is not None:
319
+ os.makedirs(args.output_dir, exist_ok=True)
320
+
321
+ # import correct text encoder class
322
+ # text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
323
+ # Load scheduler and models
324
+ from transformers import CLIPTextModel, CLIPTokenizer
325
+
326
+ pretrained_model_name_or_path = "masterful/gligen-1-4-generation-text-box"
327
+ tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer")
328
+ noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
329
+ text_encoder = CLIPTextModel.from_pretrained(pretrained_model_name_or_path, subfolder="text_encoder")
330
+
331
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
332
+ unet = UNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, subfolder="unet")
333
+
334
+ # Taken from [Sayak Paul's Diffusers PR #6511](https://github.com/huggingface/diffusers/pull/6511/files)
335
+ def unwrap_model(model):
336
+ model = accelerator.unwrap_model(model)
337
+ model = model._orig_mod if is_compiled_module(model) else model
338
+ return model
339
+
340
+ # `accelerate` 0.16.0 will have better support for customized saving
341
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
342
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
343
+ def save_model_hook(models, weights, output_dir):
344
+ if accelerator.is_main_process:
345
+ i = len(weights) - 1
346
+
347
+ while len(weights) > 0:
348
+ weights.pop()
349
+ model = models[i]
350
+
351
+ sub_dir = "unet"
352
+ model.save_pretrained(os.path.join(output_dir, sub_dir))
353
+
354
+ i -= 1
355
+
356
+ def load_model_hook(models, input_dir):
357
+ while len(models) > 0:
358
+ # pop models so that they are not loaded again
359
+ model = models.pop()
360
+
361
+ # load diffusers style into model
362
+ load_model = unet.from_pretrained(input_dir, subfolder="unet")
363
+ model.register_to_config(**load_model.config)
364
+
365
+ model.load_state_dict(load_model.state_dict())
366
+ del load_model
367
+
368
+ accelerator.register_save_state_pre_hook(save_model_hook)
369
+ accelerator.register_load_state_pre_hook(load_model_hook)
370
+
371
+ vae.requires_grad_(False)
372
+ unet.requires_grad_(False)
373
+ text_encoder.requires_grad_(False)
374
+
375
+ if args.enable_xformers_memory_efficient_attention:
376
+ if is_xformers_available():
377
+ import xformers
378
+
379
+ xformers_version = version.parse(xformers.__version__)
380
+ if xformers_version == version.parse("0.0.16"):
381
+ logger.warning(
382
+ "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."
383
+ )
384
+ unet.enable_xformers_memory_efficient_attention()
385
+ # controlnet.enable_xformers_memory_efficient_attention()
386
+ else:
387
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
388
+
389
+ # if args.gradient_checkpointing:
390
+ # controlnet.enable_gradient_checkpointing()
391
+
392
+ # Check that all trainable models are in full precision
393
+ low_precision_error_string = (
394
+ " Please make sure to always have all model weights in full float32 precision when starting training - even if"
395
+ " doing mixed precision training, copy of the weights should still be float32."
396
+ )
397
+
398
+ if unwrap_model(unet).dtype != torch.float32:
399
+ raise ValueError(f"Controlnet loaded as datatype {unwrap_model(unet).dtype}. {low_precision_error_string}")
400
+
401
+ # Enable TF32 for faster training on Ampere GPUs,
402
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
403
+ if args.allow_tf32:
404
+ torch.backends.cuda.matmul.allow_tf32 = True
405
+
406
+ if args.scale_lr:
407
+ args.learning_rate = (
408
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
409
+ )
410
+
411
+ optimizer_class = torch.optim.AdamW
412
+ # Optimizer creation
413
+ for n, m in unet.named_modules():
414
+ if ("fuser" in n) or ("position_net" in n):
415
+ import torch.nn as nn
416
+
417
+ if isinstance(m, (nn.Linear, nn.LayerNorm)):
418
+ m.reset_parameters()
419
+ params_to_optimize = []
420
+ for n, p in unet.named_parameters():
421
+ if ("fuser" in n) or ("position_net" in n):
422
+ p.requires_grad = True
423
+ params_to_optimize.append(p)
424
+ optimizer = optimizer_class(
425
+ params_to_optimize,
426
+ lr=args.learning_rate,
427
+ betas=(args.adam_beta1, args.adam_beta2),
428
+ weight_decay=args.adam_weight_decay,
429
+ eps=args.adam_epsilon,
430
+ )
431
+
432
+ from dataset import COCODataset
433
+
434
+ train_dataset = COCODataset(
435
+ data_path=args.data_path,
436
+ image_path=args.image_path,
437
+ tokenizer=tokenizer,
438
+ image_size=args.resolution,
439
+ max_boxes_per_data=30,
440
+ )
441
+
442
+ print("num samples: ", len(train_dataset))
443
+
444
+ train_dataloader = torch.utils.data.DataLoader(
445
+ train_dataset,
446
+ shuffle=True,
447
+ # collate_fn=collate_fn,
448
+ batch_size=args.train_batch_size,
449
+ num_workers=args.dataloader_num_workers,
450
+ )
451
+
452
+ # Scheduler and math around the number of training steps.
453
+ overrode_max_train_steps = False
454
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
455
+ if args.max_train_steps is None:
456
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
457
+ overrode_max_train_steps = True
458
+
459
+ lr_scheduler = get_scheduler(
460
+ args.lr_scheduler,
461
+ optimizer=optimizer,
462
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
463
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
464
+ num_cycles=args.lr_num_cycles,
465
+ power=args.lr_power,
466
+ )
467
+
468
+ # Prepare everything with our `accelerator`.
469
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
470
+ unet, optimizer, train_dataloader, lr_scheduler
471
+ )
472
+
473
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
474
+ # as these models are only used for inference, keeping weights in full precision is not required.
475
+ weight_dtype = torch.float32
476
+ if accelerator.mixed_precision == "fp16":
477
+ weight_dtype = torch.float16
478
+ elif accelerator.mixed_precision == "bf16":
479
+ weight_dtype = torch.bfloat16
480
+
481
+ # Move vae, unet and text_encoder to device and cast to weight_dtype
482
+ vae.to(accelerator.device, dtype=weight_dtype)
483
+ # unet.to(accelerator.device, dtype=weight_dtype)
484
+ unet.to(accelerator.device, dtype=torch.float32)
485
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
486
+
487
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
488
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
489
+ if overrode_max_train_steps:
490
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
491
+ # Afterwards we recalculate our number of training epochs
492
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
493
+
494
+ # We need to initialize the trackers we use, and also store our configuration.
495
+ # The trackers initializes automatically on the main process.
496
+ if accelerator.is_main_process:
497
+ tracker_config = dict(vars(args))
498
+
499
+ # tensorboard cannot handle list types for config
500
+ # tracker_config.pop("validation_prompt")
501
+ # tracker_config.pop("validation_image")
502
+
503
+ accelerator.init_trackers(args.tracker_project_name, config=tracker_config)
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 examples = {len(train_dataset)}")
510
+ # logger.info(f" Num batches each epoch = {len(train_dataloader)}")
511
+ # logger.info(f" Num Epochs = {args.num_train_epochs}")
512
+ # logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
513
+ # logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
514
+ # logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
515
+ # logger.info(f" Total optimization steps = {args.max_train_steps}")
516
+ global_step = 0
517
+ first_epoch = 0
518
+
519
+ # Potentially load in the weights and states from a previous save
520
+ if args.resume_from_checkpoint:
521
+ if args.resume_from_checkpoint != "latest":
522
+ path = os.path.basename(args.resume_from_checkpoint)
523
+ else:
524
+ # Get the most recent checkpoint
525
+ dirs = os.listdir(args.output_dir)
526
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
527
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
528
+ path = dirs[-1] if len(dirs) > 0 else None
529
+
530
+ if path is None:
531
+ accelerator.print(
532
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
533
+ )
534
+ args.resume_from_checkpoint = None
535
+ initial_global_step = 0
536
+ else:
537
+ accelerator.print(f"Resuming from checkpoint {path}")
538
+ accelerator.load_state(os.path.join(args.output_dir, path))
539
+ global_step = int(path.split("-")[1])
540
+
541
+ initial_global_step = global_step
542
+ first_epoch = global_step // num_update_steps_per_epoch
543
+ else:
544
+ initial_global_step = 0
545
+
546
+ progress_bar = tqdm(
547
+ range(0, args.max_train_steps),
548
+ initial=initial_global_step,
549
+ desc="Steps",
550
+ # Only show the progress bar once on each machine.
551
+ disable=not accelerator.is_local_main_process,
552
+ )
553
+
554
+ log_validation(
555
+ vae,
556
+ text_encoder,
557
+ tokenizer,
558
+ unet,
559
+ noise_scheduler,
560
+ args,
561
+ accelerator,
562
+ global_step,
563
+ weight_dtype,
564
+ )
565
+
566
+ # image_logs = None
567
+ for epoch in range(first_epoch, args.num_train_epochs):
568
+ for step, batch in enumerate(train_dataloader):
569
+ with accelerator.accumulate(unet):
570
+ # Convert images to latent space
571
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
572
+ latents = latents * vae.config.scaling_factor
573
+
574
+ # Sample noise that we'll add to the latents
575
+ noise = torch.randn_like(latents)
576
+ bsz = latents.shape[0]
577
+ # Sample a random timestep for each image
578
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
579
+ timesteps = timesteps.long()
580
+
581
+ # Add noise to the latents according to the noise magnitude at each timestep
582
+ # (this is the forward diffusion process)
583
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
584
+
585
+ with torch.no_grad():
586
+ # Get the text embedding for conditioning
587
+ encoder_hidden_states = text_encoder(
588
+ batch["caption"]["input_ids"].squeeze(1),
589
+ # batch['caption']['attention_mask'].squeeze(1),
590
+ return_dict=False,
591
+ )[0]
592
+
593
+ cross_attention_kwargs = {}
594
+ cross_attention_kwargs["gligen"] = {
595
+ "boxes": batch["boxes"],
596
+ "positive_embeddings": batch["text_embeddings_before_projection"],
597
+ "masks": batch["masks"],
598
+ }
599
+ # Predict the noise residual
600
+ model_pred = unet(
601
+ noisy_latents,
602
+ timesteps,
603
+ encoder_hidden_states=encoder_hidden_states,
604
+ cross_attention_kwargs=cross_attention_kwargs,
605
+ return_dict=False,
606
+ )[0]
607
+
608
+ # Get the target for loss depending on the prediction type
609
+ if noise_scheduler.config.prediction_type == "epsilon":
610
+ target = noise
611
+ elif noise_scheduler.config.prediction_type == "v_prediction":
612
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
613
+ else:
614
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
615
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
616
+
617
+ accelerator.backward(loss)
618
+ if accelerator.sync_gradients:
619
+ accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
620
+ optimizer.step()
621
+ lr_scheduler.step()
622
+ optimizer.zero_grad(set_to_none=args.set_grads_to_none)
623
+
624
+ # Checks if the accelerator has performed an optimization step behind the scenes
625
+ if accelerator.sync_gradients:
626
+ progress_bar.update(1)
627
+ global_step += 1
628
+
629
+ if global_step % args.checkpointing_steps == 0:
630
+ if accelerator.is_main_process:
631
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
632
+ if args.checkpoints_total_limit is not None:
633
+ checkpoints = os.listdir(args.output_dir)
634
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
635
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
636
+
637
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
638
+ if len(checkpoints) >= args.checkpoints_total_limit:
639
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
640
+ removing_checkpoints = checkpoints[0:num_to_remove]
641
+
642
+ logger.info(
643
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
644
+ )
645
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
646
+
647
+ for removing_checkpoint in removing_checkpoints:
648
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
649
+ shutil.rmtree(removing_checkpoint)
650
+
651
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step:06d}")
652
+ accelerator.save_state(save_path)
653
+ logger.info(f"Saved state to {save_path}")
654
+
655
+ # if args.validation_prompt is not None and global_step % args.validation_steps == 0:
656
+ log_validation(
657
+ vae,
658
+ text_encoder,
659
+ tokenizer,
660
+ unet,
661
+ noise_scheduler,
662
+ args,
663
+ accelerator,
664
+ global_step,
665
+ weight_dtype,
666
+ )
667
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
668
+ progress_bar.set_postfix(**logs)
669
+ accelerator.log(logs, step=global_step)
670
+
671
+ if global_step >= args.max_train_steps:
672
+ break
673
+
674
+ # Create the pipeline using using the trained modules and save it.
675
+ accelerator.wait_for_everyone()
676
+ if accelerator.is_main_process:
677
+ unet = unwrap_model(unet)
678
+ unet.save_pretrained(args.output_dir)
679
+ #
680
+ # # Run a final round of validation.
681
+ # image_logs = None
682
+ # if args.validation_prompt is not None:
683
+ # image_logs = log_validation(
684
+ # vae=vae,
685
+ # text_encoder=text_encoder,
686
+ # tokenizer=tokenizer,
687
+ # unet=unet,
688
+ # controlnet=None,
689
+ # args=args,
690
+ # accelerator=accelerator,
691
+ # weight_dtype=weight_dtype,
692
+ # step=global_step,
693
+ # is_final_validation=True,
694
+ # )
695
+ #
696
+ # if args.push_to_hub:
697
+ # save_model_card(
698
+ # repo_id,
699
+ # image_logs=image_logs,
700
+ # base_model=args.pretrained_model_name_or_path,
701
+ # repo_folder=args.output_dir,
702
+ # )
703
+ # upload_folder(
704
+ # repo_id=repo_id,
705
+ # folder_path=args.output_dir,
706
+ # commit_message="End of training",
707
+ # ignore_patterns=["step_*", "epoch_*"],
708
+ # )
709
+
710
+ accelerator.end_training()
711
+
712
+
713
+ if __name__ == "__main__":
714
+ args = parse_args()
715
+ main(args)
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/instructpix2pix_lora/README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InstructPix2Pix text-to-edit-image fine-tuning
2
+ This extended LoRA training script was authored by [Aiden-Frost](https://github.com/Aiden-Frost).
3
+ This is an experimental LoRA extension of [this example](https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix.py). This script provides further support add LoRA layers for unet model.
4
+
5
+ ## Running locally with PyTorch
6
+ ### Installing the dependencies
7
+
8
+ Before running the scripts, make sure to install the library's training dependencies:
9
+
10
+ **Important**
11
+
12
+ 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:
13
+ ```bash
14
+ git clone https://github.com/huggingface/diffusers
15
+ cd diffusers
16
+ pip install .
17
+ ```
18
+
19
+ Then cd in the example folder and run
20
+ ```bash
21
+ pip install -r requirements.txt
22
+ ```
23
+
24
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
25
+
26
+ ```bash
27
+ accelerate config
28
+ ```
29
+
30
+ Note also that we use PEFT library as backend for LoRA training, make sure to have `peft>=0.6.0` installed in your environment.
31
+
32
+
33
+ ## Training script example
34
+
35
+ ```bash
36
+ export MODEL_ID="timbrooks/instruct-pix2pix"
37
+ export DATASET_ID="instruction-tuning-sd/cartoonization"
38
+ export OUTPUT_DIR="instructPix2Pix-cartoonization"
39
+
40
+ accelerate launch train_instruct_pix2pix_lora.py \
41
+ --pretrained_model_name_or_path=$MODEL_ID \
42
+ --dataset_name=$DATASET_ID \
43
+ --enable_xformers_memory_efficient_attention \
44
+ --resolution=256 --random_flip \
45
+ --train_batch_size=2 --gradient_accumulation_steps=4 --gradient_checkpointing \
46
+ --max_train_steps=15000 \
47
+ --checkpointing_steps=5000 --checkpoints_total_limit=1 \
48
+ --learning_rate=5e-05 --lr_warmup_steps=0 \
49
+ --val_image_url="https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png" \
50
+ --validation_prompt="Generate a cartoonized version of the natural image" \
51
+ --seed=42 \
52
+ --rank=4 \
53
+ --output_dir=$OUTPUT_DIR \
54
+ --report_to=wandb \
55
+ --push_to_hub \
56
+ --original_image_column="original_image" \
57
+ --edited_image_column="cartoonized_image" \
58
+ --edit_prompt_column="edit_prompt"
59
+ ```
60
+
61
+ ## Inference
62
+ After training the model and the lora weight of the model is stored in the ```$OUTPUT_DIR```.
63
+
64
+ ```py
65
+ # load the base model pipeline
66
+ pipe_lora = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix")
67
+
68
+ # Load LoRA weights from the provided path
69
+ output_dir = "path/to/lora_weight_directory"
70
+ pipe_lora.unet.load_attn_procs(output_dir)
71
+
72
+ input_image_path = "/path/to/input_image"
73
+ input_image = Image.open(input_image_path)
74
+ edited_images = pipe_lora(num_images_per_prompt=1, prompt=args.edit_prompt, image=input_image, num_inference_steps=1000).images
75
+ edited_images[0].show()
76
+ ```
77
+
78
+ ## Results
79
+
80
+ Here is an example of using the script to train a instructpix2pix model.
81
+ Trained on google colab T4 GPU
82
+
83
+ ```bash
84
+ MODEL_ID="timbrooks/instruct-pix2pix"
85
+ DATASET_ID="instruction-tuning-sd/cartoonization"
86
+ TRAIN_EPOCHS=100
87
+ ```
88
+
89
+ Below are few examples for given the input image, edit_prompt and the edited_image (output of the model)
90
+
91
+ <p align="center">
92
+ <img src="https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-/blob/main/diffusers_result_assets/edited_image_results.png?raw=true" alt="instructpix2pix-inputs" width=600/>
93
+ </p>
94
+
95
+
96
+ Here are some rough statistics about the training model using this script
97
+
98
+ <p align="center">
99
+ <img src="https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-/blob/main/diffusers_result_assets/results.png?raw=true" alt="instructpix2pix-inputs" width=600/>
100
+ </p>
101
+
102
+ ## References
103
+
104
+ * InstructPix2Pix - https://github.com/timothybrooks/instruct-pix2pix
105
+ * Dataset and example training script - https://huggingface.co/blog/instruction-tuning-sd
106
+ * For more information about the project - https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/instructpix2pix_lora/train_instruct_pix2pix_lora.py ADDED
@@ -0,0 +1,1171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
18
+ Script to fine-tune Stable Diffusion for LORA InstructPix2Pix.
19
+ Base code referred from: https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix.py
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import math
25
+ import os
26
+ import shutil
27
+ from contextlib import nullcontext
28
+ from pathlib import Path
29
+
30
+ import accelerate
31
+ import datasets
32
+ import numpy as np
33
+ import PIL
34
+ import requests
35
+ import torch
36
+ import torch.nn as nn
37
+ import torch.nn.functional as F
38
+ import torch.utils.checkpoint
39
+ import transformers
40
+ from accelerate import Accelerator
41
+ from accelerate.logging import get_logger
42
+ from accelerate.utils import ProjectConfiguration, set_seed
43
+ from datasets import load_dataset
44
+ from huggingface_hub import create_repo, upload_folder
45
+ from packaging import version
46
+ from peft import LoraConfig
47
+ from peft.utils import get_peft_model_state_dict
48
+ from torchvision import transforms
49
+ from tqdm.auto import tqdm
50
+ from transformers import CLIPTextModel, CLIPTokenizer
51
+
52
+ import diffusers
53
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionInstructPix2PixPipeline, UNet2DConditionModel
54
+ from diffusers.optimization import get_scheduler
55
+ from diffusers.training_utils import EMAModel, cast_training_params
56
+ from diffusers.utils import check_min_version, convert_state_dict_to_diffusers, deprecate, is_wandb_available
57
+ from diffusers.utils.constants import DIFFUSERS_REQUEST_TIMEOUT
58
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
59
+ from diffusers.utils.import_utils import is_xformers_available
60
+ from diffusers.utils.torch_utils import is_compiled_module
61
+
62
+
63
+ if is_wandb_available():
64
+ import wandb
65
+
66
+
67
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
68
+ check_min_version("0.32.0.dev0")
69
+
70
+ logger = get_logger(__name__, log_level="INFO")
71
+
72
+ DATASET_NAME_MAPPING = {
73
+ "fusing/instructpix2pix-1000-samples": ("input_image", "edit_prompt", "edited_image"),
74
+ }
75
+ WANDB_TABLE_COL_NAMES = ["original_image", "edited_image", "edit_prompt"]
76
+
77
+
78
+ def save_model_card(
79
+ repo_id: str,
80
+ images: list = None,
81
+ base_model: str = None,
82
+ dataset_name: str = None,
83
+ repo_folder: str = None,
84
+ ):
85
+ img_str = ""
86
+ if images is not None:
87
+ for i, image in enumerate(images):
88
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
89
+ img_str += f"![img_{i}](./image_{i}.png)\n"
90
+
91
+ model_description = f"""
92
+ # LoRA text2image fine-tuning - {repo_id}
93
+ 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
94
+ {img_str}
95
+ """
96
+
97
+ model_card = load_or_create_model_card(
98
+ repo_id_or_path=repo_id,
99
+ from_training=True,
100
+ license="creativeml-openrail-m",
101
+ base_model=base_model,
102
+ model_description=model_description,
103
+ inference=True,
104
+ )
105
+
106
+ tags = [
107
+ "stable-diffusion",
108
+ "stable-diffusion-diffusers",
109
+ "text-to-image",
110
+ "instruct-pix2pix",
111
+ "diffusers",
112
+ "diffusers-training",
113
+ "lora",
114
+ ]
115
+ model_card = populate_model_card(model_card, tags=tags)
116
+
117
+ model_card.save(os.path.join(repo_folder, "README.md"))
118
+
119
+
120
+ def log_validation(
121
+ pipeline,
122
+ args,
123
+ accelerator,
124
+ generator,
125
+ ):
126
+ logger.info(
127
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
128
+ f" {args.validation_prompt}."
129
+ )
130
+ pipeline = pipeline.to(accelerator.device)
131
+ pipeline.set_progress_bar_config(disable=True)
132
+
133
+ # run inference
134
+ original_image = download_image(args.val_image_url)
135
+ edited_images = []
136
+ if torch.backends.mps.is_available():
137
+ autocast_ctx = nullcontext()
138
+ else:
139
+ autocast_ctx = torch.autocast(accelerator.device.type)
140
+
141
+ with autocast_ctx:
142
+ for _ in range(args.num_validation_images):
143
+ edited_images.append(
144
+ pipeline(
145
+ args.validation_prompt,
146
+ image=original_image,
147
+ num_inference_steps=20,
148
+ image_guidance_scale=1.5,
149
+ guidance_scale=7,
150
+ generator=generator,
151
+ ).images[0]
152
+ )
153
+
154
+ for tracker in accelerator.trackers:
155
+ if tracker.name == "wandb":
156
+ wandb_table = wandb.Table(columns=WANDB_TABLE_COL_NAMES)
157
+ for edited_image in edited_images:
158
+ wandb_table.add_data(wandb.Image(original_image), wandb.Image(edited_image), args.validation_prompt)
159
+ tracker.log({"validation": wandb_table})
160
+
161
+ return edited_images
162
+
163
+
164
+ def parse_args():
165
+ parser = argparse.ArgumentParser(description="Simple example of a training script for InstructPix2Pix.")
166
+ parser.add_argument(
167
+ "--pretrained_model_name_or_path",
168
+ type=str,
169
+ default=None,
170
+ required=True,
171
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
172
+ )
173
+ parser.add_argument(
174
+ "--revision",
175
+ type=str,
176
+ default=None,
177
+ required=False,
178
+ help="Revision of pretrained model identifier from huggingface.co/models.",
179
+ )
180
+ parser.add_argument(
181
+ "--variant",
182
+ type=str,
183
+ default=None,
184
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
185
+ )
186
+ parser.add_argument(
187
+ "--dataset_name",
188
+ type=str,
189
+ default=None,
190
+ help=(
191
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
192
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
193
+ " or to a folder containing files that 🤗 Datasets can understand."
194
+ ),
195
+ )
196
+ parser.add_argument(
197
+ "--dataset_config_name",
198
+ type=str,
199
+ default=None,
200
+ help="The config of the Dataset, leave as None if there's only one config.",
201
+ )
202
+ parser.add_argument(
203
+ "--train_data_dir",
204
+ type=str,
205
+ default=None,
206
+ help=(
207
+ "A folder containing the training data. Folder contents must follow the structure described in"
208
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
209
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
210
+ ),
211
+ )
212
+ parser.add_argument(
213
+ "--original_image_column",
214
+ type=str,
215
+ default="input_image",
216
+ help="The column of the dataset containing the original image on which edits where made.",
217
+ )
218
+ parser.add_argument(
219
+ "--edited_image_column",
220
+ type=str,
221
+ default="edited_image",
222
+ help="The column of the dataset containing the edited image.",
223
+ )
224
+ parser.add_argument(
225
+ "--edit_prompt_column",
226
+ type=str,
227
+ default="edit_prompt",
228
+ help="The column of the dataset containing the edit instruction.",
229
+ )
230
+ parser.add_argument(
231
+ "--val_image_url",
232
+ type=str,
233
+ default=None,
234
+ help="URL to the original image that you would like to edit (used during inference for debugging purposes).",
235
+ )
236
+ parser.add_argument(
237
+ "--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
238
+ )
239
+ parser.add_argument(
240
+ "--num_validation_images",
241
+ type=int,
242
+ default=4,
243
+ help="Number of images that should be generated during validation with `validation_prompt`.",
244
+ )
245
+ parser.add_argument(
246
+ "--validation_epochs",
247
+ type=int,
248
+ default=1,
249
+ help=(
250
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
251
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
252
+ ),
253
+ )
254
+ parser.add_argument(
255
+ "--max_train_samples",
256
+ type=int,
257
+ default=None,
258
+ help=(
259
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
260
+ "value if set."
261
+ ),
262
+ )
263
+ parser.add_argument(
264
+ "--output_dir",
265
+ type=str,
266
+ default="instruct-pix2pix-model",
267
+ help="The output directory where the model predictions and checkpoints will be written.",
268
+ )
269
+ parser.add_argument(
270
+ "--cache_dir",
271
+ type=str,
272
+ default=None,
273
+ help="The directory where the downloaded models and datasets will be stored.",
274
+ )
275
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
276
+ parser.add_argument(
277
+ "--resolution",
278
+ type=int,
279
+ default=256,
280
+ help=(
281
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
282
+ " resolution"
283
+ ),
284
+ )
285
+ parser.add_argument(
286
+ "--center_crop",
287
+ default=False,
288
+ action="store_true",
289
+ help=(
290
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
291
+ " cropped. The images will be resized to the resolution first before cropping."
292
+ ),
293
+ )
294
+ parser.add_argument(
295
+ "--random_flip",
296
+ action="store_true",
297
+ help="whether to randomly flip images horizontally",
298
+ )
299
+ parser.add_argument(
300
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
301
+ )
302
+ parser.add_argument("--num_train_epochs", type=int, default=100)
303
+ parser.add_argument(
304
+ "--max_train_steps",
305
+ type=int,
306
+ default=None,
307
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
308
+ )
309
+ parser.add_argument(
310
+ "--gradient_accumulation_steps",
311
+ type=int,
312
+ default=1,
313
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
314
+ )
315
+ parser.add_argument(
316
+ "--gradient_checkpointing",
317
+ action="store_true",
318
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
319
+ )
320
+ parser.add_argument(
321
+ "--learning_rate",
322
+ type=float,
323
+ default=1e-4,
324
+ help="Initial learning rate (after the potential warmup period) to use.",
325
+ )
326
+ parser.add_argument(
327
+ "--scale_lr",
328
+ action="store_true",
329
+ default=False,
330
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
331
+ )
332
+ parser.add_argument(
333
+ "--lr_scheduler",
334
+ type=str,
335
+ default="constant",
336
+ help=(
337
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
338
+ ' "constant", "constant_with_warmup"]'
339
+ ),
340
+ )
341
+ parser.add_argument(
342
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
343
+ )
344
+ parser.add_argument(
345
+ "--conditioning_dropout_prob",
346
+ type=float,
347
+ default=None,
348
+ help="Conditioning dropout probability. Drops out the conditionings (image and edit prompt) used in training InstructPix2Pix. See section 3.2.1 in the paper: https://huggingface.co/papers/2211.09800.",
349
+ )
350
+ parser.add_argument(
351
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
352
+ )
353
+ parser.add_argument(
354
+ "--allow_tf32",
355
+ action="store_true",
356
+ help=(
357
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
358
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
359
+ ),
360
+ )
361
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
362
+ parser.add_argument(
363
+ "--non_ema_revision",
364
+ type=str,
365
+ default=None,
366
+ required=False,
367
+ help=(
368
+ "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
369
+ " remote repository specified with --pretrained_model_name_or_path."
370
+ ),
371
+ )
372
+ parser.add_argument(
373
+ "--dataloader_num_workers",
374
+ type=int,
375
+ default=0,
376
+ help=(
377
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
378
+ ),
379
+ )
380
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
381
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
382
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
383
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
384
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
385
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
386
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
387
+ parser.add_argument(
388
+ "--hub_model_id",
389
+ type=str,
390
+ default=None,
391
+ help="The name of the repository to keep in sync with the local `output_dir`.",
392
+ )
393
+ parser.add_argument(
394
+ "--logging_dir",
395
+ type=str,
396
+ default="logs",
397
+ help=(
398
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
399
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
400
+ ),
401
+ )
402
+ parser.add_argument(
403
+ "--mixed_precision",
404
+ type=str,
405
+ default=None,
406
+ choices=["no", "fp16", "bf16"],
407
+ help=(
408
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
409
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
410
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
411
+ ),
412
+ )
413
+ parser.add_argument(
414
+ "--report_to",
415
+ type=str,
416
+ default="tensorboard",
417
+ help=(
418
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
419
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
420
+ ),
421
+ )
422
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
423
+ parser.add_argument(
424
+ "--checkpointing_steps",
425
+ type=int,
426
+ default=500,
427
+ help=(
428
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
429
+ " training using `--resume_from_checkpoint`."
430
+ ),
431
+ )
432
+ parser.add_argument(
433
+ "--checkpoints_total_limit",
434
+ type=int,
435
+ default=None,
436
+ help=("Max number of checkpoints to store."),
437
+ )
438
+ parser.add_argument(
439
+ "--resume_from_checkpoint",
440
+ type=str,
441
+ default=None,
442
+ help=(
443
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
444
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
445
+ ),
446
+ )
447
+ parser.add_argument(
448
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
449
+ )
450
+ parser.add_argument(
451
+ "--rank",
452
+ type=int,
453
+ default=4,
454
+ help=("The dimension of the LoRA update matrices."),
455
+ )
456
+
457
+ args = parser.parse_args()
458
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
459
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
460
+ args.local_rank = env_local_rank
461
+
462
+ # Sanity checks
463
+ if args.dataset_name is None and args.train_data_dir is None:
464
+ raise ValueError("Need either a dataset name or a training folder.")
465
+
466
+ # default to using the same revision for the non-ema model if not specified
467
+ if args.non_ema_revision is None:
468
+ args.non_ema_revision = args.revision
469
+
470
+ return args
471
+
472
+
473
+ def convert_to_np(image, resolution):
474
+ image = image.convert("RGB").resize((resolution, resolution))
475
+ return np.array(image).transpose(2, 0, 1)
476
+
477
+
478
+ def download_image(url):
479
+ image = PIL.Image.open(requests.get(url, stream=True, timeout=DIFFUSERS_REQUEST_TIMEOUT).raw)
480
+ image = PIL.ImageOps.exif_transpose(image)
481
+ image = image.convert("RGB")
482
+ return image
483
+
484
+
485
+ def main():
486
+ args = parse_args()
487
+
488
+ if args.report_to == "wandb" and args.hub_token is not None:
489
+ raise ValueError(
490
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
491
+ " Please use `hf auth login` to authenticate with the Hub."
492
+ )
493
+
494
+ if args.non_ema_revision is not None:
495
+ deprecate(
496
+ "non_ema_revision!=None",
497
+ "0.15.0",
498
+ message=(
499
+ "Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
500
+ " use `--variant=non_ema` instead."
501
+ ),
502
+ )
503
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
504
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
505
+ accelerator = Accelerator(
506
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
507
+ mixed_precision=args.mixed_precision,
508
+ log_with=args.report_to,
509
+ project_config=accelerator_project_config,
510
+ )
511
+
512
+ # Disable AMP for MPS.
513
+ if torch.backends.mps.is_available():
514
+ accelerator.native_amp = False
515
+
516
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
517
+
518
+ # Make one log on every process with the configuration for debugging.
519
+ logging.basicConfig(
520
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
521
+ datefmt="%m/%d/%Y %H:%M:%S",
522
+ level=logging.INFO,
523
+ )
524
+ logger.info(accelerator.state, main_process_only=False)
525
+ if accelerator.is_local_main_process:
526
+ datasets.utils.logging.set_verbosity_warning()
527
+ transformers.utils.logging.set_verbosity_warning()
528
+ diffusers.utils.logging.set_verbosity_info()
529
+ else:
530
+ datasets.utils.logging.set_verbosity_error()
531
+ transformers.utils.logging.set_verbosity_error()
532
+ diffusers.utils.logging.set_verbosity_error()
533
+
534
+ # If passed along, set the training seed now.
535
+ if args.seed is not None:
536
+ set_seed(args.seed)
537
+
538
+ # Handle the repository creation
539
+ if accelerator.is_main_process:
540
+ if args.output_dir is not None:
541
+ os.makedirs(args.output_dir, exist_ok=True)
542
+
543
+ if args.push_to_hub:
544
+ repo_id = create_repo(
545
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
546
+ ).repo_id
547
+
548
+ # Load scheduler, tokenizer and models.
549
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
550
+ tokenizer = CLIPTokenizer.from_pretrained(
551
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
552
+ )
553
+ text_encoder = CLIPTextModel.from_pretrained(
554
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
555
+ )
556
+ vae = AutoencoderKL.from_pretrained(
557
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
558
+ )
559
+ unet = UNet2DConditionModel.from_pretrained(
560
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision
561
+ )
562
+
563
+ # InstructPix2Pix uses an additional image for conditioning. To accommodate that,
564
+ # it uses 8 channels (instead of 4) in the first (conv) layer of the UNet. This UNet is
565
+ # then fine-tuned on the custom InstructPix2Pix dataset. This modified UNet is initialized
566
+ # from the pre-trained checkpoints. For the extra channels added to the first layer, they are
567
+ # initialized to zero.
568
+ logger.info("Initializing the InstructPix2Pix UNet from the pretrained UNet.")
569
+ in_channels = 8
570
+ out_channels = unet.conv_in.out_channels
571
+ unet.register_to_config(in_channels=in_channels)
572
+
573
+ with torch.no_grad():
574
+ new_conv_in = nn.Conv2d(
575
+ in_channels, out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding
576
+ )
577
+ new_conv_in.weight.zero_()
578
+ new_conv_in.weight[:, :in_channels, :, :].copy_(unet.conv_in.weight)
579
+ unet.conv_in = new_conv_in
580
+
581
+ # Freeze vae, text_encoder and unet
582
+ vae.requires_grad_(False)
583
+ text_encoder.requires_grad_(False)
584
+ unet.requires_grad_(False)
585
+
586
+ # referred to https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py
587
+ # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
588
+ # as these weights are only used for inference, keeping weights in full precision is not required.
589
+ weight_dtype = torch.float32
590
+ if accelerator.mixed_precision == "fp16":
591
+ weight_dtype = torch.float16
592
+ elif accelerator.mixed_precision == "bf16":
593
+ weight_dtype = torch.bfloat16
594
+
595
+ # Freeze the unet parameters before adding adapters
596
+ unet.requires_grad_(False)
597
+
598
+ unet_lora_config = LoraConfig(
599
+ r=args.rank,
600
+ lora_alpha=args.rank,
601
+ init_lora_weights="gaussian",
602
+ target_modules=["to_k", "to_q", "to_v", "to_out.0"],
603
+ )
604
+
605
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
606
+ unet.to(accelerator.device, dtype=weight_dtype)
607
+ vae.to(accelerator.device, dtype=weight_dtype)
608
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
609
+
610
+ # Add adapter and make sure the trainable params are in float32.
611
+ unet.add_adapter(unet_lora_config)
612
+ if args.mixed_precision == "fp16":
613
+ # only upcast trainable parameters (LoRA) into fp32
614
+ cast_training_params(unet, dtype=torch.float32)
615
+
616
+ # Create EMA for the unet.
617
+ if args.use_ema:
618
+ ema_unet = EMAModel(unet.parameters(), model_cls=UNet2DConditionModel, model_config=unet.config)
619
+
620
+ if args.enable_xformers_memory_efficient_attention:
621
+ if is_xformers_available():
622
+ import xformers
623
+
624
+ xformers_version = version.parse(xformers.__version__)
625
+ if xformers_version == version.parse("0.0.16"):
626
+ logger.warning(
627
+ "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."
628
+ )
629
+ unet.enable_xformers_memory_efficient_attention()
630
+ else:
631
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
632
+
633
+ trainable_params = filter(lambda p: p.requires_grad, unet.parameters())
634
+
635
+ def unwrap_model(model):
636
+ model = accelerator.unwrap_model(model)
637
+ model = model._orig_mod if is_compiled_module(model) else model
638
+ return model
639
+
640
+ # `accelerate` 0.16.0 will have better support for customized saving
641
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
642
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
643
+ def save_model_hook(models, weights, output_dir):
644
+ if accelerator.is_main_process:
645
+ if args.use_ema:
646
+ ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
647
+
648
+ for i, model in enumerate(models):
649
+ model.save_pretrained(os.path.join(output_dir, "unet"))
650
+
651
+ # make sure to pop weight so that corresponding model is not saved again
652
+ if weights:
653
+ weights.pop()
654
+
655
+ def load_model_hook(models, input_dir):
656
+ if args.use_ema:
657
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
658
+ ema_unet.load_state_dict(load_model.state_dict())
659
+ ema_unet.to(accelerator.device)
660
+ del load_model
661
+
662
+ for i in range(len(models)):
663
+ # pop models so that they are not loaded again
664
+ model = models.pop()
665
+
666
+ # load diffusers style into model
667
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
668
+ model.register_to_config(**load_model.config)
669
+
670
+ model.load_state_dict(load_model.state_dict())
671
+ del load_model
672
+
673
+ accelerator.register_save_state_pre_hook(save_model_hook)
674
+ accelerator.register_load_state_pre_hook(load_model_hook)
675
+
676
+ if args.gradient_checkpointing:
677
+ unet.enable_gradient_checkpointing()
678
+
679
+ # Enable TF32 for faster training on Ampere GPUs,
680
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
681
+ if args.allow_tf32:
682
+ torch.backends.cuda.matmul.allow_tf32 = True
683
+
684
+ if args.scale_lr:
685
+ args.learning_rate = (
686
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
687
+ )
688
+
689
+ # Initialize the optimizer
690
+ if args.use_8bit_adam:
691
+ try:
692
+ import bitsandbytes as bnb
693
+ except ImportError:
694
+ raise ImportError(
695
+ "Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
696
+ )
697
+
698
+ optimizer_cls = bnb.optim.AdamW8bit
699
+ else:
700
+ optimizer_cls = torch.optim.AdamW
701
+
702
+ # train on only lora_layers
703
+ optimizer = optimizer_cls(
704
+ trainable_params,
705
+ lr=args.learning_rate,
706
+ betas=(args.adam_beta1, args.adam_beta2),
707
+ weight_decay=args.adam_weight_decay,
708
+ eps=args.adam_epsilon,
709
+ )
710
+
711
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
712
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
713
+
714
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
715
+ # download the dataset.
716
+ if args.dataset_name is not None:
717
+ # Downloading and loading a dataset from the hub.
718
+ dataset = load_dataset(
719
+ args.dataset_name,
720
+ args.dataset_config_name,
721
+ cache_dir=args.cache_dir,
722
+ )
723
+ else:
724
+ data_files = {}
725
+ if args.train_data_dir is not None:
726
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
727
+ dataset = load_dataset(
728
+ "imagefolder",
729
+ data_files=data_files,
730
+ cache_dir=args.cache_dir,
731
+ )
732
+ # See more about loading custom images at
733
+ # https://huggingface.co/docs/datasets/main/en/image_load#imagefolder
734
+
735
+ # Preprocessing the datasets.
736
+ # We need to tokenize inputs and targets.
737
+ column_names = dataset["train"].column_names
738
+
739
+ # 6. Get the column names for input/target.
740
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
741
+ if args.original_image_column is None:
742
+ original_image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
743
+ else:
744
+ original_image_column = args.original_image_column
745
+ if original_image_column not in column_names:
746
+ raise ValueError(
747
+ f"--original_image_column' value '{args.original_image_column}' needs to be one of: {', '.join(column_names)}"
748
+ )
749
+ if args.edit_prompt_column is None:
750
+ edit_prompt_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
751
+ else:
752
+ edit_prompt_column = args.edit_prompt_column
753
+ if edit_prompt_column not in column_names:
754
+ raise ValueError(
755
+ f"--edit_prompt_column' value '{args.edit_prompt_column}' needs to be one of: {', '.join(column_names)}"
756
+ )
757
+ if args.edited_image_column is None:
758
+ edited_image_column = dataset_columns[2] if dataset_columns is not None else column_names[2]
759
+ else:
760
+ edited_image_column = args.edited_image_column
761
+ if edited_image_column not in column_names:
762
+ raise ValueError(
763
+ f"--edited_image_column' value '{args.edited_image_column}' needs to be one of: {', '.join(column_names)}"
764
+ )
765
+
766
+ # Preprocessing the datasets.
767
+ # We need to tokenize input captions and transform the images.
768
+ def tokenize_captions(captions):
769
+ inputs = tokenizer(
770
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
771
+ )
772
+ return inputs.input_ids
773
+
774
+ # Preprocessing the datasets.
775
+ train_transforms = transforms.Compose(
776
+ [
777
+ transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
778
+ transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
779
+ ]
780
+ )
781
+
782
+ def preprocess_images(examples):
783
+ original_images = np.concatenate(
784
+ [convert_to_np(image, args.resolution) for image in examples[original_image_column]]
785
+ )
786
+ edited_images = np.concatenate(
787
+ [convert_to_np(image, args.resolution) for image in examples[edited_image_column]]
788
+ )
789
+ # We need to ensure that the original and the edited images undergo the same
790
+ # augmentation transforms.
791
+ images = np.concatenate([original_images, edited_images])
792
+ images = torch.tensor(images)
793
+ images = 2 * (images / 255) - 1
794
+ return train_transforms(images)
795
+
796
+ def preprocess_train(examples):
797
+ # Preprocess images.
798
+ preprocessed_images = preprocess_images(examples)
799
+ # Since the original and edited images were concatenated before
800
+ # applying the transformations, we need to separate them and reshape
801
+ # them accordingly.
802
+ original_images, edited_images = preprocessed_images.chunk(2)
803
+ original_images = original_images.reshape(-1, 3, args.resolution, args.resolution)
804
+ edited_images = edited_images.reshape(-1, 3, args.resolution, args.resolution)
805
+
806
+ # Collate the preprocessed images into the `examples`.
807
+ examples["original_pixel_values"] = original_images
808
+ examples["edited_pixel_values"] = edited_images
809
+
810
+ # Preprocess the captions.
811
+ captions = list(examples[edit_prompt_column])
812
+ examples["input_ids"] = tokenize_captions(captions)
813
+ return examples
814
+
815
+ with accelerator.main_process_first():
816
+ if args.max_train_samples is not None:
817
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
818
+ # Set the training transforms
819
+ train_dataset = dataset["train"].with_transform(preprocess_train)
820
+
821
+ def collate_fn(examples):
822
+ original_pixel_values = torch.stack([example["original_pixel_values"] for example in examples])
823
+ original_pixel_values = original_pixel_values.to(memory_format=torch.contiguous_format).float()
824
+ edited_pixel_values = torch.stack([example["edited_pixel_values"] for example in examples])
825
+ edited_pixel_values = edited_pixel_values.to(memory_format=torch.contiguous_format).float()
826
+ input_ids = torch.stack([example["input_ids"] for example in examples])
827
+ return {
828
+ "original_pixel_values": original_pixel_values,
829
+ "edited_pixel_values": edited_pixel_values,
830
+ "input_ids": input_ids,
831
+ }
832
+
833
+ # DataLoaders creation:
834
+ train_dataloader = torch.utils.data.DataLoader(
835
+ train_dataset,
836
+ shuffle=True,
837
+ collate_fn=collate_fn,
838
+ batch_size=args.train_batch_size,
839
+ num_workers=args.dataloader_num_workers,
840
+ )
841
+
842
+ # Scheduler and math around the number of training steps.
843
+ # Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
844
+ num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
845
+ if args.max_train_steps is None:
846
+ len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
847
+ num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
848
+ num_training_steps_for_scheduler = (
849
+ args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
850
+ )
851
+ else:
852
+ num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
853
+
854
+ lr_scheduler = get_scheduler(
855
+ args.lr_scheduler,
856
+ optimizer=optimizer,
857
+ num_warmup_steps=num_warmup_steps_for_scheduler,
858
+ num_training_steps=num_training_steps_for_scheduler,
859
+ )
860
+
861
+ # Prepare everything with our `accelerator`.
862
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
863
+ unet, optimizer, train_dataloader, lr_scheduler
864
+ )
865
+
866
+ if args.use_ema:
867
+ ema_unet.to(accelerator.device)
868
+
869
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
870
+ # as these models are only used for inference, keeping weights in full precision is not required.
871
+ weight_dtype = torch.float32
872
+ if accelerator.mixed_precision == "fp16":
873
+ weight_dtype = torch.float16
874
+ elif accelerator.mixed_precision == "bf16":
875
+ weight_dtype = torch.bfloat16
876
+
877
+ # Move text_encode and vae to gpu and cast to weight_dtype
878
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
879
+ vae.to(accelerator.device, dtype=weight_dtype)
880
+
881
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
882
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
883
+ if args.max_train_steps is None:
884
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
885
+ if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
886
+ logger.warning(
887
+ f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
888
+ f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
889
+ f"This inconsistency may result in the learning rate scheduler not functioning properly."
890
+ )
891
+ # Afterwards we recalculate our number of training epochs
892
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
893
+
894
+ # We need to initialize the trackers we use, and also store our configuration.
895
+ # The trackers initializes automatically on the main process.
896
+ if accelerator.is_main_process:
897
+ accelerator.init_trackers("instruct-pix2pix", config=vars(args))
898
+
899
+ # Train!
900
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
901
+
902
+ logger.info("***** Running training *****")
903
+ logger.info(f" Num examples = {len(train_dataset)}")
904
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
905
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
906
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
907
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
908
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
909
+ global_step = 0
910
+ first_epoch = 0
911
+
912
+ # Potentially load in the weights and states from a previous save
913
+ if args.resume_from_checkpoint:
914
+ if args.resume_from_checkpoint != "latest":
915
+ path = os.path.basename(args.resume_from_checkpoint)
916
+ else:
917
+ # Get the most recent checkpoint
918
+ dirs = os.listdir(args.output_dir)
919
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
920
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
921
+ path = dirs[-1] if len(dirs) > 0 else None
922
+
923
+ if path is None:
924
+ accelerator.print(
925
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
926
+ )
927
+ args.resume_from_checkpoint = None
928
+ else:
929
+ accelerator.print(f"Resuming from checkpoint {path}")
930
+ accelerator.load_state(os.path.join(args.output_dir, path))
931
+ global_step = int(path.split("-")[1])
932
+
933
+ resume_global_step = global_step * args.gradient_accumulation_steps
934
+ first_epoch = global_step // num_update_steps_per_epoch
935
+ resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
936
+
937
+ # Only show the progress bar once on each machine.
938
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
939
+ progress_bar.set_description("Steps")
940
+
941
+ for epoch in range(first_epoch, args.num_train_epochs):
942
+ unet.train()
943
+ train_loss = 0.0
944
+ for step, batch in enumerate(train_dataloader):
945
+ # Skip steps until we reach the resumed step
946
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
947
+ if step % args.gradient_accumulation_steps == 0:
948
+ progress_bar.update(1)
949
+ continue
950
+
951
+ with accelerator.accumulate(unet):
952
+ # We want to learn the denoising process w.r.t the edited images which
953
+ # are conditioned on the original image (which was edited) and the edit instruction.
954
+ # So, first, convert images to latent space.
955
+ latents = vae.encode(batch["edited_pixel_values"].to(weight_dtype)).latent_dist.sample()
956
+ latents = latents * vae.config.scaling_factor
957
+
958
+ # Sample noise that we'll add to the latents
959
+ noise = torch.randn_like(latents)
960
+ bsz = latents.shape[0]
961
+ # Sample a random timestep for each image
962
+ timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
963
+ timesteps = timesteps.long()
964
+
965
+ # Add noise to the latents according to the noise magnitude at each timestep
966
+ # (this is the forward diffusion process)
967
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
968
+
969
+ # Get the text embedding for conditioning.
970
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
971
+
972
+ # Get the additional image embedding for conditioning.
973
+ # Instead of getting a diagonal Gaussian here, we simply take the mode.
974
+ original_image_embeds = vae.encode(batch["original_pixel_values"].to(weight_dtype)).latent_dist.mode()
975
+
976
+ # Conditioning dropout to support classifier-free guidance during inference. For more details
977
+ # check out the section 3.2.1 of the original paper https://huggingface.co/papers/2211.09800.
978
+ if args.conditioning_dropout_prob is not None:
979
+ random_p = torch.rand(bsz, device=latents.device, generator=generator)
980
+ # Sample masks for the edit prompts.
981
+ prompt_mask = random_p < 2 * args.conditioning_dropout_prob
982
+ prompt_mask = prompt_mask.reshape(bsz, 1, 1)
983
+ # Final text conditioning.
984
+ null_conditioning = text_encoder(tokenize_captions([""]).to(accelerator.device))[0]
985
+ encoder_hidden_states = torch.where(prompt_mask, null_conditioning, encoder_hidden_states)
986
+
987
+ # Sample masks for the original images.
988
+ image_mask_dtype = original_image_embeds.dtype
989
+ image_mask = 1 - (
990
+ (random_p >= args.conditioning_dropout_prob).to(image_mask_dtype)
991
+ * (random_p < 3 * args.conditioning_dropout_prob).to(image_mask_dtype)
992
+ )
993
+ image_mask = image_mask.reshape(bsz, 1, 1, 1)
994
+ # Final image conditioning.
995
+ original_image_embeds = image_mask * original_image_embeds
996
+
997
+ # Concatenate the `original_image_embeds` with the `noisy_latents`.
998
+ concatenated_noisy_latents = torch.cat([noisy_latents, original_image_embeds], dim=1)
999
+
1000
+ # Get the target for loss depending on the prediction type
1001
+ if noise_scheduler.config.prediction_type == "epsilon":
1002
+ target = noise
1003
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1004
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
1005
+ else:
1006
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1007
+
1008
+ # Predict the noise residual and compute loss
1009
+ model_pred = unet(concatenated_noisy_latents, timesteps, encoder_hidden_states, return_dict=False)[0]
1010
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1011
+
1012
+ # Gather the losses across all processes for logging (if we use distributed training).
1013
+ avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
1014
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1015
+
1016
+ # Backpropagate
1017
+ accelerator.backward(loss)
1018
+ if accelerator.sync_gradients:
1019
+ accelerator.clip_grad_norm_(trainable_params, args.max_grad_norm)
1020
+ optimizer.step()
1021
+ lr_scheduler.step()
1022
+ optimizer.zero_grad()
1023
+
1024
+ # Checks if the accelerator has performed an optimization step behind the scenes
1025
+ if accelerator.sync_gradients:
1026
+ if args.use_ema:
1027
+ ema_unet.step(trainable_params)
1028
+ progress_bar.update(1)
1029
+ global_step += 1
1030
+ accelerator.log({"train_loss": train_loss}, step=global_step)
1031
+ train_loss = 0.0
1032
+
1033
+ if global_step % args.checkpointing_steps == 0:
1034
+ if accelerator.is_main_process:
1035
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1036
+ if args.checkpoints_total_limit is not None:
1037
+ checkpoints = os.listdir(args.output_dir)
1038
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1039
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1040
+
1041
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1042
+ if len(checkpoints) >= args.checkpoints_total_limit:
1043
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1044
+ removing_checkpoints = checkpoints[0:num_to_remove]
1045
+
1046
+ logger.info(
1047
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1048
+ )
1049
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1050
+
1051
+ for removing_checkpoint in removing_checkpoints:
1052
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1053
+ shutil.rmtree(removing_checkpoint)
1054
+
1055
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1056
+ accelerator.save_state(save_path)
1057
+ unwrapped_unet = unwrap_model(unet)
1058
+ unet_lora_state_dict = convert_state_dict_to_diffusers(
1059
+ get_peft_model_state_dict(unwrapped_unet)
1060
+ )
1061
+
1062
+ StableDiffusionInstructPix2PixPipeline.save_lora_weights(
1063
+ save_directory=save_path,
1064
+ unet_lora_layers=unet_lora_state_dict,
1065
+ safe_serialization=True,
1066
+ )
1067
+ logger.info(f"Saved state to {save_path}")
1068
+
1069
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1070
+ progress_bar.set_postfix(**logs)
1071
+
1072
+ if global_step >= args.max_train_steps:
1073
+ break
1074
+
1075
+ if accelerator.is_main_process:
1076
+ if (
1077
+ (args.val_image_url is not None)
1078
+ and (args.validation_prompt is not None)
1079
+ and (epoch % args.validation_epochs == 0)
1080
+ ):
1081
+ logger.info(
1082
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
1083
+ f" {args.validation_prompt}."
1084
+ )
1085
+ # create pipeline
1086
+ if args.use_ema:
1087
+ # Store the UNet parameters temporarily and load the EMA parameters to perform inference.
1088
+ ema_unet.store(unet.parameters())
1089
+ ema_unet.copy_to(unet.parameters())
1090
+ # The models need unwrapping because for compatibility in distributed training mode.
1091
+ pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
1092
+ args.pretrained_model_name_or_path,
1093
+ unet=unwrap_model(unet),
1094
+ text_encoder=unwrap_model(text_encoder),
1095
+ vae=unwrap_model(vae),
1096
+ revision=args.revision,
1097
+ variant=args.variant,
1098
+ torch_dtype=weight_dtype,
1099
+ )
1100
+
1101
+ # run inference
1102
+ log_validation(
1103
+ pipeline,
1104
+ args,
1105
+ accelerator,
1106
+ generator,
1107
+ )
1108
+
1109
+ if args.use_ema:
1110
+ # Switch back to the original UNet parameters.
1111
+ ema_unet.restore(unet.parameters())
1112
+
1113
+ del pipeline
1114
+ torch.cuda.empty_cache()
1115
+
1116
+ # Create the pipeline using the trained modules and save it.
1117
+ accelerator.wait_for_everyone()
1118
+ if accelerator.is_main_process:
1119
+ if args.use_ema:
1120
+ ema_unet.copy_to(unet.parameters())
1121
+
1122
+ # store only LORA layers
1123
+ unet = unet.to(torch.float32)
1124
+
1125
+ unwrapped_unet = unwrap_model(unet)
1126
+ unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unwrapped_unet))
1127
+ StableDiffusionInstructPix2PixPipeline.save_lora_weights(
1128
+ save_directory=args.output_dir,
1129
+ unet_lora_layers=unet_lora_state_dict,
1130
+ safe_serialization=True,
1131
+ )
1132
+
1133
+ pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
1134
+ args.pretrained_model_name_or_path,
1135
+ text_encoder=unwrap_model(text_encoder),
1136
+ vae=unwrap_model(vae),
1137
+ unet=unwrap_model(unet),
1138
+ revision=args.revision,
1139
+ variant=args.variant,
1140
+ )
1141
+ pipeline.load_lora_weights(args.output_dir)
1142
+
1143
+ images = None
1144
+ if (args.val_image_url is not None) and (args.validation_prompt is not None):
1145
+ images = log_validation(
1146
+ pipeline,
1147
+ args,
1148
+ accelerator,
1149
+ generator,
1150
+ )
1151
+
1152
+ if args.push_to_hub:
1153
+ save_model_card(
1154
+ repo_id,
1155
+ images=images,
1156
+ base_model=args.pretrained_model_name_or_path,
1157
+ dataset_name=args.dataset_name,
1158
+ repo_folder=args.output_dir,
1159
+ )
1160
+ upload_folder(
1161
+ repo_id=repo_id,
1162
+ folder_path=args.output_dir,
1163
+ commit_message="End of training",
1164
+ ignore_patterns=["step_*", "epoch_*"],
1165
+ )
1166
+
1167
+ accelerator.end_training()
1168
+
1169
+
1170
+ if __name__ == "__main__":
1171
+ main()
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/README.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Diffusers examples with Intel optimizations
2
+
3
+ **This research project is not actively maintained by the diffusers team. For any questions or comments, please make sure to tag @hshen14 .**
4
+
5
+ This aims to provide diffusers examples with Intel optimizations such as Bfloat16 for training/fine-tuning acceleration and 8-bit integer (INT8) for inference acceleration on Intel platforms.
6
+
7
+ ## Accelerating the fine-tuning for textual inversion
8
+
9
+ We accelerate the fine-tuning for textual inversion with Intel Extension for PyTorch. The [examples](textual_inversion) enable both single node and multi-node distributed training with Bfloat16 support on Intel Xeon Scalable Processor.
10
+
11
+ ## Accelerating the inference for Stable Diffusion using Bfloat16
12
+
13
+ We start the inference acceleration with Bfloat16 using Intel Extension for PyTorch. The [script](inference_bf16.py) is generally designed to support standard Stable Diffusion models with Bfloat16 support.
14
+ ```bash
15
+ pip install diffusers transformers accelerate scipy safetensors
16
+
17
+ export KMP_BLOCKTIME=1
18
+ export KMP_SETTINGS=1
19
+ export KMP_AFFINITY=granularity=fine,compact,1,0
20
+
21
+ # Intel OpenMP
22
+ export OMP_NUM_THREADS=< Cores to use >
23
+ export LD_PRELOAD=${LD_PRELOAD}:/path/to/lib/libiomp5.so
24
+ # Jemalloc is a recommended malloc implementation that emphasizes fragmentation avoidance and scalable concurrency support.
25
+ export LD_PRELOAD=${LD_PRELOAD}:/path/to/lib/libjemalloc.so
26
+ export MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:-1,muzzy_decay_ms:9000000000"
27
+
28
+ # Launch with default DDIM
29
+ numactl --membind <node N> -C <cpu list> python python inference_bf16.py
30
+ # Launch with DPMSolverMultistepScheduler
31
+ numactl --membind <node N> -C <cpu list> python python inference_bf16.py --dpm
32
+ ```
33
+
34
+ ## Accelerating the inference for Stable Diffusion using INT8
35
+
36
+ Coming soon ...
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/inference_bf16.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import intel_extension_for_pytorch as ipex
4
+ import torch
5
+
6
+ from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
7
+
8
+
9
+ parser = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False)
10
+ parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not")
11
+ parser.add_argument("--steps", default=None, type=int, help="Num inference steps")
12
+ args = parser.parse_args()
13
+
14
+
15
+ device = "cpu"
16
+ prompt = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brightly buildings"
17
+
18
+ model_id = "path-to-your-trained-model"
19
+ pipe = StableDiffusionPipeline.from_pretrained(model_id)
20
+ if args.dpm:
21
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
22
+ pipe = pipe.to(device)
23
+
24
+ # to channels last
25
+ pipe.unet = pipe.unet.to(memory_format=torch.channels_last)
26
+ pipe.vae = pipe.vae.to(memory_format=torch.channels_last)
27
+ pipe.text_encoder = pipe.text_encoder.to(memory_format=torch.channels_last)
28
+ if pipe.requires_safety_checker:
29
+ pipe.safety_checker = pipe.safety_checker.to(memory_format=torch.channels_last)
30
+
31
+ # optimize with ipex
32
+ sample = torch.randn(2, 4, 64, 64)
33
+ timestep = torch.rand(1) * 999
34
+ encoder_hidden_status = torch.randn(2, 77, 768)
35
+ input_example = (sample, timestep, encoder_hidden_status)
36
+ try:
37
+ pipe.unet = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloat16, inplace=True, sample_input=input_example)
38
+ except Exception:
39
+ pipe.unet = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloat16, inplace=True)
40
+ pipe.vae = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloat16, inplace=True)
41
+ pipe.text_encoder = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)
42
+ if pipe.requires_safety_checker:
43
+ pipe.safety_checker = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloat16, inplace=True)
44
+
45
+ # compute
46
+ seed = 666
47
+ generator = torch.Generator(device).manual_seed(seed)
48
+ generate_kwargs = {"generator": generator}
49
+ if args.steps is not None:
50
+ generate_kwargs["num_inference_steps"] = args.steps
51
+
52
+ with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
53
+ image = pipe(prompt, **generate_kwargs).images[0]
54
+
55
+ # save image
56
+ image.save("generated.png")
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/README.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## Training with Intel Extension for PyTorch
7
+
8
+ Intel Extension for PyTorch provides the optimizations for faster training and inference on CPUs. You can leverage the training example "textual_inversion.py". Follow the [instructions](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion) to get the model and [dataset](https://huggingface.co/sd-concepts-library/dicoo2) before running the script.
9
+
10
+ The example supports both single node and multi-node distributed training:
11
+
12
+ ### Single node training
13
+
14
+ ```bash
15
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
16
+ export DATA_DIR="path-to-dir-containing-dicoo-images"
17
+
18
+ python textual_inversion.py \
19
+ --pretrained_model_name_or_path=$MODEL_NAME \
20
+ --train_data_dir=$DATA_DIR \
21
+ --learnable_property="object" \
22
+ --placeholder_token="<dicoo>" --initializer_token="toy" \
23
+ --seed=7 \
24
+ --resolution=512 \
25
+ --train_batch_size=1 \
26
+ --gradient_accumulation_steps=1 \
27
+ --max_train_steps=3000 \
28
+ --learning_rate=2.5e-03 --scale_lr \
29
+ --output_dir="textual_inversion_dicoo"
30
+ ```
31
+
32
+ Note: Bfloat16 is available on Intel Xeon Scalable Processors Cooper Lake or Sapphire Rapids. You may not get performance speedup without Bfloat16 support.
33
+
34
+ ### Multi-node distributed training
35
+
36
+ Before running the scripts, make sure to install the library's training dependencies successfully:
37
+
38
+ ```bash
39
+ python -m pip install oneccl_bind_pt==1.13 -f https://developer.intel.com/ipex-whl-stable-cpu
40
+ ```
41
+
42
+ ```bash
43
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
44
+ export DATA_DIR="path-to-dir-containing-dicoo-images"
45
+
46
+ oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
47
+ source $oneccl_bindings_for_pytorch_path/env/setvars.sh
48
+
49
+ python -m intel_extension_for_pytorch.cpu.launch --distributed \
50
+ --hostfile hostfile --nnodes 2 --nproc_per_node 2 textual_inversion.py \
51
+ --pretrained_model_name_or_path=$MODEL_NAME \
52
+ --train_data_dir=$DATA_DIR \
53
+ --learnable_property="object" \
54
+ --placeholder_token="<dicoo>" --initializer_token="toy" \
55
+ --seed=7 \
56
+ --resolution=512 \
57
+ --train_batch_size=1 \
58
+ --gradient_accumulation_steps=1 \
59
+ --max_train_steps=750 \
60
+ --learning_rate=2.5e-03 --scale_lr \
61
+ --output_dir="textual_inversion_dicoo"
62
+ ```
63
+ The above is a simple distributed training usage on 2 nodes with 2 processes on each node. Add the right hostname or ip address in the "hostfile" and make sure these 2 nodes are reachable from each other. For more details, please refer to the [user guide](https://github.com/intel/torch-ccl).
64
+
65
+
66
+ ### Reference
67
+
68
+ We publish a [Medium blog](https://medium.com/intel-analytics-software/personalized-stable-diffusion-with-few-shot-fine-tuning-on-a-single-cpu-f01a3316b13) on how to create your own Stable Diffusion model on CPUs using textual inversion. Try it out now, if you have interests.
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ accelerate>=0.16.0
2
+ torchvision
3
+ transformers>=4.21.0
4
+ ftfy
5
+ tensorboard
6
+ Jinja2
7
+ intel_extension_for_pytorch>=1.13
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import itertools
3
+ import math
4
+ import os
5
+ import random
6
+ from pathlib import Path
7
+
8
+ import intel_extension_for_pytorch as ipex
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.logging import get_logger
16
+ from accelerate.utils import ProjectConfiguration, set_seed
17
+ from huggingface_hub import create_repo, upload_folder
18
+
19
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
20
+ from packaging import version
21
+ from PIL import Image
22
+ from torch.utils.data import Dataset
23
+ from torchvision import transforms
24
+ from tqdm.auto import tqdm
25
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
26
+
27
+ from diffusers import AutoencoderKL, DDPMScheduler, PNDMScheduler, StableDiffusionPipeline, UNet2DConditionModel
28
+ from diffusers.optimization import get_scheduler
29
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
30
+ from diffusers.utils import check_min_version
31
+
32
+
33
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
34
+ PIL_INTERPOLATION = {
35
+ "linear": PIL.Image.Resampling.BILINEAR,
36
+ "bilinear": PIL.Image.Resampling.BILINEAR,
37
+ "bicubic": PIL.Image.Resampling.BICUBIC,
38
+ "lanczos": PIL.Image.Resampling.LANCZOS,
39
+ "nearest": PIL.Image.Resampling.NEAREST,
40
+ }
41
+ else:
42
+ PIL_INTERPOLATION = {
43
+ "linear": PIL.Image.LINEAR,
44
+ "bilinear": PIL.Image.BILINEAR,
45
+ "bicubic": PIL.Image.BICUBIC,
46
+ "lanczos": PIL.Image.LANCZOS,
47
+ "nearest": PIL.Image.NEAREST,
48
+ }
49
+ # ------------------------------------------------------------------------------
50
+
51
+
52
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
53
+ check_min_version("0.13.0.dev0")
54
+
55
+
56
+ logger = get_logger(__name__)
57
+
58
+
59
+ def save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path):
60
+ logger.info("Saving embeddings")
61
+ learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]
62
+ learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
63
+ torch.save(learned_embeds_dict, save_path)
64
+
65
+
66
+ def parse_args():
67
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
68
+ parser.add_argument(
69
+ "--save_steps",
70
+ type=int,
71
+ default=500,
72
+ help="Save learned_embeds.bin every X updates steps.",
73
+ )
74
+ parser.add_argument(
75
+ "--only_save_embeds",
76
+ action="store_true",
77
+ default=False,
78
+ help="Save only the embeddings for the new concept.",
79
+ )
80
+ parser.add_argument(
81
+ "--pretrained_model_name_or_path",
82
+ type=str,
83
+ default=None,
84
+ required=True,
85
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
86
+ )
87
+ parser.add_argument(
88
+ "--revision",
89
+ type=str,
90
+ default=None,
91
+ required=False,
92
+ help="Revision of pretrained model identifier from huggingface.co/models.",
93
+ )
94
+ parser.add_argument(
95
+ "--tokenizer_name",
96
+ type=str,
97
+ default=None,
98
+ help="Pretrained tokenizer name or path if not the same as model_name",
99
+ )
100
+ parser.add_argument(
101
+ "--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
102
+ )
103
+ parser.add_argument(
104
+ "--placeholder_token",
105
+ type=str,
106
+ default=None,
107
+ required=True,
108
+ help="A token to use as a placeholder for the concept.",
109
+ )
110
+ parser.add_argument(
111
+ "--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
112
+ )
113
+ parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
114
+ parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
115
+ parser.add_argument(
116
+ "--output_dir",
117
+ type=str,
118
+ default="text-inversion-model",
119
+ help="The output directory where the model predictions and checkpoints will be written.",
120
+ )
121
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
122
+ parser.add_argument(
123
+ "--resolution",
124
+ type=int,
125
+ default=512,
126
+ help=(
127
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
128
+ " resolution"
129
+ ),
130
+ )
131
+ parser.add_argument(
132
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
133
+ )
134
+ parser.add_argument(
135
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
136
+ )
137
+ parser.add_argument("--num_train_epochs", type=int, default=100)
138
+ parser.add_argument(
139
+ "--max_train_steps",
140
+ type=int,
141
+ default=5000,
142
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
143
+ )
144
+ parser.add_argument(
145
+ "--gradient_accumulation_steps",
146
+ type=int,
147
+ default=1,
148
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
149
+ )
150
+ parser.add_argument(
151
+ "--learning_rate",
152
+ type=float,
153
+ default=1e-4,
154
+ help="Initial learning rate (after the potential warmup period) to use.",
155
+ )
156
+ parser.add_argument(
157
+ "--scale_lr",
158
+ action="store_true",
159
+ default=True,
160
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
161
+ )
162
+ parser.add_argument(
163
+ "--lr_scheduler",
164
+ type=str,
165
+ default="constant",
166
+ help=(
167
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
168
+ ' "constant", "constant_with_warmup"]'
169
+ ),
170
+ )
171
+ parser.add_argument(
172
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
173
+ )
174
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
175
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
176
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
177
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
178
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
179
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
180
+ parser.add_argument(
181
+ "--hub_model_id",
182
+ type=str,
183
+ default=None,
184
+ help="The name of the repository to keep in sync with the local `output_dir`.",
185
+ )
186
+ parser.add_argument(
187
+ "--logging_dir",
188
+ type=str,
189
+ default="logs",
190
+ help=(
191
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
192
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
193
+ ),
194
+ )
195
+ parser.add_argument(
196
+ "--mixed_precision",
197
+ type=str,
198
+ default="no",
199
+ choices=["no", "fp16", "bf16"],
200
+ help=(
201
+ "Whether to use mixed precision. Choose"
202
+ "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
203
+ "and an Nvidia Ampere GPU."
204
+ ),
205
+ )
206
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
207
+
208
+ args = parser.parse_args()
209
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
210
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
211
+ args.local_rank = env_local_rank
212
+
213
+ if args.train_data_dir is None:
214
+ raise ValueError("You must specify a train data directory.")
215
+
216
+ return args
217
+
218
+
219
+ imagenet_templates_small = [
220
+ "a photo of a {}",
221
+ "a rendering of a {}",
222
+ "a cropped photo of the {}",
223
+ "the photo of a {}",
224
+ "a photo of a clean {}",
225
+ "a photo of a dirty {}",
226
+ "a dark photo of the {}",
227
+ "a photo of my {}",
228
+ "a photo of the cool {}",
229
+ "a close-up photo of a {}",
230
+ "a bright photo of the {}",
231
+ "a cropped photo of a {}",
232
+ "a photo of the {}",
233
+ "a good photo of the {}",
234
+ "a photo of one {}",
235
+ "a close-up photo of the {}",
236
+ "a rendition of the {}",
237
+ "a photo of the clean {}",
238
+ "a rendition of a {}",
239
+ "a photo of a nice {}",
240
+ "a good photo of a {}",
241
+ "a photo of the nice {}",
242
+ "a photo of the small {}",
243
+ "a photo of the weird {}",
244
+ "a photo of the large {}",
245
+ "a photo of a cool {}",
246
+ "a photo of a small {}",
247
+ ]
248
+
249
+ imagenet_style_templates_small = [
250
+ "a painting in the style of {}",
251
+ "a rendering in the style of {}",
252
+ "a cropped painting in the style of {}",
253
+ "the painting in the style of {}",
254
+ "a clean painting in the style of {}",
255
+ "a dirty painting in the style of {}",
256
+ "a dark painting in the style of {}",
257
+ "a picture in the style of {}",
258
+ "a cool painting in the style of {}",
259
+ "a close-up painting in the style of {}",
260
+ "a bright painting in the style of {}",
261
+ "a cropped painting in the style of {}",
262
+ "a good painting in the style of {}",
263
+ "a close-up painting in the style of {}",
264
+ "a rendition in the style of {}",
265
+ "a nice painting in the style of {}",
266
+ "a small painting in the style of {}",
267
+ "a weird painting in the style of {}",
268
+ "a large painting in the style of {}",
269
+ ]
270
+
271
+
272
+ class TextualInversionDataset(Dataset):
273
+ def __init__(
274
+ self,
275
+ data_root,
276
+ tokenizer,
277
+ learnable_property="object", # [object, style]
278
+ size=512,
279
+ repeats=100,
280
+ interpolation="bicubic",
281
+ flip_p=0.5,
282
+ set="train",
283
+ placeholder_token="*",
284
+ center_crop=False,
285
+ ):
286
+ self.data_root = data_root
287
+ self.tokenizer = tokenizer
288
+ self.learnable_property = learnable_property
289
+ self.size = size
290
+ self.placeholder_token = placeholder_token
291
+ self.center_crop = center_crop
292
+ self.flip_p = flip_p
293
+
294
+ self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
295
+
296
+ self.num_images = len(self.image_paths)
297
+ self._length = self.num_images
298
+
299
+ if set == "train":
300
+ self._length = self.num_images * repeats
301
+
302
+ self.interpolation = {
303
+ "linear": PIL_INTERPOLATION["linear"],
304
+ "bilinear": PIL_INTERPOLATION["bilinear"],
305
+ "bicubic": PIL_INTERPOLATION["bicubic"],
306
+ "lanczos": PIL_INTERPOLATION["lanczos"],
307
+ }[interpolation]
308
+
309
+ self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
310
+ self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
311
+
312
+ def __len__(self):
313
+ return self._length
314
+
315
+ def __getitem__(self, i):
316
+ example = {}
317
+ image = Image.open(self.image_paths[i % self.num_images])
318
+
319
+ if not image.mode == "RGB":
320
+ image = image.convert("RGB")
321
+
322
+ placeholder_string = self.placeholder_token
323
+ text = random.choice(self.templates).format(placeholder_string)
324
+
325
+ example["input_ids"] = self.tokenizer(
326
+ text,
327
+ padding="max_length",
328
+ truncation=True,
329
+ max_length=self.tokenizer.model_max_length,
330
+ return_tensors="pt",
331
+ ).input_ids[0]
332
+
333
+ # default to score-sde preprocessing
334
+ img = np.array(image).astype(np.uint8)
335
+
336
+ if self.center_crop:
337
+ crop = min(img.shape[0], img.shape[1])
338
+ (
339
+ h,
340
+ w,
341
+ ) = (
342
+ img.shape[0],
343
+ img.shape[1],
344
+ )
345
+ img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
346
+
347
+ image = Image.fromarray(img)
348
+ image = image.resize((self.size, self.size), resample=self.interpolation)
349
+
350
+ image = self.flip_transform(image)
351
+ image = np.array(image).astype(np.uint8)
352
+ image = (image / 127.5 - 1.0).astype(np.float32)
353
+
354
+ example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
355
+ return example
356
+
357
+
358
+ def freeze_params(params):
359
+ for param in params:
360
+ param.requires_grad = False
361
+
362
+
363
+ def main():
364
+ args = parse_args()
365
+
366
+ if args.report_to == "wandb" and args.hub_token is not None:
367
+ raise ValueError(
368
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
369
+ " Please use `hf auth login` to authenticate with the Hub."
370
+ )
371
+
372
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
373
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
374
+ accelerator = Accelerator(
375
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
376
+ mixed_precision=args.mixed_precision,
377
+ log_with=args.report_to,
378
+ project_config=accelerator_project_config,
379
+ )
380
+
381
+ # Disable AMP for MPS.
382
+ if torch.backends.mps.is_available():
383
+ accelerator.native_amp = False
384
+
385
+ # If passed along, set the training seed now.
386
+ if args.seed is not None:
387
+ set_seed(args.seed)
388
+
389
+ # Handle the repository creation
390
+ if accelerator.is_main_process:
391
+ if args.output_dir is not None:
392
+ os.makedirs(args.output_dir, exist_ok=True)
393
+
394
+ if args.push_to_hub:
395
+ repo_id = create_repo(
396
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
397
+ ).repo_id
398
+
399
+ # Load the tokenizer and add the placeholder token as a additional special token
400
+ if args.tokenizer_name:
401
+ tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
402
+ elif args.pretrained_model_name_or_path:
403
+ tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
404
+
405
+ # Add the placeholder token in tokenizer
406
+ num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
407
+ if num_added_tokens == 0:
408
+ raise ValueError(
409
+ f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
410
+ " `placeholder_token` that is not already in the tokenizer."
411
+ )
412
+
413
+ # Convert the initializer_token, placeholder_token to ids
414
+ token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
415
+ # Check if initializer_token is a single token or a sequence of tokens
416
+ if len(token_ids) > 1:
417
+ raise ValueError("The initializer token must be a single token.")
418
+
419
+ initializer_token_id = token_ids[0]
420
+ placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
421
+
422
+ # Load models and create wrapper for stable diffusion
423
+ text_encoder = CLIPTextModel.from_pretrained(
424
+ args.pretrained_model_name_or_path,
425
+ subfolder="text_encoder",
426
+ revision=args.revision,
427
+ )
428
+ vae = AutoencoderKL.from_pretrained(
429
+ args.pretrained_model_name_or_path,
430
+ subfolder="vae",
431
+ revision=args.revision,
432
+ )
433
+ unet = UNet2DConditionModel.from_pretrained(
434
+ args.pretrained_model_name_or_path,
435
+ subfolder="unet",
436
+ revision=args.revision,
437
+ )
438
+
439
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
440
+ text_encoder.resize_token_embeddings(len(tokenizer))
441
+
442
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
443
+ token_embeds = text_encoder.get_input_embeddings().weight.data
444
+ token_embeds[placeholder_token_id] = token_embeds[initializer_token_id]
445
+
446
+ # Freeze vae and unet
447
+ freeze_params(vae.parameters())
448
+ freeze_params(unet.parameters())
449
+ # Freeze all parameters except for the token embeddings in text encoder
450
+ params_to_freeze = itertools.chain(
451
+ text_encoder.text_model.encoder.parameters(),
452
+ text_encoder.text_model.final_layer_norm.parameters(),
453
+ text_encoder.text_model.embeddings.position_embedding.parameters(),
454
+ )
455
+ freeze_params(params_to_freeze)
456
+
457
+ if args.scale_lr:
458
+ args.learning_rate = (
459
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
460
+ )
461
+
462
+ # Initialize the optimizer
463
+ optimizer = torch.optim.AdamW(
464
+ text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
465
+ lr=args.learning_rate,
466
+ betas=(args.adam_beta1, args.adam_beta2),
467
+ weight_decay=args.adam_weight_decay,
468
+ eps=args.adam_epsilon,
469
+ )
470
+
471
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
472
+
473
+ train_dataset = TextualInversionDataset(
474
+ data_root=args.train_data_dir,
475
+ tokenizer=tokenizer,
476
+ size=args.resolution,
477
+ placeholder_token=args.placeholder_token,
478
+ repeats=args.repeats,
479
+ learnable_property=args.learnable_property,
480
+ center_crop=args.center_crop,
481
+ set="train",
482
+ )
483
+ train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True)
484
+
485
+ # Scheduler and math around the number of training steps.
486
+ overrode_max_train_steps = False
487
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
488
+ if args.max_train_steps is None:
489
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
490
+ overrode_max_train_steps = True
491
+
492
+ lr_scheduler = get_scheduler(
493
+ args.lr_scheduler,
494
+ optimizer=optimizer,
495
+ num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
496
+ num_training_steps=args.max_train_steps * accelerator.num_processes,
497
+ )
498
+
499
+ text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
500
+ text_encoder, optimizer, train_dataloader, lr_scheduler
501
+ )
502
+
503
+ # Move vae and unet to device
504
+ vae.to(accelerator.device)
505
+ unet.to(accelerator.device)
506
+
507
+ # Keep vae and unet in eval model as we don't train these
508
+ vae.eval()
509
+ unet.eval()
510
+
511
+ unet = ipex.optimize(unet, dtype=torch.bfloat16, inplace=True)
512
+ vae = ipex.optimize(vae, dtype=torch.bfloat16, inplace=True)
513
+
514
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
515
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
516
+ if overrode_max_train_steps:
517
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
518
+ # Afterwards we recalculate our number of training epochs
519
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
520
+
521
+ # We need to initialize the trackers we use, and also store our configuration.
522
+ # The trackers initializes automatically on the main process.
523
+ if accelerator.is_main_process:
524
+ accelerator.init_trackers("textual_inversion", config=vars(args))
525
+
526
+ # Train!
527
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
528
+
529
+ logger.info("***** Running training *****")
530
+ logger.info(f" Num examples = {len(train_dataset)}")
531
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
532
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
533
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
534
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
535
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
536
+ # Only show the progress bar once on each machine.
537
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
538
+ progress_bar.set_description("Steps")
539
+ global_step = 0
540
+
541
+ text_encoder.train()
542
+ text_encoder, optimizer = ipex.optimize(text_encoder, optimizer=optimizer, dtype=torch.bfloat16)
543
+
544
+ for epoch in range(args.num_train_epochs):
545
+ for step, batch in enumerate(train_dataloader):
546
+ with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
547
+ with accelerator.accumulate(text_encoder):
548
+ # Convert images to latent space
549
+ latents = vae.encode(batch["pixel_values"]).latent_dist.sample().detach()
550
+ latents = latents * vae.config.scaling_factor
551
+
552
+ # Sample noise that we'll add to the latents
553
+ noise = torch.randn(latents.shape).to(latents.device)
554
+ bsz = latents.shape[0]
555
+ # Sample a random timestep for each image
556
+ timesteps = torch.randint(
557
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
558
+ ).long()
559
+
560
+ # Add noise to the latents according to the noise magnitude at each timestep
561
+ # (this is the forward diffusion process)
562
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
563
+
564
+ # Get the text embedding for conditioning
565
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
566
+
567
+ # Predict the noise residual
568
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
569
+
570
+ # Get the target for loss depending on the prediction type
571
+ if noise_scheduler.config.prediction_type == "epsilon":
572
+ target = noise
573
+ elif noise_scheduler.config.prediction_type == "v_prediction":
574
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
575
+ else:
576
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
577
+
578
+ loss = F.mse_loss(model_pred, target, reduction="none").mean([1, 2, 3]).mean()
579
+ accelerator.backward(loss)
580
+
581
+ # Zero out the gradients for all token embeddings except the newly added
582
+ # embeddings for the concept, as we only want to optimize the concept embeddings
583
+ if accelerator.num_processes > 1:
584
+ grads = text_encoder.module.get_input_embeddings().weight.grad
585
+ else:
586
+ grads = text_encoder.get_input_embeddings().weight.grad
587
+ # Get the index for tokens that we want to zero the grads for
588
+ index_grads_to_zero = torch.arange(len(tokenizer)) != placeholder_token_id
589
+ grads.data[index_grads_to_zero, :] = grads.data[index_grads_to_zero, :].fill_(0)
590
+
591
+ optimizer.step()
592
+ lr_scheduler.step()
593
+ optimizer.zero_grad()
594
+
595
+ # Checks if the accelerator has performed an optimization step behind the scenes
596
+ if accelerator.sync_gradients:
597
+ progress_bar.update(1)
598
+ global_step += 1
599
+ if global_step % args.save_steps == 0:
600
+ save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
601
+ save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
602
+
603
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
604
+ progress_bar.set_postfix(**logs)
605
+ accelerator.log(logs, step=global_step)
606
+
607
+ if global_step >= args.max_train_steps:
608
+ break
609
+
610
+ accelerator.wait_for_everyone()
611
+
612
+ # Create the pipeline using using the trained modules and save it.
613
+ if accelerator.is_main_process:
614
+ if args.push_to_hub and args.only_save_embeds:
615
+ logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
616
+ save_full_model = True
617
+ else:
618
+ save_full_model = not args.only_save_embeds
619
+ if save_full_model:
620
+ pipeline = StableDiffusionPipeline(
621
+ text_encoder=accelerator.unwrap_model(text_encoder),
622
+ vae=vae,
623
+ unet=unet,
624
+ tokenizer=tokenizer,
625
+ scheduler=PNDMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler"),
626
+ safety_checker=StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker"),
627
+ feature_extractor=CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32"),
628
+ )
629
+ pipeline.save_pretrained(args.output_dir)
630
+ # Save the newly trained embeddings
631
+ save_path = os.path.join(args.output_dir, "learned_embeds.bin")
632
+ save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
633
+
634
+ if args.push_to_hub:
635
+ upload_folder(
636
+ repo_id=repo_id,
637
+ folder_path=args.output_dir,
638
+ commit_message="End of training",
639
+ ignore_patterns=["step_*", "epoch_*"],
640
+ )
641
+
642
+ accelerator.end_training()
643
+
644
+
645
+ if __name__ == "__main__":
646
+ main()
tasks/tasksmith-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/tests/source/examples/research_projects/lpl/README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Latent Perceptual Loss (LPL) for Stable Diffusion XL
2
+
3
+ This directory contains an implementation of Latent Perceptual Loss (LPL) for training Stable Diffusion XL models, based on the paper: [Boosting Latent Diffusion with Perceptual Objectives](https://huggingface.co/papers/2411.04873) (Berrada et al., 2025). LPL is a perceptual loss that operates in the latent space of a VAE, helping to improve the quality and consistency of generated images by bridging the disconnect between the diffusion model and the autoencoder decoder. The implementation is based on the reference implementation provided by Tariq Berrada.
4
+
5
+ ## Overview
6
+
7
+ LPL addresses a key limitation in latent diffusion models (LDMs): the disconnect between the diffusion model training and the autoencoder decoder. While LDMs train in the latent space, they don't receive direct feedback about how well their outputs decode into high-quality images. This can lead to:
8
+
9
+ - Loss of fine details in generated images
10
+ - Inconsistent image quality
11
+ - Structural artifacts
12
+ - Reduced sharpness and realism
13
+
14
+ LPL works by comparing intermediate features from the VAE decoder between the predicted and target latents. This helps the model learn better perceptual features and can lead to:
15
+
16
+ - Improved image quality and consistency (6-20% FID improvement)
17
+ - Better preservation of fine details
18
+ - More stable training, especially at high noise levels
19
+ - Better handling of structural information
20
+ - Sharper and more realistic textures
21
+
22
+ ## Implementation Details
23
+
24
+ The LPL implementation follows the paper's methodology and includes several key features:
25
+
26
+ 1. **Feature Extraction**: Extracts intermediate features from the VAE decoder, including:
27
+ - Middle block features
28
+ - Up block features (configurable number of blocks)
29
+ - Proper gradient checkpointing for memory efficiency
30
+ - Features are extracted only for timesteps below the threshold (high SNR)
31
+
32
+ 2. **Feature Normalization**: Multiple normalization options as validated in the paper:
33
+ - `default`: Normalize each feature map independently
34
+ - `shared`: Cross-normalize features using target statistics (recommended)
35
+ - `batch`: Batch-wise normalization
36
+
37
+ 3. **Outlier Handling**: Optional removal of outliers in feature maps using:
38
+ - Quantile-based filtering (2% quantiles)
39
+ - Morphological operations (opening/closing)
40
+ - Adaptive thresholding based on standard deviation
41
+
42
+ 4. **Loss Types**:
43
+ - MSE loss (default)
44
+ - L1 loss
45
+ - Optional power law weighting (2^(-i) for layer i)
46
+
47
+ ## Usage
48
+
49
+ To use LPL in your training, add the following arguments to your training command:
50
+
51
+ ```bash
52
+ python examples/research_projects/lpl/train_sdxl_lpl.py \
53
+ --use_lpl \
54
+ --lpl_weight 1.0 \ # Weight for LPL loss (1.0-2.0 recommended)
55
+ --lpl_t_threshold 200 \ # Apply LPL only for timesteps < threshold (high SNR)
56
+ --lpl_loss_type mse \ # Loss type: "mse" or "l1"
57
+ --lpl_norm_type shared \ # Normalization type: "default", "shared" (recommended), or "batch"
58
+ --lpl_pow_law \ # Use power law weighting for layers
59
+ --lpl_num_blocks 4 \ # Number of up blocks to use (1-4)
60
+ --lpl_remove_outliers \ # Remove outliers in feature maps
61
+ --lpl_scale \ # Scale LPL loss by noise level weights
62
+ --lpl_start 0 \ # Step to start applying LPL
63
+ # ... other training arguments ...
64
+ ```
65
+
66
+ ### Key Parameters
67
+
68
+ - `lpl_weight`: Controls the strength of the LPL loss relative to the main diffusion loss. Higher values (1.0-2.0) improve quality but may slow training.
69
+ - `lpl_t_threshold`: LPL is only applied for timesteps below this threshold (high SNR). Lower values (100-200) focus on more important timesteps.
70
+ - `lpl_loss_type`: Choose between MSE (default) and L1 loss. MSE is recommended for most cases.
71
+ - `lpl_norm_type`: Feature normalization strategy. "shared" is recommended as it showed best results in the paper.
72
+ - `lpl_pow_law`: Whether to use power law weighting (2^(-i) for layer i). Recommended for better feature balance.
73
+ - `lpl_num_blocks`: Number of up blocks to use for feature extraction (1-4). More blocks capture more features but use more memory.
74
+ - `lpl_remove_outliers`: Whether to remove outliers in feature maps. Recommended for stable training.
75
+ - `lpl_scale`: Whether to scale LPL loss by noise level weights. Helps focus on more important timesteps.
76
+ - `lpl_start`: Training step to start applying LPL. Can be used to warm up training.
77
+
78
+ ## Recommendations
79
+
80
+ 1. **Starting Point** (based on paper results):
81
+ ```bash
82
+ --use_lpl \
83
+ --lpl_weight 1.0 \
84
+ --lpl_t_threshold 200 \
85
+ --lpl_loss_type mse \
86
+ --lpl_norm_type shared \
87
+ --lpl_pow_law \
88
+ --lpl_num_blocks 4 \
89
+ --lpl_remove_outliers \
90
+ --lpl_scale
91
+ ```
92
+
93
+ 2. **Memory Efficiency**:
94
+ - Use `--gradient_checkpointing` for memory efficiency (enabled by default)
95
+ - Reduce `lpl_num_blocks` if memory is constrained (2-3 blocks still give good results)
96
+ - Consider using `--lpl_scale` to focus on more important timesteps
97
+ - Features are extracted only for timesteps below threshold to save memory
98
+
99
+ 3. **Quality vs Speed**:
100
+ - Higher `lpl_weight` (1.0-2.0) for better quality
101
+ - Lower `lpl_t_threshold` (100-200) for faster training
102
+ - Use `lpl_remove_outliers` for more stable training
103
+ - `lpl_norm_type shared` provides best quality/speed trade-off
104
+
105
+ ## Technical Details
106
+
107
+ ### Feature Extraction
108
+
109
+ The LPL implementation extracts features from the VAE decoder in the following order:
110
+ 1. Middle block output
111
+ 2. Up block outputs (configurable number of blocks)
112
+
113
+ Each feature map is processed with:
114
+ 1. Optional outlier removal (2% quantiles, morphological operations)
115
+ 2. Feature normalization (shared statistics recommended)
116
+ 3. Loss calculation (MSE or L1)
117
+ 4. Optional power law weighting (2^(-i) for layer i)
118
+
119
+ ### Loss Calculation
120
+
121
+ For each feature map:
122
+ 1. Features are normalized according to the chosen strategy
123
+ 2. Loss is calculated between normalized features
124
+ 3. Outliers are masked out (if enabled)
125
+ 4. Loss is weighted by layer depth (if power law enabled)
126
+ 5. Final loss is averaged across all layers
127
+
128
+ ### Memory Considerations
129
+
130
+ - Gradient checkpointing is used by default
131
+ - Features are extracted only for timesteps below the threshold
132
+ - Outlier removal is done in-place to save memory
133
+ - Feature normalization is done efficiently using vectorized operations
134
+ - Memory usage scales linearly with number of blocks used
135
+
136
+ ## Results
137
+
138
+ Based on the paper's findings, LPL provides:
139
+ - 6-20% improvement in FID scores
140
+ - Better preservation of fine details
141
+ - More realistic textures and structures
142
+ - Improved consistency across different resolutions
143
+ - Better performance on both small and large datasets
144
+
145
+ ## Citation
146
+
147
+ If you use this implementation in your research, please cite:
148
+
149
+ ```bibtex
150
+ @inproceedings{berrada2025boosting,
151
+ title={Boosting Latent Diffusion with Perceptual Objectives},
152
+ author={Tariq Berrada and Pietro Astolfi and Melissa Hall and Marton Havasi and Yohann Benchetrit and Adriana Romero-Soriano and Karteek Alahari and Michal Drozdzal and Jakob Verbeek},
153
+ booktitle={The Thirteenth International Conference on Learning Representations},
154
+ year={2025},
155
+ url={https://openreview.net/forum?id=y4DtzADzd1}
156
+ }
157
+ ```
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lpl/lpl_loss.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Berrada et al.
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+
9
+ def normalize_tensor(in_feat, eps=1e-10):
10
+ norm_factor = torch.sqrt(torch.sum(in_feat**2, dim=1, keepdim=True))
11
+ return in_feat / (norm_factor + eps)
12
+
13
+
14
+ def cross_normalize(input, target, eps=1e-10):
15
+ norm_factor = torch.sqrt(torch.sum(target**2, dim=1, keepdim=True))
16
+ return input / (norm_factor + eps), target / (norm_factor + eps)
17
+
18
+
19
+ def remove_outliers(feat, down_f=1, opening=5, closing=3, m=100, quant=0.02):
20
+ opening = int(np.ceil(opening / down_f))
21
+ closing = int(np.ceil(closing / down_f))
22
+ if opening == 2:
23
+ opening = 3
24
+ if closing == 2:
25
+ closing = 1
26
+
27
+ # replace quantile with kth value here.
28
+ feat_flat = feat.flatten(-2, -1)
29
+ k1, k2 = int(feat_flat.shape[-1] * quant), int(feat_flat.shape[-1] * (1 - quant))
30
+ q1 = feat_flat.kthvalue(k1, dim=-1).values[..., None, None]
31
+ q2 = feat_flat.kthvalue(k2, dim=-1).values[..., None, None]
32
+
33
+ m = 2 * feat_flat.std(-1)[..., None, None].detach()
34
+ mask = (q1 - m < feat) * (feat < q2 + m)
35
+
36
+ # dilate the mask.
37
+ mask = nn.MaxPool2d(kernel_size=closing, stride=1, padding=(closing - 1) // 2)(mask.float()) # closing
38
+ mask = (-nn.MaxPool2d(kernel_size=opening, stride=1, padding=(opening - 1) // 2)(-mask)).bool() # opening
39
+ feat = feat * mask
40
+ return mask, feat
41
+
42
+
43
+ class LatentPerceptualLoss(nn.Module):
44
+ def __init__(
45
+ self,
46
+ vae,
47
+ loss_type="mse",
48
+ grad_ckpt=True,
49
+ pow_law=False,
50
+ norm_type="default",
51
+ num_mid_blocks=4,
52
+ feature_type="feature",
53
+ remove_outliers=True,
54
+ ):
55
+ super().__init__()
56
+ self.vae = vae
57
+ self.decoder = self.vae.decoder
58
+ # Store scaling factors as tensors on the correct device
59
+ device = next(self.vae.parameters()).device
60
+
61
+ # Get scaling factors with proper defaults and handle None values
62
+ scale_factor = getattr(self.vae.config, "scaling_factor", None)
63
+ shift_factor = getattr(self.vae.config, "shift_factor", None)
64
+
65
+ # Convert to tensors with proper defaults
66
+ self.scale = torch.tensor(1.0 if scale_factor is None else scale_factor, device=device)
67
+ self.shift = torch.tensor(0.0 if shift_factor is None else shift_factor, device=device)
68
+
69
+ self.gradient_checkpointing = grad_ckpt
70
+ self.pow_law = pow_law
71
+ self.norm_type = norm_type.lower()
72
+ self.outlier_mask = remove_outliers
73
+ self.last_feature_stats = [] # Store feature statistics for logging
74
+
75
+ assert feature_type in ["feature", "image"]
76
+ self.feature_type = feature_type
77
+
78
+ assert self.norm_type in ["default", "shared", "batch"]
79
+ assert num_mid_blocks >= 0 and num_mid_blocks <= 4
80
+ self.n_blocks = num_mid_blocks
81
+
82
+ assert loss_type in ["mse", "l1"]
83
+ if loss_type == "mse":
84
+ self.loss_fn = nn.MSELoss(reduction="none")
85
+ elif loss_type == "l1":
86
+ self.loss_fn = nn.L1Loss(reduction="none")
87
+
88
+ def get_features(self, z, latent_embeds=None, disable_grads=False):
89
+ with torch.set_grad_enabled(not disable_grads):
90
+ if self.gradient_checkpointing and not disable_grads:
91
+
92
+ def create_custom_forward(module):
93
+ def custom_forward(*inputs):
94
+ return module(*inputs)
95
+
96
+ return custom_forward
97
+
98
+ features = []
99
+ upscale_dtype = next(iter(self.decoder.up_blocks.parameters())).dtype
100
+ sample = z
101
+ sample = self.decoder.conv_in(sample)
102
+
103
+ # middle
104
+ sample = torch.utils.checkpoint.checkpoint(
105
+ create_custom_forward(self.decoder.mid_block),
106
+ sample,
107
+ latent_embeds,
108
+ use_reentrant=False,
109
+ )
110
+ sample = sample.to(upscale_dtype)
111
+ features.append(sample)
112
+
113
+ # up
114
+ for up_block in self.decoder.up_blocks[: self.n_blocks]:
115
+ sample = torch.utils.checkpoint.checkpoint(
116
+ create_custom_forward(up_block),
117
+ sample,
118
+ latent_embeds,
119
+ use_reentrant=False,
120
+ )
121
+ features.append(sample)
122
+ return features
123
+ else:
124
+ features = []
125
+ upscale_dtype = next(iter(self.decoder.up_blocks.parameters())).dtype
126
+ sample = z
127
+ sample = self.decoder.conv_in(sample)
128
+
129
+ # middle
130
+ sample = self.decoder.mid_block(sample, latent_embeds)
131
+ sample = sample.to(upscale_dtype)
132
+ features.append(sample)
133
+
134
+ # up
135
+ for up_block in self.decoder.up_blocks[: self.n_blocks]:
136
+ sample = up_block(sample, latent_embeds)
137
+ features.append(sample)
138
+ return features
139
+
140
+ def get_loss(self, input, target, get_hist=False):
141
+ if self.feature_type == "feature":
142
+ inp_f = self.get_features(self.shift + input / self.scale)
143
+ tar_f = self.get_features(self.shift + target / self.scale, disable_grads=True)
144
+ losses = []
145
+ self.last_feature_stats = [] # Reset feature stats
146
+
147
+ for i, (x, y) in enumerate(zip(inp_f, tar_f, strict=False)):
148
+ my = torch.ones_like(y).bool()
149
+ outlier_ratio = 0.0
150
+
151
+ if self.outlier_mask:
152
+ with torch.no_grad():
153
+ if i == 2:
154
+ my, y = remove_outliers(y, down_f=2)
155
+ outlier_ratio = 1.0 - my.float().mean().item()
156
+ elif i in [3, 4, 5]:
157
+ my, y = remove_outliers(y, down_f=1)
158
+ outlier_ratio = 1.0 - my.float().mean().item()
159
+
160
+ # Store feature statistics before normalization
161
+ with torch.no_grad():
162
+ stats = {
163
+ "mean": y.mean().item(),
164
+ "std": y.std().item(),
165
+ "outlier_ratio": outlier_ratio,
166
+ }
167
+ self.last_feature_stats.append(stats)
168
+
169
+ # normalize feature tensors
170
+ if self.norm_type == "default":
171
+ x = normalize_tensor(x)
172
+ y = normalize_tensor(y)
173
+ elif self.norm_type == "shared":
174
+ x, y = cross_normalize(x, y, eps=1e-6)
175
+
176
+ term_loss = self.loss_fn(x, y) * my
177
+ # reduce loss term
178
+ loss_f = 2 ** (-min(i, 3)) if self.pow_law else 1.0
179
+ term_loss = term_loss.sum((2, 3)) * loss_f / my.sum((2, 3))
180
+ losses.append(term_loss.mean((1,)))
181
+
182
+ if get_hist:
183
+ return losses
184
+ else:
185
+ loss = sum(losses)
186
+ return loss / len(inp_f)
187
+ elif self.feature_type == "image":
188
+ inp_f = self.vae.decode(input / self.scale).sample
189
+ tar_f = self.vae.decode(target / self.scale).sample
190
+ return F.mse_loss(inp_f, tar_f)
191
+
192
+ def get_first_conv(self, z):
193
+ sample = self.decoder.conv_in(z)
194
+ return sample
195
+
196
+ def get_first_block(self, z):
197
+ sample = self.decoder.conv_in(z)
198
+ sample = self.decoder.mid_block(sample)
199
+ for resnet in self.decoder.up_blocks[0].resnets:
200
+ sample = resnet(sample, None)
201
+ return sample
202
+
203
+ def get_first_layer(self, input, target, target_layer="conv"):
204
+ if target_layer == "conv":
205
+ feat_in = self.get_first_conv(input)
206
+ with torch.no_grad():
207
+ feat_tar = self.get_first_conv(target)
208
+ else:
209
+ feat_in = self.get_first_block(input)
210
+ with torch.no_grad():
211
+ feat_tar = self.get_first_block(target)
212
+
213
+ feat_in, feat_tar = cross_normalize(feat_in, feat_tar)
214
+
215
+ return F.mse_loss(feat_in, feat_tar, reduction="mean")
tasks/tasksmith-d977e5ab6579/tests/source/examples/research_projects/lpl/train_sdxl_lpl.py ADDED
@@ -0,0 +1,1622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """LPL training script for Stable Diffusion XL for text2image."""
17
+
18
+ import argparse
19
+ import functools
20
+ import gc
21
+ import logging
22
+ import math
23
+ import os
24
+ import random
25
+ import re
26
+ import shutil
27
+ from contextlib import nullcontext
28
+ from pathlib import Path
29
+ from typing import Dict, List, Tuple
30
+
31
+ import accelerate
32
+ import datasets
33
+ import numpy as np
34
+ import torch
35
+ import torch.nn as nn
36
+ import torch.nn.functional as F
37
+ import torch.utils.checkpoint
38
+ import transformers
39
+ from accelerate import Accelerator
40
+ from accelerate.logging import get_logger
41
+ from accelerate.utils import DistributedType, ProjectConfiguration, set_seed
42
+ from datasets import concatenate_datasets, load_dataset
43
+ from huggingface_hub import create_repo, upload_folder
44
+ from lpl_loss import LatentPerceptualLoss
45
+ from packaging import version
46
+ from torchvision import transforms
47
+ from torchvision.transforms.functional import crop
48
+ from tqdm.auto import tqdm
49
+ from transformers import AutoTokenizer, PretrainedConfig
50
+
51
+ import diffusers
52
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionXLPipeline, UNet2DConditionModel
53
+ from diffusers.optimization import get_scheduler
54
+ from diffusers.training_utils import EMAModel, compute_snr
55
+ from diffusers.utils import check_min_version, is_wandb_available
56
+ from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
57
+ from diffusers.utils.import_utils import is_torch_npu_available, is_xformers_available
58
+ from diffusers.utils.torch_utils import is_compiled_module
59
+
60
+
61
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
62
+ check_min_version("0.33.0.dev0")
63
+
64
+ logger = get_logger(__name__)
65
+ if is_torch_npu_available():
66
+ import torch_npu
67
+
68
+ torch.npu.config.allow_internal_format = False
69
+
70
+ DATASET_NAME_MAPPING = {
71
+ "lambdalabs/naruto-blip-captions": ("image", "text"),
72
+ }
73
+
74
+ # Global dictionary to store intermediate features from hooks
75
+ hook_features: Dict[str, torch.Tensor] = {}
76
+
77
+
78
+ def get_intermediate_features_hook(name: str):
79
+ """Creates a hook function that saves the output of a layer."""
80
+
81
+ def hook(model, input, output):
82
+ # Some layers might return tuples (e.g., attention blocks)
83
+ # We are usually interested in the first element (hidden states)
84
+ if isinstance(output, tuple):
85
+ hook_features[name] = output[0]
86
+ else:
87
+ hook_features[name] = output
88
+
89
+ return hook
90
+
91
+
92
+ def clear_hook_features():
93
+ """Clears the global feature dictionary."""
94
+ global hook_features
95
+ hook_features = {}
96
+
97
+
98
+ def normalize_features(
99
+ feat1: torch.Tensor, feat2: torch.Tensor, eps: float = 1e-6
100
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
101
+ """
102
+ Normalizes feat1 and feat2 using the statistics of feat2 (predicted features).
103
+ Normalization is done per-channel.
104
+ """
105
+ # Calculate stats over spatial dimensions (H, W)
106
+ dims = tuple(range(2, feat2.ndim)) # Dims to reduce over (usually 2, 3 for H, W)
107
+ mean = torch.mean(feat2, dim=dims, keepdim=True)
108
+ std = torch.std(feat2, dim=dims, keepdim=True) + eps
109
+
110
+ feat1_norm = (feat1 - mean) / std
111
+ feat2_norm = (feat2 - mean) / std
112
+ return feat1_norm, feat2_norm
113
+
114
+
115
+ def get_decoder_layer_names(decoder: nn.Module) -> List[str]:
116
+ """Helper to get potential layer names for hooks in the VAE decoder."""
117
+ layer_names = []
118
+ for name, module in decoder.named_modules():
119
+ # Example: Target ResnetBlocks and potentially UpBlocks
120
+ if isinstance(module, (diffusers.models.resnet.ResnetBlock2D, diffusers.models.unet_2d_blocks.UpBlock2D)):
121
+ # Filter out redundant names if UpBlock contains ResnetBlocks already named
122
+ is_child = any(
123
+ name.startswith(parent + ".")
124
+ for parent in layer_names
125
+ if isinstance(decoder.get_submodule(parent), diffusers.models.unet_2d_blocks.UpBlock2D)
126
+ )
127
+ if not is_child:
128
+ layer_names.append(name)
129
+ # A basic default selection if complex logic fails
130
+ if not layer_names:
131
+ layer_names = [
132
+ name for name, module in decoder.named_modules() if re.match(r"up_blocks\.\d+\.resnets\.\d+$", name)
133
+ ]
134
+ return layer_names
135
+
136
+
137
+ def save_model_card(
138
+ repo_id: str,
139
+ images: list = None,
140
+ validation_prompt: str = None,
141
+ base_model: str = None,
142
+ dataset_name: str = None,
143
+ repo_folder: str = None,
144
+ vae_path: str = None,
145
+ ):
146
+ img_str = ""
147
+ if images is not None:
148
+ for i, image in enumerate(images):
149
+ image.save(os.path.join(repo_folder, f"image_{i}.png"))
150
+ img_str += f"![img_{i}](./image_{i}.png)\n"
151
+
152
+ model_description = f"""
153
+ # Text-to-image finetuning - {repo_id}
154
+
155
+ This pipeline was finetuned from **{base_model}** on the **{dataset_name}** dataset. Below are some example images generated with the finetuned pipeline using the following prompt: {validation_prompt}: \n
156
+ {img_str}
157
+
158
+ Special VAE used for training: {vae_path}.
159
+ """
160
+
161
+ model_card = load_or_create_model_card(
162
+ repo_id_or_path=repo_id,
163
+ from_training=True,
164
+ license="creativeml-openrail-m",
165
+ base_model=base_model,
166
+ model_description=model_description,
167
+ inference=True,
168
+ )
169
+
170
+ tags = [
171
+ "stable-diffusion-xl",
172
+ "stable-diffusion-xl-diffusers",
173
+ "text-to-image",
174
+ "diffusers-training",
175
+ "diffusers",
176
+ ]
177
+ model_card = populate_model_card(model_card, tags=tags)
178
+
179
+ model_card.save(os.path.join(repo_folder, "README.md"))
180
+
181
+
182
+ def import_model_class_from_model_name_or_path(
183
+ pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
184
+ ):
185
+ text_encoder_config = PretrainedConfig.from_pretrained(
186
+ pretrained_model_name_or_path, subfolder=subfolder, revision=revision
187
+ )
188
+ model_class = text_encoder_config.architectures[0]
189
+
190
+ if model_class == "CLIPTextModel":
191
+ from transformers import CLIPTextModel
192
+
193
+ return CLIPTextModel
194
+ elif model_class == "CLIPTextModelWithProjection":
195
+ from transformers import CLIPTextModelWithProjection
196
+
197
+ return CLIPTextModelWithProjection
198
+ else:
199
+ raise ValueError(f"{model_class} is not supported.")
200
+
201
+
202
+ def parse_args(input_args=None):
203
+ parser = argparse.ArgumentParser(description="LPL based training script of Stable Diffusion XL.")
204
+ parser.add_argument(
205
+ "--pretrained_model_name_or_path",
206
+ type=str,
207
+ default=None,
208
+ required=True,
209
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
210
+ )
211
+ parser.add_argument(
212
+ "--pretrained_vae_model_name_or_path",
213
+ type=str,
214
+ default=None,
215
+ help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
216
+ )
217
+ parser.add_argument(
218
+ "--revision",
219
+ type=str,
220
+ default=None,
221
+ required=False,
222
+ help="Revision of pretrained model identifier from huggingface.co/models.",
223
+ )
224
+ parser.add_argument(
225
+ "--variant",
226
+ type=str,
227
+ default=None,
228
+ help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
229
+ )
230
+ parser.add_argument(
231
+ "--dataset_name",
232
+ type=str,
233
+ default=None,
234
+ help=(
235
+ "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
236
+ " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
237
+ " or to a folder containing files that 🤗 Datasets can understand."
238
+ ),
239
+ )
240
+ parser.add_argument(
241
+ "--dataset_config_name",
242
+ type=str,
243
+ default=None,
244
+ help="The config of the Dataset, leave as None if there's only one config.",
245
+ )
246
+ parser.add_argument(
247
+ "--train_data_dir",
248
+ type=str,
249
+ default=None,
250
+ help=(
251
+ "A folder containing the training data. Folder contents must follow the structure described in"
252
+ " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
253
+ " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
254
+ ),
255
+ )
256
+ parser.add_argument(
257
+ "--image_column", type=str, default="image", help="The column of the dataset containing an image."
258
+ )
259
+ parser.add_argument(
260
+ "--caption_column",
261
+ type=str,
262
+ default="text",
263
+ help="The column of the dataset containing a caption or a list of captions.",
264
+ )
265
+ parser.add_argument(
266
+ "--validation_prompt",
267
+ type=str,
268
+ default=None,
269
+ help="A prompt that is used during validation to verify that the model is learning.",
270
+ )
271
+ parser.add_argument(
272
+ "--num_validation_images",
273
+ type=int,
274
+ default=4,
275
+ help="Number of images that should be generated during validation with `validation_prompt`.",
276
+ )
277
+ parser.add_argument(
278
+ "--validation_epochs",
279
+ type=int,
280
+ default=1,
281
+ help=(
282
+ "Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
283
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
284
+ ),
285
+ )
286
+ parser.add_argument(
287
+ "--max_train_samples",
288
+ type=int,
289
+ default=None,
290
+ help=(
291
+ "For debugging purposes or quicker training, truncate the number of training examples to this "
292
+ "value if set."
293
+ ),
294
+ )
295
+ parser.add_argument(
296
+ "--proportion_empty_prompts",
297
+ type=float,
298
+ default=0,
299
+ help="Proportion of image prompts to be replaced with empty strings. Defaults to 0 (no prompt replacement).",
300
+ )
301
+ parser.add_argument(
302
+ "--output_dir",
303
+ type=str,
304
+ default="sdxl-model-finetuned",
305
+ help="The output directory where the model predictions and checkpoints will be written.",
306
+ )
307
+ parser.add_argument(
308
+ "--cache_dir",
309
+ type=str,
310
+ default=None,
311
+ help="The directory where the downloaded models and datasets will be stored.",
312
+ )
313
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
314
+ parser.add_argument(
315
+ "--resolution",
316
+ type=int,
317
+ default=1024,
318
+ help=(
319
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
320
+ " resolution"
321
+ ),
322
+ )
323
+ parser.add_argument(
324
+ "--center_crop",
325
+ default=False,
326
+ action="store_true",
327
+ help=(
328
+ "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
329
+ " cropped. The images will be resized to the resolution first before cropping."
330
+ ),
331
+ )
332
+ parser.add_argument(
333
+ "--random_flip",
334
+ action="store_true",
335
+ help="whether to randomly flip images horizontally",
336
+ )
337
+ parser.add_argument(
338
+ "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
339
+ )
340
+ parser.add_argument("--num_train_epochs", type=int, default=100)
341
+ parser.add_argument(
342
+ "--max_train_steps",
343
+ type=int,
344
+ default=None,
345
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
346
+ )
347
+ parser.add_argument(
348
+ "--checkpointing_steps",
349
+ type=int,
350
+ default=500,
351
+ help=(
352
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
353
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
354
+ " training using `--resume_from_checkpoint`."
355
+ ),
356
+ )
357
+ parser.add_argument(
358
+ "--checkpoints_total_limit",
359
+ type=int,
360
+ default=None,
361
+ help=("Max number of checkpoints to store."),
362
+ )
363
+ parser.add_argument(
364
+ "--resume_from_checkpoint",
365
+ type=str,
366
+ default=None,
367
+ help=(
368
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
369
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
370
+ ),
371
+ )
372
+ parser.add_argument(
373
+ "--gradient_accumulation_steps",
374
+ type=int,
375
+ default=1,
376
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
377
+ )
378
+ parser.add_argument(
379
+ "--gradient_checkpointing",
380
+ action="store_true",
381
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
382
+ )
383
+ parser.add_argument(
384
+ "--learning_rate",
385
+ type=float,
386
+ default=1e-4,
387
+ help="Initial learning rate (after the potential warmup period) to use.",
388
+ )
389
+ parser.add_argument(
390
+ "--scale_lr",
391
+ action="store_true",
392
+ default=False,
393
+ help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
394
+ )
395
+ parser.add_argument(
396
+ "--lr_scheduler",
397
+ type=str,
398
+ default="constant",
399
+ help=(
400
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
401
+ ' "constant", "constant_with_warmup"]'
402
+ ),
403
+ )
404
+ parser.add_argument(
405
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
406
+ )
407
+ parser.add_argument(
408
+ "--timestep_bias_strategy",
409
+ type=str,
410
+ default="none",
411
+ choices=["earlier", "later", "range", "none"],
412
+ help=(
413
+ "The timestep bias strategy, which may help direct the model toward learning low or high frequency details."
414
+ " Choices: ['earlier', 'later', 'range', 'none']."
415
+ " The default is 'none', which means no bias is applied, and training proceeds normally."
416
+ " The value of 'later' will increase the frequency of the model's final training timesteps."
417
+ ),
418
+ )
419
+ parser.add_argument(
420
+ "--timestep_bias_multiplier",
421
+ type=float,
422
+ default=1.0,
423
+ help=(
424
+ "The multiplier for the bias. Defaults to 1.0, which means no bias is applied."
425
+ " A value of 2.0 will double the weight of the bias, and a value of 0.5 will halve it."
426
+ ),
427
+ )
428
+ parser.add_argument(
429
+ "--timestep_bias_begin",
430
+ type=int,
431
+ default=0,
432
+ help=(
433
+ "When using `--timestep_bias_strategy=range`, the beginning (inclusive) timestep to bias."
434
+ " Defaults to zero, which equates to having no specific bias."
435
+ ),
436
+ )
437
+ parser.add_argument(
438
+ "--timestep_bias_end",
439
+ type=int,
440
+ default=1000,
441
+ help=(
442
+ "When using `--timestep_bias_strategy=range`, the final timestep (inclusive) to bias."
443
+ " Defaults to 1000, which is the number of timesteps that Stable Diffusion is trained on."
444
+ ),
445
+ )
446
+ parser.add_argument(
447
+ "--timestep_bias_portion",
448
+ type=float,
449
+ default=0.25,
450
+ help=(
451
+ "The portion of timesteps to bias. Defaults to 0.25, which 25% of timesteps will be biased."
452
+ " A value of 0.5 will bias one half of the timesteps. The value provided for `--timestep_bias_strategy` determines"
453
+ " whether the biased portions are in the earlier or later timesteps."
454
+ ),
455
+ )
456
+ parser.add_argument(
457
+ "--snr_gamma",
458
+ type=float,
459
+ default=None,
460
+ help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
461
+ "More details here: https://arxiv.org/abs/2303.09556.",
462
+ )
463
+ parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
464
+ parser.add_argument(
465
+ "--allow_tf32",
466
+ action="store_true",
467
+ help=(
468
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
469
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
470
+ ),
471
+ )
472
+ parser.add_argument(
473
+ "--dataloader_num_workers",
474
+ type=int,
475
+ default=0,
476
+ help=(
477
+ "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
478
+ ),
479
+ )
480
+ parser.add_argument(
481
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
482
+ )
483
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
484
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
485
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
486
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
487
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
488
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
489
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
490
+ parser.add_argument(
491
+ "--prediction_type",
492
+ type=str,
493
+ default=None,
494
+ help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
495
+ )
496
+ parser.add_argument(
497
+ "--hub_model_id",
498
+ type=str,
499
+ default=None,
500
+ help="The name of the repository to keep in sync with the local `output_dir`.",
501
+ )
502
+ parser.add_argument(
503
+ "--logging_dir",
504
+ type=str,
505
+ default="logs",
506
+ help=(
507
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
508
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
509
+ ),
510
+ )
511
+ parser.add_argument(
512
+ "--report_to",
513
+ type=str,
514
+ default="tensorboard",
515
+ help=(
516
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
517
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
518
+ ),
519
+ )
520
+ parser.add_argument(
521
+ "--mixed_precision",
522
+ type=str,
523
+ default=None,
524
+ choices=["no", "fp16", "bf16"],
525
+ help=(
526
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
527
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
528
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
529
+ ),
530
+ )
531
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
532
+ parser.add_argument(
533
+ "--enable_npu_flash_attention", action="store_true", help="Whether or not to use npu flash attention."
534
+ )
535
+ parser.add_argument(
536
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
537
+ )
538
+ parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
539
+
540
+ parser.add_argument(
541
+ "--use_lpl",
542
+ action="store_true",
543
+ help="Whether to use Latent Perceptual Loss (LPL). Increases memory usage.",
544
+ )
545
+ parser.add_argument(
546
+ "--lpl_weight",
547
+ type=float,
548
+ default=1.0,
549
+ help="Weight for the Latent Perceptual Loss.",
550
+ )
551
+ parser.add_argument(
552
+ "--lpl_t_threshold",
553
+ type=int,
554
+ default=200,
555
+ help="Apply LPL only for timesteps t < lpl_t_threshold. Corresponds to high SNR.",
556
+ )
557
+ parser.add_argument(
558
+ "--lpl_loss_type",
559
+ type=str,
560
+ default="mse",
561
+ choices=["mse", "l1"],
562
+ help="Type of loss to use for LPL.",
563
+ )
564
+ parser.add_argument(
565
+ "--lpl_norm_type",
566
+ type=str,
567
+ default="default",
568
+ choices=["default", "shared", "batch"],
569
+ help="Type of normalization to use for LPL features.",
570
+ )
571
+ parser.add_argument(
572
+ "--lpl_pow_law",
573
+ action="store_true",
574
+ help="Whether to use power law weighting for LPL layers.",
575
+ )
576
+ parser.add_argument(
577
+ "--lpl_num_blocks",
578
+ type=int,
579
+ default=4,
580
+ help="Number of up blocks to use for LPL feature extraction.",
581
+ )
582
+ parser.add_argument(
583
+ "--lpl_remove_outliers",
584
+ action="store_true",
585
+ help="Whether to remove outliers in LPL feature maps.",
586
+ )
587
+ parser.add_argument(
588
+ "--lpl_scale",
589
+ action="store_true",
590
+ help="Whether to scale LPL loss by noise level weights.",
591
+ )
592
+ parser.add_argument(
593
+ "--lpl_start",
594
+ type=int,
595
+ default=0,
596
+ help="Step to start applying LPL loss.",
597
+ )
598
+
599
+ if input_args is not None:
600
+ args = parser.parse_args(input_args)
601
+ else:
602
+ args = parser.parse_args()
603
+
604
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
605
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
606
+ args.local_rank = env_local_rank
607
+
608
+ # Sanity checks
609
+ if args.dataset_name is None and args.train_data_dir is None:
610
+ raise ValueError("Need either a dataset name or a training folder.")
611
+ if args.proportion_empty_prompts < 0 or args.proportion_empty_prompts > 1:
612
+ raise ValueError("`--proportion_empty_prompts` must be in the range [0, 1].")
613
+
614
+ return args
615
+
616
+
617
+ # Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
618
+ def encode_prompt(batch, text_encoders, tokenizers, proportion_empty_prompts, caption_column, is_train=True):
619
+ prompt_embeds_list = []
620
+ prompt_batch = batch[caption_column]
621
+
622
+ captions = []
623
+ for caption in prompt_batch:
624
+ if random.random() < proportion_empty_prompts:
625
+ captions.append("")
626
+ elif isinstance(caption, str):
627
+ captions.append(caption)
628
+ elif isinstance(caption, (list, np.ndarray)):
629
+ # take a random caption if there are multiple
630
+ captions.append(random.choice(caption) if is_train else caption[0])
631
+
632
+ with torch.no_grad():
633
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
634
+ text_inputs = tokenizer(
635
+ captions,
636
+ padding="max_length",
637
+ max_length=tokenizer.model_max_length,
638
+ truncation=True,
639
+ return_tensors="pt",
640
+ )
641
+ text_input_ids = text_inputs.input_ids
642
+ prompt_embeds = text_encoder(
643
+ text_input_ids.to(text_encoder.device),
644
+ output_hidden_states=True,
645
+ return_dict=False,
646
+ )
647
+
648
+ # We are only ALWAYS interested in the pooled output of the final text encoder
649
+ pooled_prompt_embeds = prompt_embeds[0]
650
+ prompt_embeds = prompt_embeds[-1][-2]
651
+ bs_embed, seq_len, _ = prompt_embeds.shape
652
+ prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
653
+ prompt_embeds_list.append(prompt_embeds)
654
+
655
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
656
+ pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
657
+ return {"prompt_embeds": prompt_embeds.cpu(), "pooled_prompt_embeds": pooled_prompt_embeds.cpu()}
658
+
659
+
660
+ def compute_vae_encodings(batch, vae):
661
+ images = batch.pop("pixel_values")
662
+ pixel_values = torch.stack(list(images))
663
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
664
+ pixel_values = pixel_values.to(vae.device, dtype=vae.dtype)
665
+
666
+ with torch.no_grad():
667
+ model_input = vae.encode(pixel_values).latent_dist.sample()
668
+ model_input = model_input * vae.config.scaling_factor
669
+
670
+ # There might have slightly performance improvement
671
+ # by changing model_input.cpu() to accelerator.gather(model_input)
672
+ return {"model_input": model_input.cpu()}
673
+
674
+
675
+ def generate_timestep_weights(args, num_timesteps):
676
+ weights = torch.ones(num_timesteps)
677
+
678
+ # Determine the indices to bias
679
+ num_to_bias = int(args.timestep_bias_portion * num_timesteps)
680
+
681
+ if args.timestep_bias_strategy == "later":
682
+ bias_indices = slice(-num_to_bias, None)
683
+ elif args.timestep_bias_strategy == "earlier":
684
+ bias_indices = slice(0, num_to_bias)
685
+ elif args.timestep_bias_strategy == "range":
686
+ # Out of the possible 1000 timesteps, we might want to focus on eg. 200-500.
687
+ range_begin = args.timestep_bias_begin
688
+ range_end = args.timestep_bias_end
689
+ if range_begin < 0:
690
+ raise ValueError(
691
+ "When using the range strategy for timestep bias, you must provide a beginning timestep greater or equal to zero."
692
+ )
693
+ if range_end > num_timesteps:
694
+ raise ValueError(
695
+ "When using the range strategy for timestep bias, you must provide an ending timestep smaller than the number of timesteps."
696
+ )
697
+ bias_indices = slice(range_begin, range_end)
698
+ else: # 'none' or any other string
699
+ return weights
700
+ if args.timestep_bias_multiplier <= 0:
701
+ return ValueError(
702
+ "The parameter --timestep_bias_multiplier is not intended to be used to disable the training of specific timesteps."
703
+ " If it was intended to disable timestep bias, use `--timestep_bias_strategy none` instead."
704
+ " A timestep bias multiplier less than or equal to 0 is not allowed."
705
+ )
706
+
707
+ # Apply the bias
708
+ weights[bias_indices] *= args.timestep_bias_multiplier
709
+
710
+ # Normalize
711
+ weights /= weights.sum()
712
+
713
+ return weights
714
+
715
+
716
+ def main(args):
717
+ if args.report_to == "wandb" and args.hub_token is not None:
718
+ raise ValueError(
719
+ "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
720
+ " Please use `huggingface-cli login` to authenticate with the Hub."
721
+ )
722
+
723
+ logging_dir = Path(args.output_dir, args.logging_dir)
724
+
725
+ accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
726
+
727
+ if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
728
+ # due to pytorch#99272, MPS does not yet support bfloat16.
729
+ raise ValueError(
730
+ "Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
731
+ )
732
+
733
+ accelerator = Accelerator(
734
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
735
+ mixed_precision=args.mixed_precision,
736
+ log_with=args.report_to,
737
+ project_config=accelerator_project_config,
738
+ )
739
+
740
+ # Disable AMP for MPS.
741
+ if torch.backends.mps.is_available():
742
+ accelerator.native_amp = False
743
+
744
+ if args.report_to == "wandb":
745
+ if not is_wandb_available():
746
+ raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
747
+ import wandb
748
+
749
+ # Make one log on every process with the configuration for debugging.
750
+ logging.basicConfig(
751
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
752
+ datefmt="%m/%d/%Y %H:%M:%S",
753
+ level=logging.INFO,
754
+ )
755
+ logger.info(accelerator.state, main_process_only=False)
756
+ if accelerator.is_local_main_process:
757
+ datasets.utils.logging.set_verbosity_warning()
758
+ transformers.utils.logging.set_verbosity_warning()
759
+ diffusers.utils.logging.set_verbosity_info()
760
+ else:
761
+ datasets.utils.logging.set_verbosity_error()
762
+ transformers.utils.logging.set_verbosity_error()
763
+ diffusers.utils.logging.set_verbosity_error()
764
+
765
+ # If passed along, set the training seed now.
766
+ if args.seed is not None:
767
+ set_seed(args.seed)
768
+
769
+ # Handle the repository creation
770
+ if accelerator.is_main_process:
771
+ if args.output_dir is not None:
772
+ os.makedirs(args.output_dir, exist_ok=True)
773
+
774
+ if args.push_to_hub:
775
+ repo_id = create_repo(
776
+ repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
777
+ ).repo_id
778
+
779
+ # Load the tokenizers
780
+ tokenizer_one = AutoTokenizer.from_pretrained(
781
+ args.pretrained_model_name_or_path,
782
+ subfolder="tokenizer",
783
+ revision=args.revision,
784
+ use_fast=False,
785
+ )
786
+ tokenizer_two = AutoTokenizer.from_pretrained(
787
+ args.pretrained_model_name_or_path,
788
+ subfolder="tokenizer_2",
789
+ revision=args.revision,
790
+ use_fast=False,
791
+ )
792
+
793
+ # import correct text encoder classes
794
+ text_encoder_cls_one = import_model_class_from_model_name_or_path(
795
+ args.pretrained_model_name_or_path, args.revision
796
+ )
797
+ text_encoder_cls_two = import_model_class_from_model_name_or_path(
798
+ args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
799
+ )
800
+
801
+ # Load scheduler and models
802
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
803
+ # Check for terminal SNR in combination with SNR Gamma
804
+ text_encoder_one = text_encoder_cls_one.from_pretrained(
805
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
806
+ )
807
+ text_encoder_two = text_encoder_cls_two.from_pretrained(
808
+ args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
809
+ )
810
+ vae_path = (
811
+ args.pretrained_model_name_or_path
812
+ if args.pretrained_vae_model_name_or_path is None
813
+ else args.pretrained_vae_model_name_or_path
814
+ )
815
+ vae = AutoencoderKL.from_pretrained(
816
+ vae_path,
817
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
818
+ revision=args.revision,
819
+ variant=args.variant,
820
+ )
821
+ unet = UNet2DConditionModel.from_pretrained(
822
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
823
+ )
824
+
825
+ # Freeze vae and text encoders.
826
+ vae.requires_grad_(False)
827
+ text_encoder_one.requires_grad_(False)
828
+ text_encoder_two.requires_grad_(False)
829
+ # Set unet as trainable.
830
+ unet.train()
831
+
832
+ # For mixed precision training we cast all non-trainable weights to half-precision
833
+ # as these weights are only used for inference, keeping weights in full precision is not required.
834
+ weight_dtype = torch.float32
835
+ if accelerator.mixed_precision == "fp16":
836
+ weight_dtype = torch.float16
837
+ elif accelerator.mixed_precision == "bf16":
838
+ weight_dtype = torch.bfloat16
839
+
840
+ # Move unet, vae and text_encoder to device and cast to weight_dtype
841
+ # The VAE is in float32 to avoid NaN losses.
842
+ vae.to(accelerator.device, dtype=torch.float32)
843
+ text_encoder_one.to(accelerator.device, dtype=weight_dtype)
844
+ text_encoder_two.to(accelerator.device, dtype=weight_dtype)
845
+
846
+ # Create EMA for the unet.
847
+ if args.use_ema:
848
+ ema_unet = UNet2DConditionModel.from_pretrained(
849
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
850
+ )
851
+ ema_unet = EMAModel(ema_unet.parameters(), model_cls=UNet2DConditionModel, model_config=ema_unet.config)
852
+ if args.enable_npu_flash_attention:
853
+ if is_torch_npu_available():
854
+ logger.info("npu flash attention enabled.")
855
+ unet.enable_npu_flash_attention()
856
+ else:
857
+ raise ValueError("npu flash attention requires torch_npu extensions and is supported only on npu devices.")
858
+ if args.enable_xformers_memory_efficient_attention:
859
+ if is_xformers_available():
860
+ import xformers
861
+
862
+ xformers_version = version.parse(xformers.__version__)
863
+ if xformers_version == version.parse("0.0.16"):
864
+ logger.warning(
865
+ "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."
866
+ )
867
+ unet.enable_xformers_memory_efficient_attention()
868
+ else:
869
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
870
+
871
+ # `accelerate` 0.16.0 will have better support for customized saving
872
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
873
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
874
+ def save_model_hook(models, weights, output_dir):
875
+ if accelerator.is_main_process:
876
+ if args.use_ema:
877
+ ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
878
+
879
+ for i, model in enumerate(models):
880
+ model.save_pretrained(os.path.join(output_dir, "unet"))
881
+
882
+ # make sure to pop weight so that corresponding model is not saved again
883
+ if weights:
884
+ weights.pop()
885
+
886
+ def load_model_hook(models, input_dir):
887
+ if args.use_ema:
888
+ load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
889
+ ema_unet.load_state_dict(load_model.state_dict())
890
+ ema_unet.to(accelerator.device)
891
+ del load_model
892
+
893
+ for _ in range(len(models)):
894
+ # pop models so that they are not loaded again
895
+ model = models.pop()
896
+
897
+ # load diffusers style into model
898
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
899
+ model.register_to_config(**load_model.config)
900
+
901
+ model.load_state_dict(load_model.state_dict())
902
+ del load_model
903
+
904
+ accelerator.register_save_state_pre_hook(save_model_hook)
905
+ accelerator.register_load_state_pre_hook(load_model_hook)
906
+
907
+ if args.gradient_checkpointing:
908
+ unet.enable_gradient_checkpointing()
909
+
910
+ # Enable TF32 for faster training on Ampere GPUs,
911
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
912
+ if args.allow_tf32:
913
+ torch.backends.cuda.matmul.allow_tf32 = True
914
+
915
+ if args.scale_lr:
916
+ args.learning_rate = (
917
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
918
+ )
919
+
920
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
921
+ if args.use_8bit_adam:
922
+ try:
923
+ import bitsandbytes as bnb
924
+ except ImportError:
925
+ raise ImportError(
926
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
927
+ )
928
+
929
+ optimizer_class = bnb.optim.AdamW8bit
930
+ else:
931
+ optimizer_class = torch.optim.AdamW
932
+
933
+ # Optimizer creation
934
+ params_to_optimize = unet.parameters()
935
+ optimizer = optimizer_class(
936
+ params_to_optimize,
937
+ lr=args.learning_rate,
938
+ betas=(args.adam_beta1, args.adam_beta2),
939
+ weight_decay=args.adam_weight_decay,
940
+ eps=args.adam_epsilon,
941
+ )
942
+
943
+ # Get the datasets: you can either provide your own training and evaluation files (see below)
944
+ # or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
945
+
946
+ # In distributed training, the load_dataset function guarantees that only one local process can concurrently
947
+ # download the dataset.
948
+ if args.dataset_name is not None:
949
+ # Downloading and loading a dataset from the hub.
950
+ dataset = load_dataset(
951
+ args.dataset_name, args.dataset_config_name, cache_dir=args.cache_dir, data_dir=args.train_data_dir
952
+ )
953
+ else:
954
+ data_files = {}
955
+ if args.train_data_dir is not None:
956
+ data_files["train"] = os.path.join(args.train_data_dir, "**")
957
+ dataset = load_dataset(
958
+ "imagefolder",
959
+ data_files=data_files,
960
+ cache_dir=args.cache_dir,
961
+ )
962
+ # See more about loading custom images at
963
+ # https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
964
+
965
+ # Preprocessing the datasets.
966
+ # We need to tokenize inputs and targets.
967
+ column_names = dataset["train"].column_names
968
+
969
+ # 6. Get the column names for input/target.
970
+ dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
971
+ if args.image_column is None:
972
+ image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
973
+ else:
974
+ image_column = args.image_column
975
+ if image_column not in column_names:
976
+ raise ValueError(
977
+ f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
978
+ )
979
+ if args.caption_column is None:
980
+ caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
981
+ else:
982
+ caption_column = args.caption_column
983
+ if caption_column not in column_names:
984
+ raise ValueError(
985
+ f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
986
+ )
987
+
988
+ # Preprocessing the datasets.
989
+ train_resize = transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR)
990
+ train_crop = transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution)
991
+ train_flip = transforms.RandomHorizontalFlip(p=1.0)
992
+ train_transforms = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
993
+
994
+ def preprocess_train(examples):
995
+ images = [image.convert("RGB") for image in examples[image_column]]
996
+ # image aug
997
+ original_sizes = []
998
+ all_images = []
999
+ crop_top_lefts = []
1000
+ for image in images:
1001
+ original_sizes.append((image.height, image.width))
1002
+ image = train_resize(image)
1003
+ if args.random_flip and random.random() < 0.5:
1004
+ # flip
1005
+ image = train_flip(image)
1006
+ if args.center_crop:
1007
+ y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
1008
+ x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
1009
+ image = train_crop(image)
1010
+ else:
1011
+ y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
1012
+ image = crop(image, y1, x1, h, w)
1013
+ crop_top_left = (y1, x1)
1014
+ crop_top_lefts.append(crop_top_left)
1015
+ image = train_transforms(image)
1016
+ all_images.append(image)
1017
+
1018
+ examples["original_sizes"] = original_sizes
1019
+ examples["crop_top_lefts"] = crop_top_lefts
1020
+ examples["pixel_values"] = all_images
1021
+ return examples
1022
+
1023
+ with accelerator.main_process_first():
1024
+ if args.max_train_samples is not None:
1025
+ dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
1026
+ # Set the training transforms
1027
+ train_dataset = dataset["train"].with_transform(preprocess_train)
1028
+
1029
+ # Let's first compute all the embeddings so that we can free up the text encoders
1030
+ # from memory. We will pre-compute the VAE encodings too.
1031
+ text_encoders = [text_encoder_one, text_encoder_two]
1032
+ tokenizers = [tokenizer_one, tokenizer_two]
1033
+ compute_embeddings_fn = functools.partial(
1034
+ encode_prompt,
1035
+ text_encoders=text_encoders,
1036
+ tokenizers=tokenizers,
1037
+ proportion_empty_prompts=args.proportion_empty_prompts,
1038
+ caption_column=args.caption_column,
1039
+ )
1040
+ compute_vae_encodings_fn = functools.partial(compute_vae_encodings, vae=vae)
1041
+ with accelerator.main_process_first():
1042
+ from datasets.fingerprint import Hasher
1043
+
1044
+ # fingerprint used by the cache for the other processes to load the result
1045
+ # details: https://github.com/huggingface/diffusers/pull/4038#discussion_r1266078401
1046
+ new_fingerprint = Hasher.hash(args)
1047
+ new_fingerprint_for_vae = Hasher.hash((vae_path, args))
1048
+ train_dataset_with_embeddings = train_dataset.map(
1049
+ compute_embeddings_fn, batched=True, new_fingerprint=new_fingerprint
1050
+ )
1051
+ train_dataset_with_vae = train_dataset.map(
1052
+ compute_vae_encodings_fn,
1053
+ batched=True,
1054
+ batch_size=args.train_batch_size,
1055
+ new_fingerprint=new_fingerprint_for_vae,
1056
+ )
1057
+ precomputed_dataset = concatenate_datasets(
1058
+ [train_dataset_with_embeddings, train_dataset_with_vae.remove_columns(["image", "text"])], axis=1
1059
+ )
1060
+ precomputed_dataset = precomputed_dataset.with_transform(preprocess_train)
1061
+
1062
+ del compute_vae_encodings_fn, compute_embeddings_fn, text_encoder_one, text_encoder_two
1063
+ del text_encoders, tokenizers
1064
+ if not args.use_lpl:
1065
+ del vae
1066
+ gc.collect()
1067
+
1068
+ if is_torch_npu_available():
1069
+ torch_npu.npu.empty_cache()
1070
+ elif torch.cuda.is_available():
1071
+ torch.cuda.empty_cache()
1072
+
1073
+ def collate_fn(examples):
1074
+ model_input = torch.stack([torch.tensor(example["model_input"]) for example in examples])
1075
+ original_sizes = [example["original_sizes"] for example in examples]
1076
+ crop_top_lefts = [example["crop_top_lefts"] for example in examples]
1077
+ prompt_embeds = torch.stack([torch.tensor(example["prompt_embeds"]) for example in examples])
1078
+ pooled_prompt_embeds = torch.stack([torch.tensor(example["pooled_prompt_embeds"]) for example in examples])
1079
+
1080
+ return {
1081
+ "model_input": model_input,
1082
+ "prompt_embeds": prompt_embeds,
1083
+ "pooled_prompt_embeds": pooled_prompt_embeds,
1084
+ "original_sizes": original_sizes,
1085
+ "crop_top_lefts": crop_top_lefts,
1086
+ }
1087
+
1088
+ # DataLoaders creation:
1089
+ train_dataloader = torch.utils.data.DataLoader(
1090
+ precomputed_dataset,
1091
+ shuffle=True,
1092
+ collate_fn=collate_fn,
1093
+ batch_size=args.train_batch_size,
1094
+ num_workers=args.dataloader_num_workers,
1095
+ )
1096
+
1097
+ # Scheduler and math around the number of training steps.
1098
+ overrode_max_train_steps = False
1099
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1100
+ if args.max_train_steps is None:
1101
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1102
+ overrode_max_train_steps = True
1103
+
1104
+ lr_scheduler = get_scheduler(
1105
+ args.lr_scheduler,
1106
+ optimizer=optimizer,
1107
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
1108
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
1109
+ )
1110
+
1111
+ # Prepare everything with our `accelerator`.
1112
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
1113
+ unet, optimizer, train_dataloader, lr_scheduler
1114
+ )
1115
+
1116
+ if args.use_ema:
1117
+ ema_unet.to(accelerator.device)
1118
+
1119
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1120
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1121
+ if overrode_max_train_steps:
1122
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1123
+ # Afterwards we recalculate our number of training epochs
1124
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1125
+
1126
+ # We need to initialize the trackers we use, and also store our configuration.
1127
+ # The trackers initializes automatically on the main process.
1128
+ if accelerator.is_main_process:
1129
+ accelerator.init_trackers("text2image-fine-tune-sdxl", config=vars(args))
1130
+
1131
+ if args.use_lpl:
1132
+ lpl_fn = LatentPerceptualLoss(
1133
+ vae=vae,
1134
+ loss_type=args.lpl_loss_type,
1135
+ grad_ckpt=args.gradient_checkpointing,
1136
+ pow_law=args.lpl_pow_law,
1137
+ norm_type=args.lpl_norm_type,
1138
+ num_mid_blocks=args.lpl_num_blocks,
1139
+ feature_type="feature",
1140
+ remove_outliers=args.lpl_remove_outliers,
1141
+ )
1142
+ lpl_fn.to(accelerator.device)
1143
+ else:
1144
+ lpl_fn = None
1145
+
1146
+ # Function for unwrapping if torch.compile() was used in accelerate.
1147
+ def unwrap_model(model):
1148
+ model = accelerator.unwrap_model(model)
1149
+ model = model._orig_mod if is_compiled_module(model) else model
1150
+ return model
1151
+
1152
+ if torch.backends.mps.is_available() or "playground" in args.pretrained_model_name_or_path:
1153
+ autocast_ctx = nullcontext()
1154
+ else:
1155
+ autocast_ctx = torch.autocast(accelerator.device.type)
1156
+
1157
+ # Train!
1158
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1159
+
1160
+ logger.info("***** Running training *****")
1161
+ logger.info(f" Num examples = {len(precomputed_dataset)}")
1162
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1163
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1164
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1165
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1166
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1167
+ global_step = 0
1168
+ first_epoch = 0
1169
+
1170
+ # Potentially load in the weights and states from a previous save
1171
+ if args.resume_from_checkpoint:
1172
+ if args.resume_from_checkpoint != "latest":
1173
+ path = os.path.basename(args.resume_from_checkpoint)
1174
+ else:
1175
+ # Get the most recent checkpoint
1176
+ dirs = os.listdir(args.output_dir)
1177
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1178
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1179
+ path = dirs[-1] if len(dirs) > 0 else None
1180
+
1181
+ if path is None:
1182
+ accelerator.print(
1183
+ f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
1184
+ )
1185
+ args.resume_from_checkpoint = None
1186
+ initial_global_step = 0
1187
+ else:
1188
+ accelerator.print(f"Resuming from checkpoint {path}")
1189
+ accelerator.load_state(os.path.join(args.output_dir, path))
1190
+ global_step = int(path.split("-")[1])
1191
+
1192
+ initial_global_step = global_step
1193
+ first_epoch = global_step // num_update_steps_per_epoch
1194
+
1195
+ else:
1196
+ initial_global_step = 0
1197
+
1198
+ progress_bar = tqdm(
1199
+ range(0, args.max_train_steps),
1200
+ initial=initial_global_step,
1201
+ desc="Steps",
1202
+ # Only show the progress bar once on each machine.
1203
+ disable=not accelerator.is_local_main_process,
1204
+ )
1205
+
1206
+ # Get scheduler alphas and sigmas for LPL z0_hat calculation
1207
+ alphas_cumprod = noise_scheduler.alphas_cumprod.to(accelerator.device)
1208
+
1209
+ for epoch in range(first_epoch, args.num_train_epochs):
1210
+ train_loss = 0.0
1211
+ for step, batch in enumerate(train_dataloader):
1212
+ with accelerator.accumulate(unet):
1213
+ # Sample noise that we'll add to the latents
1214
+ model_input = batch["model_input"].to(accelerator.device)
1215
+ noise = torch.randn_like(model_input)
1216
+ if args.noise_offset:
1217
+ # https://www.crosslabs.org//blog/diffusion-with-offset-noise
1218
+ noise += args.noise_offset * torch.randn(
1219
+ (model_input.shape[0], model_input.shape[1], 1, 1), device=model_input.device
1220
+ )
1221
+
1222
+ bsz = model_input.shape[0]
1223
+ if args.timestep_bias_strategy == "none":
1224
+ # Sample a random timestep for each image without bias.
1225
+ timesteps = torch.randint(
1226
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=model_input.device
1227
+ )
1228
+ else:
1229
+ # Sample a random timestep for each image, potentially biased by the timestep weights.
1230
+ # Biasing the timestep weights allows us to spend less time training irrelevant timesteps.
1231
+ weights = generate_timestep_weights(args, noise_scheduler.config.num_train_timesteps).to(
1232
+ model_input.device
1233
+ )
1234
+ timesteps = torch.multinomial(weights, bsz, replacement=True).long()
1235
+
1236
+ # Add noise to the model input according to the noise magnitude at each timestep
1237
+ # (this is the forward diffusion process)
1238
+ noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps).to(dtype=weight_dtype)
1239
+
1240
+ # time ids
1241
+ def compute_time_ids(original_size, crops_coords_top_left):
1242
+ # Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
1243
+ target_size = (args.resolution, args.resolution)
1244
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1245
+ add_time_ids = torch.tensor([add_time_ids], device=accelerator.device, dtype=weight_dtype)
1246
+ return add_time_ids
1247
+
1248
+ add_time_ids = torch.cat(
1249
+ [compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
1250
+ )
1251
+
1252
+ # Predict the noise residual
1253
+ unet_added_conditions = {"time_ids": add_time_ids}
1254
+ prompt_embeds = batch["prompt_embeds"].to(accelerator.device, dtype=weight_dtype)
1255
+ pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(accelerator.device)
1256
+ unet_added_conditions.update({"text_embeds": pooled_prompt_embeds})
1257
+ model_pred = unet(
1258
+ noisy_model_input,
1259
+ timesteps,
1260
+ prompt_embeds,
1261
+ added_cond_kwargs=unet_added_conditions,
1262
+ return_dict=False,
1263
+ )[0]
1264
+
1265
+ # Get the target for loss depending on the prediction type
1266
+ if args.prediction_type is not None:
1267
+ # set prediction_type of scheduler if defined
1268
+ noise_scheduler.register_to_config(prediction_type=args.prediction_type)
1269
+
1270
+ if noise_scheduler.config.prediction_type == "epsilon":
1271
+ target = noise
1272
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1273
+ target = noise_scheduler.get_velocity(model_input, noise, timesteps)
1274
+ elif noise_scheduler.config.prediction_type == "sample":
1275
+ # We set the target to latents here, but the model_pred will return the noise sample prediction.
1276
+ target = model_input
1277
+ # We will have to subtract the noise residual from the prediction to get the target sample.
1278
+ model_pred = model_pred - noise
1279
+ else:
1280
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1281
+
1282
+ if args.snr_gamma is None:
1283
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1284
+ else:
1285
+ # Compute loss-weights as per Section 3.4 of https://arxiv.org/abs/2303.09556.
1286
+ # Since we predict the noise instead of x_0, the original formulation is slightly changed.
1287
+ # This is discussed in Section 4.2 of the same paper.
1288
+ snr = compute_snr(noise_scheduler, timesteps)
1289
+ mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
1290
+ dim=1
1291
+ )[0]
1292
+ if noise_scheduler.config.prediction_type == "epsilon":
1293
+ mse_loss_weights = mse_loss_weights / snr
1294
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1295
+ mse_loss_weights = mse_loss_weights / (snr + 1)
1296
+
1297
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
1298
+ loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
1299
+ loss = loss.mean()
1300
+
1301
+ lpl_loss_value = torch.tensor(0.0, device=accelerator.device)
1302
+ if args.use_lpl and lpl_fn is not None and global_step >= args.lpl_start:
1303
+ # Apply LPL only below the timestep threshold
1304
+ lpl_mask = timesteps < args.lpl_t_threshold
1305
+ if lpl_mask.any():
1306
+ # Select samples that meet the threshold
1307
+ masked_indices = torch.where(lpl_mask)[0]
1308
+ z0_masked = model_input[masked_indices]
1309
+ zt_masked = noisy_model_input[masked_indices]
1310
+ t_masked = timesteps[masked_indices]
1311
+ model_pred_masked = model_pred[masked_indices]
1312
+
1313
+ # Calculate z0_hat for the masked samples
1314
+ alpha_t = alphas_cumprod[t_masked].sqrt().to(torch.float32)
1315
+ sigma_t = (1 - alphas_cumprod[t_masked]).sqrt().to(torch.float32)
1316
+ alpha_t = alpha_t.view(-1, 1, 1, 1)
1317
+ sigma_t = sigma_t.view(-1, 1, 1, 1)
1318
+
1319
+ if noise_scheduler.config.prediction_type == "epsilon":
1320
+ z0_hat_masked = (zt_masked.float() - sigma_t * model_pred_masked.float()) / alpha_t
1321
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1322
+ z0_hat_masked = alpha_t * zt_masked.float() - sigma_t * model_pred_masked.float()
1323
+ else: # sample prediction
1324
+ z0_hat_masked = model_pred_masked.float()
1325
+
1326
+ with accelerator.autocast():
1327
+ lpl_loss_value = lpl_fn.get_loss(z0_hat_masked, z0_masked)
1328
+
1329
+ if args.lpl_scale:
1330
+ if args.snr_gamma is not None:
1331
+ # Use SNR-based weights if available
1332
+ snr = compute_snr(noise_scheduler, t_masked)
1333
+ snr_weights = torch.stack(
1334
+ [snr, args.snr_gamma * torch.ones_like(t_masked)], dim=1
1335
+ ).min(dim=1)[0]
1336
+ if noise_scheduler.config.prediction_type == "epsilon":
1337
+ snr_weights = snr_weights / snr
1338
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1339
+ snr_weights = snr_weights / (snr + 1)
1340
+ lpl_loss_value = (lpl_loss_value * snr_weights).mean()
1341
+ else:
1342
+ # If no SNR weighting, just use mean
1343
+ lpl_loss_value = lpl_loss_value.mean()
1344
+ else:
1345
+ lpl_loss_value = lpl_loss_value.mean()
1346
+
1347
+ # Combine losses
1348
+ total_loss = loss + args.lpl_weight * lpl_loss_value
1349
+
1350
+ # Gather the losses across all processes for logging
1351
+ avg_loss = accelerator.gather(total_loss.repeat(args.train_batch_size)).mean()
1352
+ train_loss += avg_loss.item() / args.gradient_accumulation_steps
1353
+
1354
+ # Backpropagate
1355
+ accelerator.backward(total_loss)
1356
+ if accelerator.sync_gradients:
1357
+ params_to_clip = unet.parameters()
1358
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1359
+ optimizer.step()
1360
+ lr_scheduler.step()
1361
+ optimizer.zero_grad()
1362
+
1363
+ # Checks if the accelerator has performed an optimization step behind the scenes
1364
+ if accelerator.sync_gradients:
1365
+ if args.use_ema:
1366
+ ema_unet.step(unet.parameters())
1367
+ progress_bar.update(1)
1368
+ global_step += 1
1369
+
1370
+ # Enhanced logging for LPL metrics
1371
+ log_data = {
1372
+ "train_loss": train_loss,
1373
+ "diffusion_loss": loss.item(),
1374
+ "learning_rate": lr_scheduler.get_last_lr()[0],
1375
+ }
1376
+
1377
+ if args.use_lpl and lpl_fn is not None and global_step >= args.lpl_start:
1378
+ if lpl_mask.any():
1379
+ # LPL application statistics
1380
+ log_data.update(
1381
+ {
1382
+ "lpl/loss": lpl_loss_value.item(),
1383
+ "lpl/num_samples": lpl_mask.sum().item(),
1384
+ "lpl/application_ratio": lpl_mask.float().mean().item(),
1385
+ "lpl/weight": args.lpl_weight,
1386
+ "lpl/weighted_loss": (args.lpl_weight * lpl_loss_value).item(),
1387
+ }
1388
+ )
1389
+
1390
+ # SNR statistics for LPL-applied samples
1391
+ if args.snr_gamma is not None:
1392
+ snr_values = snr[masked_indices]
1393
+ log_data.update(
1394
+ {
1395
+ "lpl/snr_mean": snr_values.mean().item(),
1396
+ "lpl/snr_std": snr_values.std().item(),
1397
+ "lpl/snr_min": snr_values.min().item(),
1398
+ "lpl/snr_max": snr_values.max().item(),
1399
+ }
1400
+ )
1401
+
1402
+ # Feature statistics if available
1403
+ if hasattr(lpl_fn, "last_feature_stats"):
1404
+ for layer_idx, stats in enumerate(lpl_fn.last_feature_stats):
1405
+ log_data.update(
1406
+ {
1407
+ f"lpl/features/layer_{layer_idx}/mean": stats["mean"],
1408
+ f"lpl/features/layer_{layer_idx}/std": stats["std"],
1409
+ f"lpl/features/layer_{layer_idx}/outlier_ratio": stats.get(
1410
+ "outlier_ratio", 0.0
1411
+ ),
1412
+ }
1413
+ )
1414
+
1415
+ # Memory usage if available
1416
+ if torch.cuda.is_available():
1417
+ log_data.update(
1418
+ {
1419
+ "lpl/memory/allocated": torch.cuda.memory_allocated() / 1024**2, # MB
1420
+ "lpl/memory/reserved": torch.cuda.memory_reserved() / 1024**2, # MB
1421
+ }
1422
+ )
1423
+
1424
+ # Log to accelerator
1425
+ accelerator.log(log_data, step=global_step)
1426
+
1427
+ # Update progress bar with more metrics
1428
+ progress_bar_logs = {
1429
+ "loss": loss.detach().item(),
1430
+ "lr": lr_scheduler.get_last_lr()[0],
1431
+ }
1432
+ if args.use_lpl and lpl_loss_value.item() > 0:
1433
+ progress_bar_logs.update(
1434
+ {
1435
+ "lpl": lpl_loss_value.item(),
1436
+ "lpl_ratio": lpl_mask.float().mean().item() if lpl_mask.any() else 0.0,
1437
+ }
1438
+ )
1439
+ progress_bar.set_postfix(**progress_bar_logs)
1440
+
1441
+ # DeepSpeed requires saving weights on every device; saving weights only on the main process would cause issues.
1442
+ if accelerator.distributed_type == DistributedType.DEEPSPEED or accelerator.is_main_process:
1443
+ if global_step % args.checkpointing_steps == 0:
1444
+ # _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
1445
+ if args.checkpoints_total_limit is not None:
1446
+ checkpoints = os.listdir(args.output_dir)
1447
+ checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
1448
+ checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
1449
+
1450
+ # before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
1451
+ if len(checkpoints) >= args.checkpoints_total_limit:
1452
+ num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
1453
+ removing_checkpoints = checkpoints[0:num_to_remove]
1454
+
1455
+ logger.info(
1456
+ f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
1457
+ )
1458
+ logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
1459
+
1460
+ for removing_checkpoint in removing_checkpoints:
1461
+ removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
1462
+ shutil.rmtree(removing_checkpoint)
1463
+
1464
+ save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1465
+ accelerator.save_state(save_path)
1466
+ logger.info(f"Saved state to {save_path}")
1467
+
1468
+ logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1469
+ progress_bar.set_postfix(**logs)
1470
+
1471
+ if global_step >= args.max_train_steps:
1472
+ break
1473
+
1474
+ if accelerator.is_main_process:
1475
+ if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
1476
+ logger.info(
1477
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
1478
+ f" {args.validation_prompt}."
1479
+ )
1480
+ if args.use_ema:
1481
+ # Store the UNet parameters temporarily and load the EMA parameters to perform inference.
1482
+ ema_unet.store(unet.parameters())
1483
+ ema_unet.copy_to(unet.parameters())
1484
+
1485
+ # create pipeline
1486
+ vae = AutoencoderKL.from_pretrained(
1487
+ vae_path,
1488
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
1489
+ revision=args.revision,
1490
+ variant=args.variant,
1491
+ )
1492
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1493
+ args.pretrained_model_name_or_path,
1494
+ vae=vae,
1495
+ unet=accelerator.unwrap_model(unet),
1496
+ revision=args.revision,
1497
+ variant=args.variant,
1498
+ torch_dtype=weight_dtype,
1499
+ )
1500
+ if args.prediction_type is not None:
1501
+ scheduler_args = {"prediction_type": args.prediction_type}
1502
+ pipeline.scheduler = pipeline.scheduler.from_config(pipeline.scheduler.config, **scheduler_args)
1503
+
1504
+ pipeline = pipeline.to(accelerator.device)
1505
+ pipeline.set_progress_bar_config(disable=True)
1506
+
1507
+ # run inference
1508
+ generator = (
1509
+ torch.Generator(device=accelerator.device).manual_seed(args.seed)
1510
+ if args.seed is not None
1511
+ else None
1512
+ )
1513
+ pipeline_args = {"prompt": args.validation_prompt}
1514
+
1515
+ with autocast_ctx:
1516
+ images = [
1517
+ pipeline(**pipeline_args, generator=generator, num_inference_steps=25).images[0]
1518
+ for _ in range(args.num_validation_images)
1519
+ ]
1520
+
1521
+ for tracker in accelerator.trackers:
1522
+ if tracker.name == "tensorboard":
1523
+ np_images = np.stack([np.asarray(img) for img in images])
1524
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
1525
+ if tracker.name == "wandb":
1526
+ tracker.log(
1527
+ {
1528
+ "validation": [
1529
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1530
+ for i, image in enumerate(images)
1531
+ ]
1532
+ }
1533
+ )
1534
+
1535
+ del pipeline
1536
+ if is_torch_npu_available():
1537
+ torch_npu.npu.empty_cache()
1538
+ elif torch.cuda.is_available():
1539
+ torch.cuda.empty_cache()
1540
+
1541
+ if args.use_ema:
1542
+ # Switch back to the original UNet parameters.
1543
+ ema_unet.restore(unet.parameters())
1544
+
1545
+ accelerator.wait_for_everyone()
1546
+ if accelerator.is_main_process:
1547
+ unet = unwrap_model(unet)
1548
+ if args.use_ema:
1549
+ ema_unet.copy_to(unet.parameters())
1550
+
1551
+ # Serialize pipeline.
1552
+ vae = AutoencoderKL.from_pretrained(
1553
+ vae_path,
1554
+ subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
1555
+ revision=args.revision,
1556
+ variant=args.variant,
1557
+ torch_dtype=weight_dtype,
1558
+ )
1559
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
1560
+ args.pretrained_model_name_or_path,
1561
+ unet=unet,
1562
+ vae=vae,
1563
+ revision=args.revision,
1564
+ variant=args.variant,
1565
+ torch_dtype=weight_dtype,
1566
+ )
1567
+ if args.prediction_type is not None:
1568
+ scheduler_args = {"prediction_type": args.prediction_type}
1569
+ pipeline.scheduler = pipeline.scheduler.from_config(pipeline.scheduler.config, **scheduler_args)
1570
+ pipeline.save_pretrained(args.output_dir)
1571
+
1572
+ # run inference
1573
+ images = []
1574
+ if args.validation_prompt and args.num_validation_images > 0:
1575
+ pipeline = pipeline.to(accelerator.device)
1576
+ generator = (
1577
+ torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed is not None else None
1578
+ )
1579
+
1580
+ with autocast_ctx:
1581
+ images = [
1582
+ pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
1583
+ for _ in range(args.num_validation_images)
1584
+ ]
1585
+
1586
+ for tracker in accelerator.trackers:
1587
+ if tracker.name == "tensorboard":
1588
+ np_images = np.stack([np.asarray(img) for img in images])
1589
+ tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC")
1590
+ if tracker.name == "wandb":
1591
+ tracker.log(
1592
+ {
1593
+ "test": [
1594
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1595
+ for i, image in enumerate(images)
1596
+ ]
1597
+ }
1598
+ )
1599
+
1600
+ if args.push_to_hub:
1601
+ save_model_card(
1602
+ repo_id=repo_id,
1603
+ images=images,
1604
+ validation_prompt=args.validation_prompt,
1605
+ base_model=args.pretrained_model_name_or_path,
1606
+ dataset_name=args.dataset_name,
1607
+ repo_folder=args.output_dir,
1608
+ vae_path=args.pretrained_vae_model_name_or_path,
1609
+ )
1610
+ upload_folder(
1611
+ repo_id=repo_id,
1612
+ folder_path=args.output_dir,
1613
+ commit_message="End of training",
1614
+ ignore_patterns=["step_*", "epoch_*"],
1615
+ )
1616
+
1617
+ accelerator.end_training()
1618
+
1619
+
1620
+ if __name__ == "__main__":
1621
+ args = parse_args()
1622
+ main(args)
tasks/tasksmith-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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 hyperparameters to get the best result on your dataset.___
8
+
9
+
10
+ ## Running locally with PyTorch
11
+ ### Installing the dependencies
12
+
13
+ Before running the scripts, make sure to install the library's training dependencies:
14
+
15
+ **Important**
16
+
17
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
18
+ ```bash
19
+ git clone https://github.com/huggingface/diffusers
20
+ cd diffusers
21
+ pip install .
22
+ ```
23
+
24
+ Then cd in the example folder and run
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ ```
28
+
29
+ And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
30
+
31
+ ```bash
32
+ accelerate config
33
+ ```
34
+
35
+ ### 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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/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-d977e5ab6579/tests/source/examples/research_projects/pixart/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ images/
2
+ output/
tasks/tasksmith-d977e5ab6579/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: str | None = "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-d977e5ab6579/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: str | None = "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-d977e5ab6579/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