Stage Harbor release files 66001-66500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/README.md +167 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/accelerate.yaml +17 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/compute_embeddings.py +107 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/ds2.yaml +23 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/train_dreambooth_lora_flux_miniature.py +1200 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/geodiff/README.md +6 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/geodiff/geodiff_molecule_conformation.ipynb +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/README.md +156 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/dataset.py +110 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/demo.ipynb +196 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/generated-images-100000-00.png +3 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/make_datasets.py +119 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/requirements.txt +11 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/train_gligen_text.py +715 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/instructpix2pix_lora/README.md +106 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/instructpix2pix_lora/train_instruct_pix2pix_lora.py +1171 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/README.md +36 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/inference_bf16.py +56 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion/README.md +68 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion/requirements.txt +7 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py +646 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md +93 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt +7 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py +112 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py +996 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/README.md +226 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/requirements.txt +4 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py +415 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py +422 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py +445 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py +520 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/lora/README.md +83 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/lora/requirements.txt +8 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/lora/train_text_to_image_lora.py +1026 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth/README.md +338 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth/requirements.txt +6 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py +1195 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/README.md +93 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/requirements.txt +8 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/train_multi_subject_dreambooth_inpainting.py +661 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/README.md +143 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/multi_token_clip.py +104 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/requirements.txt +6 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/requirements_flax.txt +8 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion.py +937 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion_flax.py +654 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/README.md +5 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/text_to_image/README.md +74 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/text_to_image/requirements.txt +7 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/text_to_image/train_text_to_image.py +954 -0
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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things simple. It should act as a reference to build things further.
|
| 5 |
+
|
| 6 |
+
This example shows how to fine-tune [Flux.1 Dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) with LoRA and quantization. We show this by using the [`Norod78/Yarn-art-style`](https://huggingface.co/datasets/Norod78/Yarn-art-style) dataset. Steps below summarize the workflow:
|
| 7 |
+
|
| 8 |
+
* We precompute the text embeddings in `compute_embeddings.py` and serialize them into a parquet file.
|
| 9 |
+
* Even though optional, we load the T5-xxl in NF4 to further reduce the memory foot-print.
|
| 10 |
+
* `train_dreambooth_lora_flux_miniature.py` takes care of training:
|
| 11 |
+
* Since we already precomputed the text embeddings, we don't load the text encoders.
|
| 12 |
+
* We load the VAE and use it to precompute the image latents and we then delete it.
|
| 13 |
+
* Load the Flux transformer, quantize it with the [NF4 datatype](https://huggingface.co/papers/2305.14314) through `bitsandbytes`, prepare it for 4bit training.
|
| 14 |
+
* Add LoRA adapter layers to it and then ensure they are kept in FP32 precision.
|
| 15 |
+
* Train!
|
| 16 |
+
|
| 17 |
+
To run training in a memory-optimized manner, we additionally use:
|
| 18 |
+
|
| 19 |
+
* 8Bit Adam
|
| 20 |
+
* Gradient checkpointing
|
| 21 |
+
|
| 22 |
+
We have tested the scripts on a 24GB 4090. It works on a free-tier Colab Notebook, too, but it's extremely slow.
|
| 23 |
+
|
| 24 |
+
## Training
|
| 25 |
+
|
| 26 |
+
Ensure you have installed the required libraries:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install -U transformers accelerate bitsandbytes peft datasets
|
| 30 |
+
pip install git+https://github.com/huggingface/diffusers -U
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Now, compute the text embeddings:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
python compute_embeddings.py
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
It should create a file named `embeddings.parquet`. We're then ready to launch training. First, authenticate so that you can access the Flux.1 Dev model:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
huggingface-cli
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Then launch:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
accelerate launch --config_file=accelerate.yaml \
|
| 49 |
+
train_dreambooth_lora_flux_miniature.py \
|
| 50 |
+
--pretrained_model_name_or_path="black-forest-labs/FLUX.1-dev" \
|
| 51 |
+
--data_df_path="embeddings.parquet" \
|
| 52 |
+
--output_dir="yarn_art_lora_flux_nf4" \
|
| 53 |
+
--mixed_precision="fp16" \
|
| 54 |
+
--use_8bit_adam \
|
| 55 |
+
--weighting_scheme="none" \
|
| 56 |
+
--resolution=1024 \
|
| 57 |
+
--train_batch_size=1 \
|
| 58 |
+
--repeats=1 \
|
| 59 |
+
--learning_rate=1e-4 \
|
| 60 |
+
--guidance_scale=1 \
|
| 61 |
+
--report_to="wandb" \
|
| 62 |
+
--gradient_accumulation_steps=4 \
|
| 63 |
+
--gradient_checkpointing \
|
| 64 |
+
--lr_scheduler="constant" \
|
| 65 |
+
--lr_warmup_steps=0 \
|
| 66 |
+
--cache_latents \
|
| 67 |
+
--rank=4 \
|
| 68 |
+
--max_train_steps=700 \
|
| 69 |
+
--seed="0"
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
We can directly pass a quantized checkpoint path, too:
|
| 73 |
+
|
| 74 |
+
```diff
|
| 75 |
+
+ --quantized_model_path="hf-internal-testing/flux.1-dev-nf4-pkg"
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Depending on the machine, training time will vary but for our case, it was 1.5 hours. It maybe possible to speed this up by using `torch.bfloat16`.
|
| 79 |
+
|
| 80 |
+
We support training with the DeepSpeed Zero2 optimizer, too. To use it, first install DeepSpeed:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
pip install -Uq deepspeed
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
And then launch:
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
accelerate launch --config_file=ds2.yaml \
|
| 90 |
+
train_dreambooth_lora_flux_miniature.py \
|
| 91 |
+
--pretrained_model_name_or_path="black-forest-labs/FLUX.1-dev" \
|
| 92 |
+
--data_df_path="embeddings.parquet" \
|
| 93 |
+
--output_dir="yarn_art_lora_flux_nf4" \
|
| 94 |
+
--mixed_precision="no" \
|
| 95 |
+
--use_8bit_adam \
|
| 96 |
+
--weighting_scheme="none" \
|
| 97 |
+
--resolution=1024 \
|
| 98 |
+
--train_batch_size=1 \
|
| 99 |
+
--repeats=1 \
|
| 100 |
+
--learning_rate=1e-4 \
|
| 101 |
+
--guidance_scale=1 \
|
| 102 |
+
--report_to="wandb" \
|
| 103 |
+
--gradient_accumulation_steps=4 \
|
| 104 |
+
--gradient_checkpointing \
|
| 105 |
+
--lr_scheduler="constant" \
|
| 106 |
+
--lr_warmup_steps=0 \
|
| 107 |
+
--cache_latents \
|
| 108 |
+
--rank=4 \
|
| 109 |
+
--max_train_steps=700 \
|
| 110 |
+
--seed="0"
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## Inference
|
| 114 |
+
|
| 115 |
+
When loading the LoRA params (that were obtained on a quantized base model) and merging them into the base model, it is recommended to first dequantize the base model, merge the LoRA params into it, and then quantize the model again. This is because merging into 4bit quantized models can lead to some rounding errors. Below, we provide an end-to-end example:
|
| 116 |
+
|
| 117 |
+
1. First, load the original model and merge the LoRA params into it:
|
| 118 |
+
|
| 119 |
+
```py
|
| 120 |
+
from diffusers import FluxPipeline
|
| 121 |
+
import torch
|
| 122 |
+
|
| 123 |
+
ckpt_id = "black-forest-labs/FLUX.1-dev"
|
| 124 |
+
pipeline = FluxPipeline.from_pretrained(
|
| 125 |
+
ckpt_id, text_encoder=None, text_encoder_2=None, torch_dtype=torch.float16
|
| 126 |
+
)
|
| 127 |
+
pipeline.load_lora_weights("yarn_art_lora_flux_nf4", weight_name="pytorch_lora_weights.safetensors")
|
| 128 |
+
pipeline.fuse_lora()
|
| 129 |
+
pipeline.unload_lora_weights()
|
| 130 |
+
|
| 131 |
+
pipeline.transformer.save_pretrained("fused_transformer")
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
2. Quantize the model and run inference
|
| 135 |
+
|
| 136 |
+
```py
|
| 137 |
+
from diffusers import AutoPipelineForText2Image, FluxTransformer2DModel, BitsAndBytesConfig
|
| 138 |
+
import torch
|
| 139 |
+
|
| 140 |
+
ckpt_id = "black-forest-labs/FLUX.1-dev"
|
| 141 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 142 |
+
nf4_config = BitsAndBytesConfig(
|
| 143 |
+
load_in_4bit=True,
|
| 144 |
+
bnb_4bit_quant_type="nf4",
|
| 145 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 146 |
+
)
|
| 147 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 148 |
+
"fused_transformer",
|
| 149 |
+
quantization_config=nf4_config,
|
| 150 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 151 |
+
)
|
| 152 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 153 |
+
ckpt_id, transformer=transformer, torch_dtype=bnb_4bit_compute_dtype
|
| 154 |
+
)
|
| 155 |
+
pipeline.enable_model_cpu_offload()
|
| 156 |
+
|
| 157 |
+
image = pipeline(
|
| 158 |
+
"a puppy in a pond, yarn art style", num_inference_steps=28, guidance_scale=3.5, height=768
|
| 159 |
+
).images[0]
|
| 160 |
+
image.save("yarn_merged.png")
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
| Dequantize, merge, quantize | Merging directly into quantized model |
|
| 164 |
+
|-------|-------|
|
| 165 |
+
|  |  |
|
| 166 |
+
|
| 167 |
+
As we can notice the first column result follows the style more closely.
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/accelerate.yaml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
distributed_type: NO
|
| 4 |
+
downcast_bf16: 'no'
|
| 5 |
+
enable_cpu_affinity: true
|
| 6 |
+
gpu_ids: all
|
| 7 |
+
machine_rank: 0
|
| 8 |
+
main_training_function: main
|
| 9 |
+
mixed_precision: bf16
|
| 10 |
+
num_machines: 1
|
| 11 |
+
num_processes: 1
|
| 12 |
+
rdzv_backend: static
|
| 13 |
+
same_network: true
|
| 14 |
+
tpu_env: []
|
| 15 |
+
tpu_use_cluster: false
|
| 16 |
+
tpu_use_sudo: false
|
| 17 |
+
use_cpu: false
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/compute_embeddings.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import torch
|
| 21 |
+
from datasets import load_dataset
|
| 22 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 23 |
+
from tqdm.auto import tqdm
|
| 24 |
+
from transformers import T5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers import FluxPipeline
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
MAX_SEQ_LENGTH = 77
|
| 30 |
+
OUTPUT_PATH = "embeddings.parquet"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_image_hash(image):
|
| 34 |
+
return insecure_hashlib.sha256(image.tobytes()).hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_flux_dev_pipeline():
|
| 38 |
+
id = "black-forest-labs/FLUX.1-dev"
|
| 39 |
+
text_encoder = T5EncoderModel.from_pretrained(id, subfolder="text_encoder_2", load_in_8bit=True, device_map="auto")
|
| 40 |
+
pipeline = FluxPipeline.from_pretrained(
|
| 41 |
+
id, text_encoder_2=text_encoder, transformer=None, vae=None, device_map="balanced"
|
| 42 |
+
)
|
| 43 |
+
return pipeline
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@torch.no_grad()
|
| 47 |
+
def compute_embeddings(pipeline, prompts, max_sequence_length):
|
| 48 |
+
all_prompt_embeds = []
|
| 49 |
+
all_pooled_prompt_embeds = []
|
| 50 |
+
all_text_ids = []
|
| 51 |
+
for prompt in tqdm(prompts, desc="Encoding prompts."):
|
| 52 |
+
(
|
| 53 |
+
prompt_embeds,
|
| 54 |
+
pooled_prompt_embeds,
|
| 55 |
+
text_ids,
|
| 56 |
+
) = pipeline.encode_prompt(prompt=prompt, prompt_2=None, max_sequence_length=max_sequence_length)
|
| 57 |
+
all_prompt_embeds.append(prompt_embeds)
|
| 58 |
+
all_pooled_prompt_embeds.append(pooled_prompt_embeds)
|
| 59 |
+
all_text_ids.append(text_ids)
|
| 60 |
+
|
| 61 |
+
max_memory = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024
|
| 62 |
+
print(f"Max memory allocated: {max_memory:.3f} GB")
|
| 63 |
+
return all_prompt_embeds, all_pooled_prompt_embeds, all_text_ids
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def run(args):
|
| 67 |
+
dataset = load_dataset("Norod78/Yarn-art-style", split="train")
|
| 68 |
+
image_prompts = {generate_image_hash(sample["image"]): sample["text"] for sample in dataset}
|
| 69 |
+
all_prompts = list(image_prompts.values())
|
| 70 |
+
print(f"{len(all_prompts)=}")
|
| 71 |
+
|
| 72 |
+
pipeline = load_flux_dev_pipeline()
|
| 73 |
+
all_prompt_embeds, all_pooled_prompt_embeds, all_text_ids = compute_embeddings(
|
| 74 |
+
pipeline, all_prompts, args.max_sequence_length
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
data = []
|
| 78 |
+
for i, (image_hash, _) in enumerate(image_prompts.items()):
|
| 79 |
+
data.append((image_hash, all_prompt_embeds[i], all_pooled_prompt_embeds[i], all_text_ids[i]))
|
| 80 |
+
print(f"{len(data)=}")
|
| 81 |
+
|
| 82 |
+
# Create a DataFrame
|
| 83 |
+
embedding_cols = ["prompt_embeds", "pooled_prompt_embeds", "text_ids"]
|
| 84 |
+
df = pd.DataFrame(data, columns=["image_hash"] + embedding_cols)
|
| 85 |
+
print(f"{len(df)=}")
|
| 86 |
+
|
| 87 |
+
# Convert embedding lists to arrays (for proper storage in parquet)
|
| 88 |
+
for col in embedding_cols:
|
| 89 |
+
df[col] = df[col].apply(lambda x: x.cpu().numpy().flatten().tolist())
|
| 90 |
+
|
| 91 |
+
# Save the dataframe to a parquet file
|
| 92 |
+
df.to_parquet(args.output_path)
|
| 93 |
+
print(f"Data successfully serialized to {args.output_path}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
parser = argparse.ArgumentParser()
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--max_sequence_length",
|
| 100 |
+
type=int,
|
| 101 |
+
default=MAX_SEQ_LENGTH,
|
| 102 |
+
help="Maximum sequence length to use for computing the embeddings. The more the higher computational costs.",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument("--output_path", type=str, default=OUTPUT_PATH, help="Path to serialize the parquet file.")
|
| 105 |
+
args = parser.parse_args()
|
| 106 |
+
|
| 107 |
+
run(args)
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/ds2.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
deepspeed_config:
|
| 4 |
+
gradient_accumulation_steps: 1
|
| 5 |
+
gradient_clipping: 1.0
|
| 6 |
+
offload_optimizer_device: cpu
|
| 7 |
+
offload_param_device: cpu
|
| 8 |
+
zero3_init_flag: false
|
| 9 |
+
zero_stage: 2
|
| 10 |
+
distributed_type: DEEPSPEED
|
| 11 |
+
downcast_bf16: 'no'
|
| 12 |
+
enable_cpu_affinity: false
|
| 13 |
+
machine_rank: 0
|
| 14 |
+
main_training_function: main
|
| 15 |
+
mixed_precision: 'no'
|
| 16 |
+
num_machines: 1
|
| 17 |
+
num_processes: 1
|
| 18 |
+
rdzv_backend: static
|
| 19 |
+
same_network: true
|
| 20 |
+
tpu_env: []
|
| 21 |
+
tpu_use_cluster: false
|
| 22 |
+
tpu_use_sudo: false
|
| 23 |
+
use_cpu: false
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/flux_lora_quantization/train_dreambooth_lora_flux_miniature.py
ADDED
|
@@ -0,0 +1,1200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import copy
|
| 18 |
+
import logging
|
| 19 |
+
import math
|
| 20 |
+
import os
|
| 21 |
+
import random
|
| 22 |
+
import shutil
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pandas as pd
|
| 27 |
+
import torch
|
| 28 |
+
import torch.utils.checkpoint
|
| 29 |
+
import transformers
|
| 30 |
+
from accelerate import Accelerator, DistributedType
|
| 31 |
+
from accelerate.logging import get_logger
|
| 32 |
+
from accelerate.utils import DistributedDataParallelKwargs, ProjectConfiguration, set_seed
|
| 33 |
+
from datasets import load_dataset
|
| 34 |
+
from huggingface_hub import create_repo, upload_folder
|
| 35 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 36 |
+
from peft import LoraConfig, prepare_model_for_kbit_training, set_peft_model_state_dict
|
| 37 |
+
from peft.utils import get_peft_model_state_dict
|
| 38 |
+
from PIL.ImageOps import exif_transpose
|
| 39 |
+
from torch.utils.data import Dataset
|
| 40 |
+
from torchvision import transforms
|
| 41 |
+
from torchvision.transforms.functional import crop
|
| 42 |
+
from tqdm.auto import tqdm
|
| 43 |
+
|
| 44 |
+
import diffusers
|
| 45 |
+
from diffusers import (
|
| 46 |
+
AutoencoderKL,
|
| 47 |
+
BitsAndBytesConfig,
|
| 48 |
+
FlowMatchEulerDiscreteScheduler,
|
| 49 |
+
FluxPipeline,
|
| 50 |
+
FluxTransformer2DModel,
|
| 51 |
+
)
|
| 52 |
+
from diffusers.optimization import get_scheduler
|
| 53 |
+
from diffusers.training_utils import (
|
| 54 |
+
cast_training_params,
|
| 55 |
+
compute_density_for_timestep_sampling,
|
| 56 |
+
compute_loss_weighting_for_sd3,
|
| 57 |
+
free_memory,
|
| 58 |
+
)
|
| 59 |
+
from diffusers.utils import (
|
| 60 |
+
check_min_version,
|
| 61 |
+
convert_unet_state_dict_to_peft,
|
| 62 |
+
is_wandb_available,
|
| 63 |
+
)
|
| 64 |
+
from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
|
| 65 |
+
from diffusers.utils.torch_utils import is_compiled_module
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if is_wandb_available():
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 72 |
+
check_min_version("0.31.0.dev0")
|
| 73 |
+
|
| 74 |
+
logger = get_logger(__name__)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def save_model_card(
|
| 78 |
+
repo_id: str,
|
| 79 |
+
base_model: str = None,
|
| 80 |
+
instance_prompt=None,
|
| 81 |
+
repo_folder=None,
|
| 82 |
+
quantization_config=None,
|
| 83 |
+
):
|
| 84 |
+
widget_dict = []
|
| 85 |
+
|
| 86 |
+
model_description = f"""
|
| 87 |
+
# Flux DreamBooth LoRA - {repo_id}
|
| 88 |
+
|
| 89 |
+
<Gallery />
|
| 90 |
+
|
| 91 |
+
## Model description
|
| 92 |
+
|
| 93 |
+
These are {repo_id} DreamBooth LoRA weights for {base_model}.
|
| 94 |
+
|
| 95 |
+
The weights were trained using [DreamBooth](https://dreambooth.github.io/) with the [Flux diffusers trainer](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_flux.md).
|
| 96 |
+
|
| 97 |
+
Was LoRA for the text encoder enabled? False.
|
| 98 |
+
|
| 99 |
+
Quantization config:
|
| 100 |
+
|
| 101 |
+
```yaml
|
| 102 |
+
{quantization_config}
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
## Trigger words
|
| 106 |
+
|
| 107 |
+
You should use `{instance_prompt}` to trigger the image generation.
|
| 108 |
+
|
| 109 |
+
## Download model
|
| 110 |
+
|
| 111 |
+
[Download the *.safetensors LoRA]({repo_id}/tree/main) in the Files & versions tab.
|
| 112 |
+
|
| 113 |
+
For more details, including weighting, merging and fusing LoRAs, check the [documentation on loading LoRAs in diffusers](https://huggingface.co/docs/diffusers/main/en/using-diffusers/loading_adapters)
|
| 114 |
+
|
| 115 |
+
## Usage
|
| 116 |
+
|
| 117 |
+
TODO
|
| 118 |
+
|
| 119 |
+
## License
|
| 120 |
+
|
| 121 |
+
Please adhere to the licensing terms as described [here](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md).
|
| 122 |
+
"""
|
| 123 |
+
model_card = load_or_create_model_card(
|
| 124 |
+
repo_id_or_path=repo_id,
|
| 125 |
+
from_training=True,
|
| 126 |
+
license="other",
|
| 127 |
+
base_model=base_model,
|
| 128 |
+
prompt=instance_prompt,
|
| 129 |
+
model_description=model_description,
|
| 130 |
+
widget=widget_dict,
|
| 131 |
+
)
|
| 132 |
+
tags = [
|
| 133 |
+
"text-to-image",
|
| 134 |
+
"diffusers-training",
|
| 135 |
+
"diffusers",
|
| 136 |
+
"lora",
|
| 137 |
+
"flux",
|
| 138 |
+
"flux-diffusers",
|
| 139 |
+
"template:sd-lora",
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
model_card = populate_model_card(model_card, tags=tags)
|
| 143 |
+
model_card.save(os.path.join(repo_folder, "README.md"))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def parse_args(input_args=None):
|
| 147 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--pretrained_model_name_or_path",
|
| 150 |
+
type=str,
|
| 151 |
+
default=None,
|
| 152 |
+
required=True,
|
| 153 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument(
|
| 156 |
+
"--quantized_model_path",
|
| 157 |
+
type=str,
|
| 158 |
+
default=None,
|
| 159 |
+
help="Path to the quantized model.",
|
| 160 |
+
)
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--revision",
|
| 163 |
+
type=str,
|
| 164 |
+
default=None,
|
| 165 |
+
required=False,
|
| 166 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 167 |
+
)
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--variant",
|
| 170 |
+
type=str,
|
| 171 |
+
default=None,
|
| 172 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--data_df_path",
|
| 176 |
+
type=str,
|
| 177 |
+
default=None,
|
| 178 |
+
help=("Path to the parquet file serialized with compute_embeddings.py."),
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--cache_dir",
|
| 183 |
+
type=str,
|
| 184 |
+
default=None,
|
| 185 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument("--repeats", type=int, default=1, help="How many times to repeat the training data.")
|
| 188 |
+
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--max_sequence_length",
|
| 191 |
+
type=int,
|
| 192 |
+
default=77,
|
| 193 |
+
help="Used for reading the embeddings. Needs to be the same as used during `compute_embeddings.py`.",
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--rank",
|
| 198 |
+
type=int,
|
| 199 |
+
default=4,
|
| 200 |
+
help=("The dimension of the LoRA update matrices."),
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--output_dir",
|
| 205 |
+
type=str,
|
| 206 |
+
default="flux-dreambooth-lora-nf4",
|
| 207 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--resolution",
|
| 212 |
+
type=int,
|
| 213 |
+
default=512,
|
| 214 |
+
help=(
|
| 215 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 216 |
+
" resolution"
|
| 217 |
+
),
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--center_crop",
|
| 221 |
+
default=False,
|
| 222 |
+
action="store_true",
|
| 223 |
+
help=(
|
| 224 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 225 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 226 |
+
),
|
| 227 |
+
)
|
| 228 |
+
parser.add_argument(
|
| 229 |
+
"--random_flip",
|
| 230 |
+
action="store_true",
|
| 231 |
+
help="whether to randomly flip images horizontally",
|
| 232 |
+
)
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 240 |
+
parser.add_argument(
|
| 241 |
+
"--max_train_steps",
|
| 242 |
+
type=int,
|
| 243 |
+
default=None,
|
| 244 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--checkpointing_steps",
|
| 248 |
+
type=int,
|
| 249 |
+
default=500,
|
| 250 |
+
help=(
|
| 251 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 252 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 253 |
+
" training using `--resume_from_checkpoint`."
|
| 254 |
+
),
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"--checkpoints_total_limit",
|
| 258 |
+
type=int,
|
| 259 |
+
default=None,
|
| 260 |
+
help=("Max number of checkpoints to store."),
|
| 261 |
+
)
|
| 262 |
+
parser.add_argument(
|
| 263 |
+
"--resume_from_checkpoint",
|
| 264 |
+
type=str,
|
| 265 |
+
default=None,
|
| 266 |
+
help=(
|
| 267 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 268 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 269 |
+
),
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--gradient_accumulation_steps",
|
| 273 |
+
type=int,
|
| 274 |
+
default=1,
|
| 275 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 276 |
+
)
|
| 277 |
+
parser.add_argument(
|
| 278 |
+
"--gradient_checkpointing",
|
| 279 |
+
action="store_true",
|
| 280 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 281 |
+
)
|
| 282 |
+
parser.add_argument(
|
| 283 |
+
"--learning_rate",
|
| 284 |
+
type=float,
|
| 285 |
+
default=1e-4,
|
| 286 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
parser.add_argument(
|
| 290 |
+
"--guidance_scale",
|
| 291 |
+
type=float,
|
| 292 |
+
default=3.5,
|
| 293 |
+
help="the FLUX.1 dev variant is a guidance distilled model",
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
parser.add_argument(
|
| 297 |
+
"--scale_lr",
|
| 298 |
+
action="store_true",
|
| 299 |
+
default=False,
|
| 300 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 301 |
+
)
|
| 302 |
+
parser.add_argument(
|
| 303 |
+
"--lr_scheduler",
|
| 304 |
+
type=str,
|
| 305 |
+
default="constant",
|
| 306 |
+
help=(
|
| 307 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 308 |
+
' "constant", "constant_with_warmup"]'
|
| 309 |
+
),
|
| 310 |
+
)
|
| 311 |
+
parser.add_argument(
|
| 312 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 313 |
+
)
|
| 314 |
+
parser.add_argument(
|
| 315 |
+
"--lr_num_cycles",
|
| 316 |
+
type=int,
|
| 317 |
+
default=1,
|
| 318 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 319 |
+
)
|
| 320 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 321 |
+
parser.add_argument(
|
| 322 |
+
"--dataloader_num_workers",
|
| 323 |
+
type=int,
|
| 324 |
+
default=0,
|
| 325 |
+
help=(
|
| 326 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 327 |
+
),
|
| 328 |
+
)
|
| 329 |
+
parser.add_argument(
|
| 330 |
+
"--weighting_scheme",
|
| 331 |
+
type=str,
|
| 332 |
+
default="none",
|
| 333 |
+
choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
|
| 334 |
+
help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'),
|
| 335 |
+
)
|
| 336 |
+
parser.add_argument(
|
| 337 |
+
"--logit_mean", type=float, default=0.0, help="mean to use when using the `'logit_normal'` weighting scheme."
|
| 338 |
+
)
|
| 339 |
+
parser.add_argument(
|
| 340 |
+
"--logit_std", type=float, default=1.0, help="std to use when using the `'logit_normal'` weighting scheme."
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument(
|
| 343 |
+
"--mode_scale",
|
| 344 |
+
type=float,
|
| 345 |
+
default=1.29,
|
| 346 |
+
help="Scale of mode weighting scheme. Only effective when using the `'mode'` as the `weighting_scheme`.",
|
| 347 |
+
)
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--optimizer",
|
| 350 |
+
type=str,
|
| 351 |
+
default="AdamW",
|
| 352 |
+
choices=["AdamW", "Prodigy", "AdEMAMix"],
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
parser.add_argument(
|
| 356 |
+
"--use_8bit_adam",
|
| 357 |
+
action="store_true",
|
| 358 |
+
help="Whether or not to use 8-bit Adam from bitsandbytes. Ignored if optimizer is not set to AdamW",
|
| 359 |
+
)
|
| 360 |
+
parser.add_argument(
|
| 361 |
+
"--use_8bit_ademamix",
|
| 362 |
+
action="store_true",
|
| 363 |
+
help="Whether or not to use 8-bit AdEMAMix from bitsandbytes.",
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
parser.add_argument(
|
| 367 |
+
"--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam and Prodigy optimizers."
|
| 368 |
+
)
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam and Prodigy optimizers."
|
| 371 |
+
)
|
| 372 |
+
parser.add_argument(
|
| 373 |
+
"--prodigy_beta3",
|
| 374 |
+
type=float,
|
| 375 |
+
default=None,
|
| 376 |
+
help="coefficients for computing the Prodigy stepsize using running averages. If set to None, "
|
| 377 |
+
"uses the value of square root of beta2. Ignored if optimizer is adamW",
|
| 378 |
+
)
|
| 379 |
+
parser.add_argument("--prodigy_decouple", type=bool, default=True, help="Use AdamW style decoupled weight decay")
|
| 380 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-04, help="Weight decay to use for unet params")
|
| 381 |
+
|
| 382 |
+
parser.add_argument(
|
| 383 |
+
"--adam_epsilon",
|
| 384 |
+
type=float,
|
| 385 |
+
default=1e-08,
|
| 386 |
+
help="Epsilon value for the Adam optimizer and Prodigy optimizers.",
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
parser.add_argument(
|
| 390 |
+
"--prodigy_use_bias_correction",
|
| 391 |
+
type=bool,
|
| 392 |
+
default=True,
|
| 393 |
+
help="Turn on Adam's bias correction. True by default. Ignored if optimizer is adamW",
|
| 394 |
+
)
|
| 395 |
+
parser.add_argument(
|
| 396 |
+
"--prodigy_safeguard_warmup",
|
| 397 |
+
type=bool,
|
| 398 |
+
default=True,
|
| 399 |
+
help="Remove lr from the denominator of D estimate to avoid issues during warm-up stage. True by default. "
|
| 400 |
+
"Ignored if optimizer is adamW",
|
| 401 |
+
)
|
| 402 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 403 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 404 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 405 |
+
parser.add_argument(
|
| 406 |
+
"--hub_model_id",
|
| 407 |
+
type=str,
|
| 408 |
+
default=None,
|
| 409 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 410 |
+
)
|
| 411 |
+
parser.add_argument(
|
| 412 |
+
"--logging_dir",
|
| 413 |
+
type=str,
|
| 414 |
+
default="logs",
|
| 415 |
+
help=(
|
| 416 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 417 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 418 |
+
),
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
parser.add_argument(
|
| 422 |
+
"--cache_latents",
|
| 423 |
+
action="store_true",
|
| 424 |
+
default=False,
|
| 425 |
+
help="Cache the VAE latents",
|
| 426 |
+
)
|
| 427 |
+
parser.add_argument(
|
| 428 |
+
"--report_to",
|
| 429 |
+
type=str,
|
| 430 |
+
default="tensorboard",
|
| 431 |
+
help=(
|
| 432 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 433 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 434 |
+
),
|
| 435 |
+
)
|
| 436 |
+
parser.add_argument(
|
| 437 |
+
"--mixed_precision",
|
| 438 |
+
type=str,
|
| 439 |
+
default=None,
|
| 440 |
+
choices=["no", "fp16", "bf16"],
|
| 441 |
+
help=(
|
| 442 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 443 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 444 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 445 |
+
),
|
| 446 |
+
)
|
| 447 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 448 |
+
|
| 449 |
+
if input_args is not None:
|
| 450 |
+
args = parser.parse_args(input_args)
|
| 451 |
+
else:
|
| 452 |
+
args = parser.parse_args()
|
| 453 |
+
|
| 454 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 455 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 456 |
+
args.local_rank = env_local_rank
|
| 457 |
+
|
| 458 |
+
return args
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class DreamBoothDataset(Dataset):
|
| 462 |
+
def __init__(
|
| 463 |
+
self,
|
| 464 |
+
data_df_path,
|
| 465 |
+
dataset_name,
|
| 466 |
+
size=1024,
|
| 467 |
+
max_sequence_length=77,
|
| 468 |
+
center_crop=False,
|
| 469 |
+
):
|
| 470 |
+
# Logistics
|
| 471 |
+
self.size = size
|
| 472 |
+
self.center_crop = center_crop
|
| 473 |
+
self.max_sequence_length = max_sequence_length
|
| 474 |
+
|
| 475 |
+
self.data_df_path = Path(data_df_path)
|
| 476 |
+
if not self.data_df_path.exists():
|
| 477 |
+
raise ValueError("`data_df_path` doesn't exists.")
|
| 478 |
+
|
| 479 |
+
# Load images.
|
| 480 |
+
dataset = load_dataset(dataset_name, split="train")
|
| 481 |
+
instance_images = [sample["image"] for sample in dataset]
|
| 482 |
+
image_hashes = [self.generate_image_hash(image) for image in instance_images]
|
| 483 |
+
self.instance_images = instance_images
|
| 484 |
+
self.image_hashes = image_hashes
|
| 485 |
+
|
| 486 |
+
# Image transformations
|
| 487 |
+
self.pixel_values = self.apply_image_transformations(
|
| 488 |
+
instance_images=instance_images, size=size, center_crop=center_crop
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
# Map hashes to embeddings.
|
| 492 |
+
self.data_dict = self.map_image_hash_embedding(data_df_path=data_df_path)
|
| 493 |
+
|
| 494 |
+
self.num_instance_images = len(instance_images)
|
| 495 |
+
self._length = self.num_instance_images
|
| 496 |
+
|
| 497 |
+
def __len__(self):
|
| 498 |
+
return self._length
|
| 499 |
+
|
| 500 |
+
def __getitem__(self, index):
|
| 501 |
+
example = {}
|
| 502 |
+
instance_image = self.pixel_values[index % self.num_instance_images]
|
| 503 |
+
image_hash = self.image_hashes[index % self.num_instance_images]
|
| 504 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.data_dict[image_hash]
|
| 505 |
+
example["instance_images"] = instance_image
|
| 506 |
+
example["prompt_embeds"] = prompt_embeds
|
| 507 |
+
example["pooled_prompt_embeds"] = pooled_prompt_embeds
|
| 508 |
+
example["text_ids"] = text_ids
|
| 509 |
+
return example
|
| 510 |
+
|
| 511 |
+
def apply_image_transformations(self, instance_images, size, center_crop):
|
| 512 |
+
pixel_values = []
|
| 513 |
+
|
| 514 |
+
train_resize = transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 515 |
+
train_crop = transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size)
|
| 516 |
+
train_flip = transforms.RandomHorizontalFlip(p=1.0)
|
| 517 |
+
train_transforms = transforms.Compose(
|
| 518 |
+
[
|
| 519 |
+
transforms.ToTensor(),
|
| 520 |
+
transforms.Normalize([0.5], [0.5]),
|
| 521 |
+
]
|
| 522 |
+
)
|
| 523 |
+
for image in instance_images:
|
| 524 |
+
image = exif_transpose(image)
|
| 525 |
+
if not image.mode == "RGB":
|
| 526 |
+
image = image.convert("RGB")
|
| 527 |
+
image = train_resize(image)
|
| 528 |
+
if args.random_flip and random.random() < 0.5:
|
| 529 |
+
# flip
|
| 530 |
+
image = train_flip(image)
|
| 531 |
+
if args.center_crop:
|
| 532 |
+
y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
|
| 533 |
+
x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
|
| 534 |
+
image = train_crop(image)
|
| 535 |
+
else:
|
| 536 |
+
y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
|
| 537 |
+
image = crop(image, y1, x1, h, w)
|
| 538 |
+
image = train_transforms(image)
|
| 539 |
+
pixel_values.append(image)
|
| 540 |
+
|
| 541 |
+
return pixel_values
|
| 542 |
+
|
| 543 |
+
def convert_to_torch_tensor(self, embeddings: list):
|
| 544 |
+
prompt_embeds = embeddings[0]
|
| 545 |
+
pooled_prompt_embeds = embeddings[1]
|
| 546 |
+
text_ids = embeddings[2]
|
| 547 |
+
prompt_embeds = np.array(prompt_embeds).reshape(self.max_sequence_length, 4096)
|
| 548 |
+
pooled_prompt_embeds = np.array(pooled_prompt_embeds).reshape(768)
|
| 549 |
+
text_ids = np.array(text_ids).reshape(77, 3)
|
| 550 |
+
return torch.from_numpy(prompt_embeds), torch.from_numpy(pooled_prompt_embeds), torch.from_numpy(text_ids)
|
| 551 |
+
|
| 552 |
+
def map_image_hash_embedding(self, data_df_path):
|
| 553 |
+
hashes_df = pd.read_parquet(data_df_path)
|
| 554 |
+
data_dict = {}
|
| 555 |
+
for i, row in hashes_df.iterrows():
|
| 556 |
+
embeddings = [row["prompt_embeds"], row["pooled_prompt_embeds"], row["text_ids"]]
|
| 557 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.convert_to_torch_tensor(embeddings=embeddings)
|
| 558 |
+
data_dict.update({row["image_hash"]: (prompt_embeds, pooled_prompt_embeds, text_ids)})
|
| 559 |
+
return data_dict
|
| 560 |
+
|
| 561 |
+
def generate_image_hash(self, image):
|
| 562 |
+
return insecure_hashlib.sha256(image.tobytes()).hexdigest()
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def collate_fn(examples):
|
| 566 |
+
pixel_values = [example["instance_images"] for example in examples]
|
| 567 |
+
prompt_embeds = [example["prompt_embeds"] for example in examples]
|
| 568 |
+
pooled_prompt_embeds = [example["pooled_prompt_embeds"] for example in examples]
|
| 569 |
+
text_ids = [example["text_ids"] for example in examples]
|
| 570 |
+
|
| 571 |
+
pixel_values = torch.stack(pixel_values)
|
| 572 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 573 |
+
prompt_embeds = torch.stack(prompt_embeds)
|
| 574 |
+
pooled_prompt_embeds = torch.stack(pooled_prompt_embeds)
|
| 575 |
+
text_ids = torch.stack(text_ids)[0] # just 2D tensor
|
| 576 |
+
|
| 577 |
+
batch = {
|
| 578 |
+
"pixel_values": pixel_values,
|
| 579 |
+
"prompt_embeds": prompt_embeds,
|
| 580 |
+
"pooled_prompt_embeds": pooled_prompt_embeds,
|
| 581 |
+
"text_ids": text_ids,
|
| 582 |
+
}
|
| 583 |
+
return batch
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def main(args):
|
| 587 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 588 |
+
raise ValueError(
|
| 589 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 590 |
+
" Please use `huggingface-cli login` to authenticate with the Hub."
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
|
| 594 |
+
# due to pytorch#99272, MPS does not yet support bfloat16.
|
| 595 |
+
raise ValueError(
|
| 596 |
+
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 600 |
+
|
| 601 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 602 |
+
kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
|
| 603 |
+
accelerator = Accelerator(
|
| 604 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 605 |
+
mixed_precision=args.mixed_precision,
|
| 606 |
+
log_with=args.report_to,
|
| 607 |
+
project_config=accelerator_project_config,
|
| 608 |
+
kwargs_handlers=[kwargs],
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# Disable AMP for MPS.
|
| 612 |
+
if torch.backends.mps.is_available():
|
| 613 |
+
accelerator.native_amp = False
|
| 614 |
+
|
| 615 |
+
if args.report_to == "wandb":
|
| 616 |
+
if not is_wandb_available():
|
| 617 |
+
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
|
| 618 |
+
|
| 619 |
+
# Make one log on every process with the configuration for debugging.
|
| 620 |
+
logging.basicConfig(
|
| 621 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 622 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 623 |
+
level=logging.INFO,
|
| 624 |
+
)
|
| 625 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 626 |
+
if accelerator.is_local_main_process:
|
| 627 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 628 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 629 |
+
else:
|
| 630 |
+
transformers.utils.logging.set_verbosity_error()
|
| 631 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 632 |
+
|
| 633 |
+
# If passed along, set the training seed now.
|
| 634 |
+
if args.seed is not None:
|
| 635 |
+
set_seed(args.seed)
|
| 636 |
+
|
| 637 |
+
# Handle the repository creation
|
| 638 |
+
if accelerator.is_main_process:
|
| 639 |
+
if args.output_dir is not None:
|
| 640 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 641 |
+
|
| 642 |
+
if args.push_to_hub:
|
| 643 |
+
repo_id = create_repo(
|
| 644 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name,
|
| 645 |
+
exist_ok=True,
|
| 646 |
+
).repo_id
|
| 647 |
+
|
| 648 |
+
# Load scheduler and models
|
| 649 |
+
noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
| 650 |
+
args.pretrained_model_name_or_path, subfolder="scheduler"
|
| 651 |
+
)
|
| 652 |
+
noise_scheduler_copy = copy.deepcopy(noise_scheduler)
|
| 653 |
+
vae = AutoencoderKL.from_pretrained(
|
| 654 |
+
args.pretrained_model_name_or_path,
|
| 655 |
+
subfolder="vae",
|
| 656 |
+
revision=args.revision,
|
| 657 |
+
variant=args.variant,
|
| 658 |
+
)
|
| 659 |
+
bnb_4bit_compute_dtype = torch.float32
|
| 660 |
+
if args.mixed_precision == "fp16":
|
| 661 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 662 |
+
elif args.mixed_precision == "bf16":
|
| 663 |
+
bnb_4bit_compute_dtype = torch.bfloat16
|
| 664 |
+
if args.quantized_model_path is not None:
|
| 665 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 666 |
+
args.quantized_model_path,
|
| 667 |
+
subfolder="transformer",
|
| 668 |
+
revision=args.revision,
|
| 669 |
+
variant=args.variant,
|
| 670 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 671 |
+
)
|
| 672 |
+
else:
|
| 673 |
+
nf4_config = BitsAndBytesConfig(
|
| 674 |
+
load_in_4bit=True,
|
| 675 |
+
bnb_4bit_quant_type="nf4",
|
| 676 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 677 |
+
)
|
| 678 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 679 |
+
args.pretrained_model_name_or_path,
|
| 680 |
+
subfolder="transformer",
|
| 681 |
+
revision=args.revision,
|
| 682 |
+
variant=args.variant,
|
| 683 |
+
quantization_config=nf4_config,
|
| 684 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 685 |
+
)
|
| 686 |
+
transformer = prepare_model_for_kbit_training(transformer, use_gradient_checkpointing=False)
|
| 687 |
+
|
| 688 |
+
# We only train the additional adapter LoRA layers
|
| 689 |
+
transformer.requires_grad_(False)
|
| 690 |
+
vae.requires_grad_(False)
|
| 691 |
+
|
| 692 |
+
# For mixed precision training we cast all non-trainable weights (vae, text_encoder and transformer) to half-precision
|
| 693 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 694 |
+
weight_dtype = torch.float32
|
| 695 |
+
if accelerator.mixed_precision == "fp16":
|
| 696 |
+
weight_dtype = torch.float16
|
| 697 |
+
elif accelerator.mixed_precision == "bf16":
|
| 698 |
+
weight_dtype = torch.bfloat16
|
| 699 |
+
|
| 700 |
+
if torch.backends.mps.is_available() and weight_dtype == torch.bfloat16:
|
| 701 |
+
# due to pytorch#99272, MPS does not yet support bfloat16.
|
| 702 |
+
raise ValueError(
|
| 703 |
+
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 707 |
+
if args.gradient_checkpointing:
|
| 708 |
+
transformer.enable_gradient_checkpointing()
|
| 709 |
+
|
| 710 |
+
# now we will add new LoRA weights to the attention layers
|
| 711 |
+
transformer_lora_config = LoraConfig(
|
| 712 |
+
r=args.rank,
|
| 713 |
+
lora_alpha=args.rank,
|
| 714 |
+
init_lora_weights="gaussian",
|
| 715 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 716 |
+
)
|
| 717 |
+
transformer.add_adapter(transformer_lora_config)
|
| 718 |
+
|
| 719 |
+
def unwrap_model(model):
|
| 720 |
+
model = accelerator.unwrap_model(model)
|
| 721 |
+
model = model._orig_mod if is_compiled_module(model) else model
|
| 722 |
+
return model
|
| 723 |
+
|
| 724 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 725 |
+
def save_model_hook(models, weights, output_dir):
|
| 726 |
+
if accelerator.is_main_process:
|
| 727 |
+
transformer_lora_layers_to_save = None
|
| 728 |
+
|
| 729 |
+
for model in models:
|
| 730 |
+
if isinstance(unwrap_model(model), type(unwrap_model(transformer))):
|
| 731 |
+
model = unwrap_model(model)
|
| 732 |
+
transformer_lora_layers_to_save = get_peft_model_state_dict(model)
|
| 733 |
+
else:
|
| 734 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 735 |
+
|
| 736 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 737 |
+
if weights:
|
| 738 |
+
weights.pop()
|
| 739 |
+
|
| 740 |
+
FluxPipeline.save_lora_weights(
|
| 741 |
+
output_dir,
|
| 742 |
+
transformer_lora_layers=transformer_lora_layers_to_save,
|
| 743 |
+
text_encoder_lora_layers=None,
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
def load_model_hook(models, input_dir):
|
| 747 |
+
transformer_ = None
|
| 748 |
+
|
| 749 |
+
if not accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 750 |
+
while len(models) > 0:
|
| 751 |
+
model = models.pop()
|
| 752 |
+
|
| 753 |
+
if isinstance(model, type(unwrap_model(transformer))):
|
| 754 |
+
transformer_ = model
|
| 755 |
+
else:
|
| 756 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 757 |
+
else:
|
| 758 |
+
if args.quantized_model_path is not None:
|
| 759 |
+
transformer_ = FluxTransformer2DModel.from_pretrained(
|
| 760 |
+
args.quantized_model_path,
|
| 761 |
+
subfolder="transformer",
|
| 762 |
+
revision=args.revision,
|
| 763 |
+
variant=args.variant,
|
| 764 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 765 |
+
)
|
| 766 |
+
else:
|
| 767 |
+
nf4_config = BitsAndBytesConfig(
|
| 768 |
+
load_in_4bit=True,
|
| 769 |
+
bnb_4bit_quant_type="nf4",
|
| 770 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 771 |
+
)
|
| 772 |
+
transformer_ = FluxTransformer2DModel.from_pretrained(
|
| 773 |
+
args.pretrained_model_name_or_path,
|
| 774 |
+
subfolder="transformer",
|
| 775 |
+
revision=args.revision,
|
| 776 |
+
variant=args.variant,
|
| 777 |
+
quantization_config=nf4_config,
|
| 778 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 779 |
+
)
|
| 780 |
+
transformer_ = prepare_model_for_kbit_training(transformer_, use_gradient_checkpointing=False)
|
| 781 |
+
transformer_.add_adapter(transformer_lora_config)
|
| 782 |
+
|
| 783 |
+
lora_state_dict = FluxPipeline.lora_state_dict(input_dir)
|
| 784 |
+
|
| 785 |
+
transformer_state_dict = {
|
| 786 |
+
f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.")
|
| 787 |
+
}
|
| 788 |
+
transformer_state_dict = convert_unet_state_dict_to_peft(transformer_state_dict)
|
| 789 |
+
incompatible_keys = set_peft_model_state_dict(transformer_, transformer_state_dict, adapter_name="default")
|
| 790 |
+
if incompatible_keys is not None:
|
| 791 |
+
# check only for unexpected keys
|
| 792 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 793 |
+
if unexpected_keys:
|
| 794 |
+
logger.warning(
|
| 795 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 796 |
+
f" {unexpected_keys}. "
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
# Make sure the trainable params are in float32. This is again needed since the base models
|
| 800 |
+
# are in `weight_dtype`. More details:
|
| 801 |
+
# https://github.com/huggingface/diffusers/pull/6514#discussion_r1449796804
|
| 802 |
+
if args.mixed_precision == "fp16":
|
| 803 |
+
models = [transformer_]
|
| 804 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 805 |
+
cast_training_params(models)
|
| 806 |
+
|
| 807 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 808 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 809 |
+
|
| 810 |
+
if args.scale_lr:
|
| 811 |
+
args.learning_rate = (
|
| 812 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
# Make sure the trainable params are in float32.
|
| 816 |
+
if args.mixed_precision == "fp16":
|
| 817 |
+
models = [transformer]
|
| 818 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 819 |
+
cast_training_params(models, dtype=torch.float32)
|
| 820 |
+
|
| 821 |
+
transformer_lora_parameters = list(filter(lambda p: p.requires_grad, transformer.parameters()))
|
| 822 |
+
|
| 823 |
+
# Optimization parameters
|
| 824 |
+
transformer_parameters_with_lr = {"params": transformer_lora_parameters, "lr": args.learning_rate}
|
| 825 |
+
params_to_optimize = [transformer_parameters_with_lr]
|
| 826 |
+
|
| 827 |
+
# Optimizer creation
|
| 828 |
+
if args.use_8bit_adam and not args.optimizer.lower() == "adamw":
|
| 829 |
+
logger.warning(
|
| 830 |
+
f"use_8bit_adam is ignored when optimizer is not set to 'AdamW'. Optimizer was "
|
| 831 |
+
f"set to {args.optimizer.lower()}"
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
if args.use_8bit_ademamix and not args.optimizer.lower() == "ademamix":
|
| 835 |
+
logger.warning(
|
| 836 |
+
f"use_8bit_ademamix is ignored when optimizer is not set to 'AdEMAMix'. Optimizer was "
|
| 837 |
+
f"set to {args.optimizer.lower()}"
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
if args.optimizer.lower() == "adamw":
|
| 841 |
+
if args.use_8bit_adam:
|
| 842 |
+
try:
|
| 843 |
+
import bitsandbytes as bnb
|
| 844 |
+
except ImportError:
|
| 845 |
+
raise ImportError(
|
| 846 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 850 |
+
else:
|
| 851 |
+
optimizer_class = torch.optim.AdamW
|
| 852 |
+
|
| 853 |
+
optimizer = optimizer_class(
|
| 854 |
+
params_to_optimize,
|
| 855 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 856 |
+
weight_decay=args.adam_weight_decay,
|
| 857 |
+
eps=args.adam_epsilon,
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
elif args.optimizer.lower() == "ademamix":
|
| 861 |
+
try:
|
| 862 |
+
import bitsandbytes as bnb
|
| 863 |
+
except ImportError:
|
| 864 |
+
raise ImportError(
|
| 865 |
+
"To use AdEMAMix (or its 8bit variant), please install the bitsandbytes library: `pip install -U bitsandbytes`."
|
| 866 |
+
)
|
| 867 |
+
if args.use_8bit_ademamix:
|
| 868 |
+
optimizer_class = bnb.optim.AdEMAMix8bit
|
| 869 |
+
else:
|
| 870 |
+
optimizer_class = bnb.optim.AdEMAMix
|
| 871 |
+
|
| 872 |
+
optimizer = optimizer_class(params_to_optimize)
|
| 873 |
+
|
| 874 |
+
if args.optimizer.lower() == "prodigy":
|
| 875 |
+
try:
|
| 876 |
+
import prodigyopt
|
| 877 |
+
except ImportError:
|
| 878 |
+
raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`")
|
| 879 |
+
|
| 880 |
+
optimizer_class = prodigyopt.Prodigy
|
| 881 |
+
|
| 882 |
+
if args.learning_rate <= 0.1:
|
| 883 |
+
logger.warning(
|
| 884 |
+
"Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0"
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
optimizer = optimizer_class(
|
| 888 |
+
params_to_optimize,
|
| 889 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 890 |
+
beta3=args.prodigy_beta3,
|
| 891 |
+
weight_decay=args.adam_weight_decay,
|
| 892 |
+
eps=args.adam_epsilon,
|
| 893 |
+
decouple=args.prodigy_decouple,
|
| 894 |
+
use_bias_correction=args.prodigy_use_bias_correction,
|
| 895 |
+
safeguard_warmup=args.prodigy_safeguard_warmup,
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
# Dataset and DataLoaders creation:
|
| 899 |
+
train_dataset = DreamBoothDataset(
|
| 900 |
+
data_df_path=args.data_df_path,
|
| 901 |
+
dataset_name="Norod78/Yarn-art-style",
|
| 902 |
+
size=args.resolution,
|
| 903 |
+
max_sequence_length=args.max_sequence_length,
|
| 904 |
+
center_crop=args.center_crop,
|
| 905 |
+
)
|
| 906 |
+
|
| 907 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 908 |
+
train_dataset,
|
| 909 |
+
batch_size=args.train_batch_size,
|
| 910 |
+
shuffle=True,
|
| 911 |
+
collate_fn=collate_fn,
|
| 912 |
+
num_workers=args.dataloader_num_workers,
|
| 913 |
+
)
|
| 914 |
+
|
| 915 |
+
vae_config_shift_factor = vae.config.shift_factor
|
| 916 |
+
vae_config_scaling_factor = vae.config.scaling_factor
|
| 917 |
+
vae_config_block_out_channels = vae.config.block_out_channels
|
| 918 |
+
if args.cache_latents:
|
| 919 |
+
latents_cache = []
|
| 920 |
+
for batch in tqdm(train_dataloader, desc="Caching latents"):
|
| 921 |
+
with torch.no_grad():
|
| 922 |
+
batch["pixel_values"] = batch["pixel_values"].to(
|
| 923 |
+
accelerator.device, non_blocking=True, dtype=weight_dtype
|
| 924 |
+
)
|
| 925 |
+
latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist)
|
| 926 |
+
|
| 927 |
+
del vae
|
| 928 |
+
free_memory()
|
| 929 |
+
|
| 930 |
+
# Scheduler and math around the number of training steps.
|
| 931 |
+
overrode_max_train_steps = False
|
| 932 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 933 |
+
if args.max_train_steps is None:
|
| 934 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 935 |
+
overrode_max_train_steps = True
|
| 936 |
+
|
| 937 |
+
lr_scheduler = get_scheduler(
|
| 938 |
+
args.lr_scheduler,
|
| 939 |
+
optimizer=optimizer,
|
| 940 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 941 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 942 |
+
num_cycles=args.lr_num_cycles,
|
| 943 |
+
power=args.lr_power,
|
| 944 |
+
)
|
| 945 |
+
|
| 946 |
+
# Prepare everything with our `accelerator`.
|
| 947 |
+
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 948 |
+
transformer, optimizer, train_dataloader, lr_scheduler
|
| 949 |
+
)
|
| 950 |
+
|
| 951 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 952 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 953 |
+
if overrode_max_train_steps:
|
| 954 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 955 |
+
# Afterwards we recalculate our number of training epochs
|
| 956 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 957 |
+
|
| 958 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 959 |
+
# The trackers initializes automatically on the main process.
|
| 960 |
+
if accelerator.is_main_process:
|
| 961 |
+
tracker_name = "dreambooth-flux-dev-lora-nf4"
|
| 962 |
+
accelerator.init_trackers(tracker_name, config=vars(args))
|
| 963 |
+
|
| 964 |
+
# Train!
|
| 965 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 966 |
+
|
| 967 |
+
logger.info("***** Running training *****")
|
| 968 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 969 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 970 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 971 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 972 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 973 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 974 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 975 |
+
global_step = 0
|
| 976 |
+
first_epoch = 0
|
| 977 |
+
|
| 978 |
+
# Potentially load in the weights and states from a previous save
|
| 979 |
+
if args.resume_from_checkpoint:
|
| 980 |
+
if args.resume_from_checkpoint != "latest":
|
| 981 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 982 |
+
else:
|
| 983 |
+
# Get the mos recent checkpoint
|
| 984 |
+
dirs = os.listdir(args.output_dir)
|
| 985 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 986 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 987 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 988 |
+
|
| 989 |
+
if path is None:
|
| 990 |
+
accelerator.print(
|
| 991 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 992 |
+
)
|
| 993 |
+
args.resume_from_checkpoint = None
|
| 994 |
+
initial_global_step = 0
|
| 995 |
+
else:
|
| 996 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 997 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 998 |
+
global_step = int(path.split("-")[1])
|
| 999 |
+
|
| 1000 |
+
initial_global_step = global_step
|
| 1001 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 1002 |
+
|
| 1003 |
+
else:
|
| 1004 |
+
initial_global_step = 0
|
| 1005 |
+
|
| 1006 |
+
progress_bar = tqdm(
|
| 1007 |
+
range(0, args.max_train_steps),
|
| 1008 |
+
initial=initial_global_step,
|
| 1009 |
+
desc="Steps",
|
| 1010 |
+
# Only show the progress bar once on each machine.
|
| 1011 |
+
disable=not accelerator.is_local_main_process,
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
|
| 1015 |
+
sigmas = noise_scheduler_copy.sigmas.to(device=accelerator.device, dtype=dtype)
|
| 1016 |
+
schedule_timesteps = noise_scheduler_copy.timesteps.to(accelerator.device)
|
| 1017 |
+
timesteps = timesteps.to(accelerator.device)
|
| 1018 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 1019 |
+
|
| 1020 |
+
sigma = sigmas[step_indices].flatten()
|
| 1021 |
+
while len(sigma.shape) < n_dim:
|
| 1022 |
+
sigma = sigma.unsqueeze(-1)
|
| 1023 |
+
return sigma
|
| 1024 |
+
|
| 1025 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 1026 |
+
transformer.train()
|
| 1027 |
+
|
| 1028 |
+
for step, batch in enumerate(train_dataloader):
|
| 1029 |
+
models_to_accumulate = [transformer]
|
| 1030 |
+
with accelerator.accumulate(models_to_accumulate):
|
| 1031 |
+
# Convert images to latent space
|
| 1032 |
+
if args.cache_latents:
|
| 1033 |
+
model_input = latents_cache[step].sample()
|
| 1034 |
+
else:
|
| 1035 |
+
pixel_values = batch["pixel_values"].to(dtype=vae.dtype)
|
| 1036 |
+
model_input = vae.encode(pixel_values).latent_dist.sample()
|
| 1037 |
+
model_input = (model_input - vae_config_shift_factor) * vae_config_scaling_factor
|
| 1038 |
+
model_input = model_input.to(dtype=weight_dtype)
|
| 1039 |
+
|
| 1040 |
+
vae_scale_factor = 2 ** (len(vae_config_block_out_channels) - 1)
|
| 1041 |
+
|
| 1042 |
+
latent_image_ids = FluxPipeline._prepare_latent_image_ids(
|
| 1043 |
+
model_input.shape[0],
|
| 1044 |
+
model_input.shape[2] // 2,
|
| 1045 |
+
model_input.shape[3] // 2,
|
| 1046 |
+
accelerator.device,
|
| 1047 |
+
weight_dtype,
|
| 1048 |
+
)
|
| 1049 |
+
# Sample noise that we'll add to the latents
|
| 1050 |
+
noise = torch.randn_like(model_input)
|
| 1051 |
+
bsz = model_input.shape[0]
|
| 1052 |
+
|
| 1053 |
+
# Sample a random timestep for each image
|
| 1054 |
+
# for weighting schemes where we sample timesteps non-uniformly
|
| 1055 |
+
u = compute_density_for_timestep_sampling(
|
| 1056 |
+
weighting_scheme=args.weighting_scheme,
|
| 1057 |
+
batch_size=bsz,
|
| 1058 |
+
logit_mean=args.logit_mean,
|
| 1059 |
+
logit_std=args.logit_std,
|
| 1060 |
+
mode_scale=args.mode_scale,
|
| 1061 |
+
)
|
| 1062 |
+
indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
|
| 1063 |
+
timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device)
|
| 1064 |
+
|
| 1065 |
+
# Add noise according to flow matching.
|
| 1066 |
+
# zt = (1 - texp) * x + texp * z1
|
| 1067 |
+
sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype)
|
| 1068 |
+
noisy_model_input = (1.0 - sigmas) * model_input + sigmas * noise
|
| 1069 |
+
|
| 1070 |
+
packed_noisy_model_input = FluxPipeline._pack_latents(
|
| 1071 |
+
noisy_model_input,
|
| 1072 |
+
batch_size=model_input.shape[0],
|
| 1073 |
+
num_channels_latents=model_input.shape[1],
|
| 1074 |
+
height=model_input.shape[2],
|
| 1075 |
+
width=model_input.shape[3],
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
# handle guidance
|
| 1079 |
+
if unwrap_model(transformer).config.guidance_embeds:
|
| 1080 |
+
guidance = torch.tensor([args.guidance_scale], device=accelerator.device)
|
| 1081 |
+
guidance = guidance.expand(model_input.shape[0])
|
| 1082 |
+
else:
|
| 1083 |
+
guidance = None
|
| 1084 |
+
|
| 1085 |
+
# Predict the noise
|
| 1086 |
+
prompt_embeds = batch["prompt_embeds"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1087 |
+
pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1088 |
+
text_ids = batch["text_ids"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1089 |
+
model_pred = transformer(
|
| 1090 |
+
hidden_states=packed_noisy_model_input,
|
| 1091 |
+
# YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transformer model (we should not keep it but I want to keep the inputs same for the model for testing)
|
| 1092 |
+
timestep=timesteps / 1000,
|
| 1093 |
+
guidance=guidance,
|
| 1094 |
+
pooled_projections=pooled_prompt_embeds,
|
| 1095 |
+
encoder_hidden_states=prompt_embeds,
|
| 1096 |
+
txt_ids=text_ids,
|
| 1097 |
+
img_ids=latent_image_ids,
|
| 1098 |
+
return_dict=False,
|
| 1099 |
+
)[0]
|
| 1100 |
+
model_pred = FluxPipeline._unpack_latents(
|
| 1101 |
+
model_pred,
|
| 1102 |
+
height=model_input.shape[2] * vae_scale_factor,
|
| 1103 |
+
width=model_input.shape[3] * vae_scale_factor,
|
| 1104 |
+
vae_scale_factor=vae_scale_factor,
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
# these weighting schemes use a uniform timestep sampling
|
| 1108 |
+
# and instead post-weight the loss
|
| 1109 |
+
weighting = compute_loss_weighting_for_sd3(weighting_scheme=args.weighting_scheme, sigmas=sigmas)
|
| 1110 |
+
|
| 1111 |
+
# flow matching loss
|
| 1112 |
+
target = noise - model_input
|
| 1113 |
+
|
| 1114 |
+
# Compute regular loss.
|
| 1115 |
+
loss = torch.mean(
|
| 1116 |
+
(weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
|
| 1117 |
+
1,
|
| 1118 |
+
)
|
| 1119 |
+
loss = loss.mean()
|
| 1120 |
+
accelerator.backward(loss)
|
| 1121 |
+
|
| 1122 |
+
if accelerator.sync_gradients:
|
| 1123 |
+
params_to_clip = transformer.parameters()
|
| 1124 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 1125 |
+
|
| 1126 |
+
optimizer.step()
|
| 1127 |
+
lr_scheduler.step()
|
| 1128 |
+
optimizer.zero_grad()
|
| 1129 |
+
|
| 1130 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1131 |
+
if accelerator.sync_gradients:
|
| 1132 |
+
progress_bar.update(1)
|
| 1133 |
+
global_step += 1
|
| 1134 |
+
|
| 1135 |
+
if accelerator.is_main_process or accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 1136 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1137 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1138 |
+
if args.checkpoints_total_limit is not None:
|
| 1139 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1140 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1141 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1142 |
+
|
| 1143 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1144 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1145 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1146 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1147 |
+
|
| 1148 |
+
logger.info(
|
| 1149 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1150 |
+
)
|
| 1151 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1152 |
+
|
| 1153 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1154 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1155 |
+
shutil.rmtree(removing_checkpoint)
|
| 1156 |
+
|
| 1157 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1158 |
+
accelerator.save_state(save_path)
|
| 1159 |
+
logger.info(f"Saved state to {save_path}")
|
| 1160 |
+
|
| 1161 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1162 |
+
progress_bar.set_postfix(**logs)
|
| 1163 |
+
accelerator.log(logs, step=global_step)
|
| 1164 |
+
|
| 1165 |
+
if global_step >= args.max_train_steps:
|
| 1166 |
+
break
|
| 1167 |
+
|
| 1168 |
+
# Save the lora layers
|
| 1169 |
+
accelerator.wait_for_everyone()
|
| 1170 |
+
if accelerator.is_main_process:
|
| 1171 |
+
transformer = unwrap_model(transformer)
|
| 1172 |
+
transformer_lora_layers = get_peft_model_state_dict(transformer)
|
| 1173 |
+
|
| 1174 |
+
FluxPipeline.save_lora_weights(
|
| 1175 |
+
save_directory=args.output_dir,
|
| 1176 |
+
transformer_lora_layers=transformer_lora_layers,
|
| 1177 |
+
text_encoder_lora_layers=None,
|
| 1178 |
+
)
|
| 1179 |
+
|
| 1180 |
+
if args.push_to_hub:
|
| 1181 |
+
save_model_card(
|
| 1182 |
+
repo_id,
|
| 1183 |
+
base_model=args.pretrained_model_name_or_path,
|
| 1184 |
+
instance_prompt=None,
|
| 1185 |
+
repo_folder=args.output_dir,
|
| 1186 |
+
quantization_config=transformer.config["quantization_config"],
|
| 1187 |
+
)
|
| 1188 |
+
upload_folder(
|
| 1189 |
+
repo_id=repo_id,
|
| 1190 |
+
folder_path=args.output_dir,
|
| 1191 |
+
commit_message="End of training",
|
| 1192 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
accelerator.end_training()
|
| 1196 |
+
|
| 1197 |
+
|
| 1198 |
+
if __name__ == "__main__":
|
| 1199 |
+
args = parse_args()
|
| 1200 |
+
main(args)
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/geodiff/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GeoDiff
|
| 2 |
+
|
| 3 |
+
> [!TIP]
|
| 4 |
+
> This notebook is not actively maintained by the Diffusers team. For any questions or comments, please contact [natolambert](https://twitter.com/natolambert).
|
| 5 |
+
|
| 6 |
+
This is an experimental research notebook demonstrating how to generate stable 3D structures of molecules with [GeoDiff](https://github.com/MinkaiXu/GeoDiff) and Diffusers.
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/geodiff/geodiff_molecule_conformation.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GLIGEN: Open-Set Grounded Text-to-Image Generation
|
| 2 |
+
|
| 3 |
+
These scripts contain the code to prepare the grounding data and train the GLIGEN model on COCO dataset.
|
| 4 |
+
|
| 5 |
+
### Install the requirements
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
conda create -n diffusers python==3.10
|
| 9 |
+
conda activate diffusers
|
| 10 |
+
pip install -r requirements.txt
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
accelerate config
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
Or for a default accelerate configuration without answering questions about your environment
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
accelerate config default
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
Or if your environment doesn't support an interactive shell e.g. a notebook
|
| 26 |
+
|
| 27 |
+
```python
|
| 28 |
+
from accelerate.utils import write_basic_config
|
| 29 |
+
|
| 30 |
+
write_basic_config()
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
### Prepare the training data
|
| 34 |
+
|
| 35 |
+
If you want to make your own grounding data, you need to install the requirements.
|
| 36 |
+
|
| 37 |
+
I used [RAM](https://github.com/xinyu1205/recognize-anything) to tag
|
| 38 |
+
images, [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO/issues?q=refer) to detect objects,
|
| 39 |
+
and [BLIP2](https://huggingface.co/docs/transformers/en/model_doc/blip-2) to caption instances.
|
| 40 |
+
|
| 41 |
+
Only RAM needs to be installed manually:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
pip install git+https://github.com/xinyu1205/recognize-anything.git --no-deps
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Download the pre-trained model:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
huggingface-cli download --resume-download xinyu1205/recognize_anything_model ram_swin_large_14m.pth
|
| 51 |
+
huggingface-cli download --resume-download IDEA-Research/grounding-dino-base
|
| 52 |
+
huggingface-cli download --resume-download Salesforce/blip2-flan-t5-xxl
|
| 53 |
+
huggingface-cli download --resume-download clip-vit-large-patch14
|
| 54 |
+
huggingface-cli download --resume-download masterful/gligen-1-4-generation-text-box
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Make the training data on 8 GPUs:
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
torchrun --master_port 17673 --nproc_per_node=8 make_datasets.py \
|
| 61 |
+
--data_root /mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017 \
|
| 62 |
+
--save_root /root/gligen_data \
|
| 63 |
+
--ram_checkpoint /root/.cache/huggingface/hub/models--xinyu1205--recognize_anything_model/snapshots/ebc52dc741e86466202a5ab8ab22eae6e7d48bf1/ram_swin_large_14m.pth
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
You can download the COCO training data from
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
huggingface-cli download --resume-download Hzzone/GLIGEN_COCO coco_train2017.pth
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
It's in the format of
|
| 73 |
+
|
| 74 |
+
```json
|
| 75 |
+
[
|
| 76 |
+
...
|
| 77 |
+
{
|
| 78 |
+
'file_path': Path,
|
| 79 |
+
'annos': [
|
| 80 |
+
{
|
| 81 |
+
'caption': Instance
|
| 82 |
+
Caption,
|
| 83 |
+
'bbox': bbox
|
| 84 |
+
in
|
| 85 |
+
xyxy,
|
| 86 |
+
'text_embeddings_before_projection': CLIP
|
| 87 |
+
text
|
| 88 |
+
embedding
|
| 89 |
+
before
|
| 90 |
+
linear
|
| 91 |
+
projection
|
| 92 |
+
}
|
| 93 |
+
]
|
| 94 |
+
}
|
| 95 |
+
...
|
| 96 |
+
]
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
### Training commands
|
| 100 |
+
|
| 101 |
+
The training script is heavily based
|
| 102 |
+
on https://github.com/huggingface/diffusers/blob/main/examples/controlnet/train_controlnet.py
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
accelerate launch train_gligen_text.py \
|
| 106 |
+
--data_path /root/data/zhizhonghuang/coco_train2017.pth \
|
| 107 |
+
--image_path /mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017 \
|
| 108 |
+
--train_batch_size 8 \
|
| 109 |
+
--max_train_steps 100000 \
|
| 110 |
+
--checkpointing_steps 1000 \
|
| 111 |
+
--checkpoints_total_limit 10 \
|
| 112 |
+
--learning_rate 5e-5 \
|
| 113 |
+
--dataloader_num_workers 16 \
|
| 114 |
+
--mixed_precision fp16 \
|
| 115 |
+
--report_to wandb \
|
| 116 |
+
--tracker_project_name gligen \
|
| 117 |
+
--output_dir /root/data/zhizhonghuang/ckpt/GLIGEN_Text_Retrain_COCO
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
I trained the model on 8 A100 GPUs for about 11 hours (at least 24GB GPU memory). The generated images will follow the
|
| 121 |
+
layout possibly at 50k iterations.
|
| 122 |
+
|
| 123 |
+
Note that although the pre-trained GLIGEN model has been loaded, the parameters of `fuser` and `position_net` have been reset (see line 420 in `train_gligen_text.py`)
|
| 124 |
+
|
| 125 |
+
The trained model can be downloaded from
|
| 126 |
+
|
| 127 |
+
```bash
|
| 128 |
+
huggingface-cli download --resume-download Hzzone/GLIGEN_COCO config.json diffusion_pytorch_model.safetensors
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
You can run `demo.ipynb` to visualize the generated images.
|
| 132 |
+
|
| 133 |
+
Example prompts:
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
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'
|
| 137 |
+
boxes = [[0.041015625, 0.548828125, 0.453125, 0.859375],
|
| 138 |
+
[0.525390625, 0.552734375, 0.93359375, 0.865234375],
|
| 139 |
+
[0.12890625, 0.015625, 0.412109375, 0.279296875],
|
| 140 |
+
[0.578125, 0.08203125, 0.857421875, 0.27734375]]
|
| 141 |
+
gligen_phrases = ['a green car', 'a blue truck', 'a red air balloon', 'a bird']
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Example images:
|
| 145 |
+

|
| 146 |
+
|
| 147 |
+
### Citation
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
@article{li2023gligen,
|
| 151 |
+
title={GLIGEN: Open-Set Grounded Text-to-Image Generation},
|
| 152 |
+
author={Li, Yuheng and Liu, Haotian and Wu, Qingyang and Mu, Fangzhou and Yang, Jianwei and Gao, Jianfeng and Li, Chunyuan and Lee, Yong Jae},
|
| 153 |
+
journal={CVPR},
|
| 154 |
+
year={2023}
|
| 155 |
+
}
|
| 156 |
+
```
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/dataset.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def recalculate_box_and_verify_if_valid(x, y, w, h, image_size, original_image_size, min_box_size):
|
| 10 |
+
scale = image_size / min(original_image_size)
|
| 11 |
+
crop_y = (original_image_size[1] * scale - image_size) // 2
|
| 12 |
+
crop_x = (original_image_size[0] * scale - image_size) // 2
|
| 13 |
+
x0 = max(x * scale - crop_x, 0)
|
| 14 |
+
y0 = max(y * scale - crop_y, 0)
|
| 15 |
+
x1 = min((x + w) * scale - crop_x, image_size)
|
| 16 |
+
y1 = min((y + h) * scale - crop_y, image_size)
|
| 17 |
+
if (x1 - x0) * (y1 - y0) / (image_size * image_size) < min_box_size:
|
| 18 |
+
return False, (None, None, None, None)
|
| 19 |
+
return True, (x0, y0, x1, y1)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class COCODataset(torch.utils.data.Dataset):
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
data_path,
|
| 26 |
+
image_path,
|
| 27 |
+
image_size=512,
|
| 28 |
+
min_box_size=0.01,
|
| 29 |
+
max_boxes_per_data=8,
|
| 30 |
+
tokenizer=None,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.min_box_size = min_box_size
|
| 34 |
+
self.max_boxes_per_data = max_boxes_per_data
|
| 35 |
+
self.image_size = image_size
|
| 36 |
+
self.image_path = image_path
|
| 37 |
+
self.tokenizer = tokenizer
|
| 38 |
+
self.transforms = transforms.Compose(
|
| 39 |
+
[
|
| 40 |
+
transforms.Resize(image_size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 41 |
+
transforms.CenterCrop(image_size),
|
| 42 |
+
transforms.ToTensor(),
|
| 43 |
+
transforms.Normalize([0.5], [0.5]),
|
| 44 |
+
]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.data_list = torch.load(data_path, map_location="cpu")
|
| 48 |
+
|
| 49 |
+
def __getitem__(self, index):
|
| 50 |
+
if self.max_boxes_per_data > 99:
|
| 51 |
+
assert False, "Are you sure setting such large number of boxes per image?"
|
| 52 |
+
|
| 53 |
+
out = {}
|
| 54 |
+
|
| 55 |
+
data = self.data_list[index]
|
| 56 |
+
image = Image.open(os.path.join(self.image_path, data["file_path"])).convert("RGB")
|
| 57 |
+
original_image_size = image.size
|
| 58 |
+
out["pixel_values"] = self.transforms(image)
|
| 59 |
+
|
| 60 |
+
annos = data["annos"]
|
| 61 |
+
|
| 62 |
+
areas, valid_annos = [], []
|
| 63 |
+
for anno in annos:
|
| 64 |
+
# x, y, w, h = anno['bbox']
|
| 65 |
+
x0, y0, x1, y1 = anno["bbox"]
|
| 66 |
+
x, y, w, h = x0, y0, x1 - x0, y1 - y0
|
| 67 |
+
valid, (x0, y0, x1, y1) = recalculate_box_and_verify_if_valid(
|
| 68 |
+
x, y, w, h, self.image_size, original_image_size, self.min_box_size
|
| 69 |
+
)
|
| 70 |
+
if valid:
|
| 71 |
+
anno["bbox"] = [x0, y0, x1, y1]
|
| 72 |
+
areas.append((x1 - x0) * (y1 - y0))
|
| 73 |
+
valid_annos.append(anno)
|
| 74 |
+
|
| 75 |
+
# Sort according to area and choose the largest N objects
|
| 76 |
+
wanted_idxs = torch.tensor(areas).sort(descending=True)[1]
|
| 77 |
+
wanted_idxs = wanted_idxs[: self.max_boxes_per_data]
|
| 78 |
+
valid_annos = [valid_annos[i] for i in wanted_idxs]
|
| 79 |
+
|
| 80 |
+
out["boxes"] = torch.zeros(self.max_boxes_per_data, 4)
|
| 81 |
+
out["masks"] = torch.zeros(self.max_boxes_per_data)
|
| 82 |
+
out["text_embeddings_before_projection"] = torch.zeros(self.max_boxes_per_data, 768)
|
| 83 |
+
|
| 84 |
+
for i, anno in enumerate(valid_annos):
|
| 85 |
+
out["boxes"][i] = torch.tensor(anno["bbox"]) / self.image_size
|
| 86 |
+
out["masks"][i] = 1
|
| 87 |
+
out["text_embeddings_before_projection"][i] = anno["text_embeddings_before_projection"]
|
| 88 |
+
|
| 89 |
+
prob_drop_boxes = 0.1
|
| 90 |
+
if random.random() < prob_drop_boxes:
|
| 91 |
+
out["masks"][:] = 0
|
| 92 |
+
|
| 93 |
+
caption = random.choice(data["captions"])
|
| 94 |
+
|
| 95 |
+
prob_drop_captions = 0.5
|
| 96 |
+
if random.random() < prob_drop_captions:
|
| 97 |
+
caption = ""
|
| 98 |
+
caption = self.tokenizer(
|
| 99 |
+
caption,
|
| 100 |
+
max_length=self.tokenizer.model_max_length,
|
| 101 |
+
padding="max_length",
|
| 102 |
+
truncation=True,
|
| 103 |
+
return_tensors="pt",
|
| 104 |
+
)
|
| 105 |
+
out["caption"] = caption
|
| 106 |
+
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
def __len__(self):
|
| 110 |
+
return len(self.data_list)
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/demo.ipynb
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 2,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [
|
| 8 |
+
{
|
| 9 |
+
"name": "stdout",
|
| 10 |
+
"output_type": "stream",
|
| 11 |
+
"text": [
|
| 12 |
+
"The autoreload extension is already loaded. To reload it, use:\n",
|
| 13 |
+
" %reload_ext autoreload\n"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"name": "stderr",
|
| 18 |
+
"output_type": "stream",
|
| 19 |
+
"text": [
|
| 20 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
| 21 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
| 22 |
+
]
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"source": [
|
| 26 |
+
"%load_ext autoreload\n",
|
| 27 |
+
"%autoreload 2\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"from diffusers import StableDiffusionGLIGENPipeline"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"execution_count": 7,
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"outputs": [],
|
| 37 |
+
"source": [
|
| 38 |
+
"from transformers import CLIPTextModel, CLIPTokenizer\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"import diffusers\n",
|
| 41 |
+
"from diffusers import (\n",
|
| 42 |
+
" AutoencoderKL,\n",
|
| 43 |
+
" DDPMScheduler,\n",
|
| 44 |
+
" EulerDiscreteScheduler,\n",
|
| 45 |
+
" UNet2DConditionModel,\n",
|
| 46 |
+
")\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"# pretrained_model_name_or_path = 'masterful/gligen-1-4-generation-text-box'\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"pretrained_model_name_or_path = \"/root/data/zhizhonghuang/checkpoints/models--masterful--gligen-1-4-generation-text-box/snapshots/d2820dc1e9ba6ca082051ce79cfd3eb468ae2c83\"\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder=\"tokenizer\")\n",
|
| 54 |
+
"noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder=\"scheduler\")\n",
|
| 55 |
+
"text_encoder = CLIPTextModel.from_pretrained(pretrained_model_name_or_path, subfolder=\"text_encoder\")\n",
|
| 56 |
+
"vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder=\"vae\")\n",
|
| 57 |
+
"# unet = UNet2DConditionModel.from_pretrained(\n",
|
| 58 |
+
"# pretrained_model_name_or_path, subfolder=\"unet\"\n",
|
| 59 |
+
"# )\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"noise_scheduler = EulerDiscreteScheduler.from_config(noise_scheduler.config)"
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"execution_count": 8,
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"outputs": [],
|
| 69 |
+
"source": [
|
| 70 |
+
"unet = UNet2DConditionModel.from_pretrained(\"/root/data/zhizhonghuang/ckpt/GLIGEN_Text_Retrain_COCO\")"
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"execution_count": 9,
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"outputs": [
|
| 78 |
+
{
|
| 79 |
+
"name": "stderr",
|
| 80 |
+
"output_type": "stream",
|
| 81 |
+
"text": [
|
| 82 |
+
"You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion_gligen.pipeline_stable_diffusion_gligen.StableDiffusionGLIGENPipeline'> by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\n"
|
| 83 |
+
]
|
| 84 |
+
}
|
| 85 |
+
],
|
| 86 |
+
"source": [
|
| 87 |
+
"pipe = StableDiffusionGLIGENPipeline(\n",
|
| 88 |
+
" vae,\n",
|
| 89 |
+
" text_encoder,\n",
|
| 90 |
+
" tokenizer,\n",
|
| 91 |
+
" unet,\n",
|
| 92 |
+
" noise_scheduler,\n",
|
| 93 |
+
" safety_checker=None,\n",
|
| 94 |
+
" feature_extractor=None,\n",
|
| 95 |
+
")\n",
|
| 96 |
+
"pipe = pipe.to(\"cuda\")"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"execution_count": 10,
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"outputs": [],
|
| 104 |
+
"source": [
|
| 105 |
+
"import numpy as np\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# 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'\n",
|
| 109 |
+
"# gen_boxes = [('a green car', [21, 281, 211, 159]), ('a blue truck', [269, 283, 209, 160]), ('a red air balloon', [66, 8, 145, 135]), ('a bird', [296, 42, 143, 100])]\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"# prompt = 'A realistic top-down view of a wooden table with two apples on it'\n",
|
| 112 |
+
"# gen_boxes = [('a wooden table', [20, 148, 472, 216]), ('an apple', [150, 226, 100, 100]), ('an apple', [280, 226, 100, 100])]\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# prompt = 'A realistic scene of three skiers standing in a line on the snow near a palm tree'\n",
|
| 115 |
+
"# gen_boxes = [('a skier', [5, 152, 139, 168]), ('a skier', [278, 192, 121, 158]), ('a skier', [148, 173, 124, 155]), ('a palm tree', [404, 105, 103, 251])]\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"prompt = \"An oil painting of a pink dolphin jumping on the left of a steam boat on the sea\"\n",
|
| 118 |
+
"gen_boxes = [(\"a steam boat\", [232, 225, 257, 149]), (\"a jumping pink dolphin\", [21, 249, 189, 123])]\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"boxes = np.array([x[1] for x in gen_boxes])\n",
|
| 121 |
+
"boxes = boxes / 512\n",
|
| 122 |
+
"boxes[:, 2] = boxes[:, 0] + boxes[:, 2]\n",
|
| 123 |
+
"boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n",
|
| 124 |
+
"boxes = boxes.tolist()\n",
|
| 125 |
+
"gligen_phrases = [x[0] for x in gen_boxes]"
|
| 126 |
+
]
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"execution_count": 11,
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"outputs": [
|
| 133 |
+
{
|
| 134 |
+
"name": "stderr",
|
| 135 |
+
"output_type": "stream",
|
| 136 |
+
"text": [
|
| 137 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py:683: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.\n",
|
| 138 |
+
" num_channels_latents = self.unet.in_channels\n",
|
| 139 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py:716: FutureWarning: Accessing config attribute `cross_attention_dim` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'cross_attention_dim' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.cross_attention_dim'.\n",
|
| 140 |
+
" max_objs, self.unet.cross_attention_dim, device=device, dtype=self.text_encoder.dtype\n",
|
| 141 |
+
"100%|██████████| 50/50 [01:21<00:00, 1.64s/it]\n"
|
| 142 |
+
]
|
| 143 |
+
}
|
| 144 |
+
],
|
| 145 |
+
"source": [
|
| 146 |
+
"images = pipe(\n",
|
| 147 |
+
" prompt=prompt,\n",
|
| 148 |
+
" gligen_phrases=gligen_phrases,\n",
|
| 149 |
+
" gligen_boxes=boxes,\n",
|
| 150 |
+
" gligen_scheduled_sampling_beta=1.0,\n",
|
| 151 |
+
" output_type=\"pil\",\n",
|
| 152 |
+
" num_inference_steps=50,\n",
|
| 153 |
+
" negative_prompt=\"artifacts, blurry, smooth texture, bad quality, distortions, unrealistic, distorted image, bad proportions, duplicate\",\n",
|
| 154 |
+
" num_images_per_prompt=16,\n",
|
| 155 |
+
").images"
|
| 156 |
+
]
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"execution_count": 12,
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"outputs": [],
|
| 163 |
+
"source": [
|
| 164 |
+
"diffusers.utils.make_image_grid(images, 4, len(images) // 4)"
|
| 165 |
+
]
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"outputs": [],
|
| 172 |
+
"source": []
|
| 173 |
+
}
|
| 174 |
+
],
|
| 175 |
+
"metadata": {
|
| 176 |
+
"kernelspec": {
|
| 177 |
+
"display_name": "Python 3 (ipykernel)",
|
| 178 |
+
"language": "python",
|
| 179 |
+
"name": "python3"
|
| 180 |
+
},
|
| 181 |
+
"language_info": {
|
| 182 |
+
"codemirror_mode": {
|
| 183 |
+
"name": "ipython",
|
| 184 |
+
"version": 3
|
| 185 |
+
},
|
| 186 |
+
"file_extension": ".py",
|
| 187 |
+
"mimetype": "text/x-python",
|
| 188 |
+
"name": "python",
|
| 189 |
+
"nbconvert_exporter": "python",
|
| 190 |
+
"pygments_lexer": "ipython3",
|
| 191 |
+
"version": "3.11.9"
|
| 192 |
+
}
|
| 193 |
+
},
|
| 194 |
+
"nbformat": 4,
|
| 195 |
+
"nbformat_minor": 4
|
| 196 |
+
}
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/generated-images-100000-00.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/make_datasets.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torchvision
|
| 7 |
+
import torchvision.transforms as TS
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from ram import inference_ram
|
| 10 |
+
from ram.models import ram
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import (
|
| 13 |
+
AutoModelForZeroShotObjectDetection,
|
| 14 |
+
AutoProcessor,
|
| 15 |
+
Blip2ForConditionalGeneration,
|
| 16 |
+
Blip2Processor,
|
| 17 |
+
CLIPTextModel,
|
| 18 |
+
CLIPTokenizer,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
torch.autograd.set_grad_enabled(False)
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
parser = argparse.ArgumentParser("Caption Generation script", add_help=False)
|
| 26 |
+
parser.add_argument("--data_root", type=str, required=True, help="path to COCO")
|
| 27 |
+
parser.add_argument("--save_root", type=str, required=True, help="path to save")
|
| 28 |
+
parser.add_argument("--ram_checkpoint", type=str, required=True, help="path to save")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
|
| 31 |
+
# ram_checkpoint = '/root/.cache/huggingface/hub/models--xinyu1205--recognize_anything_model/snapshots/ebc52dc741e86466202a5ab8ab22eae6e7d48bf1/ram_swin_large_14m.pth'
|
| 32 |
+
# data_root = '/mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017'
|
| 33 |
+
# save_root = '/root/gligen_data'
|
| 34 |
+
box_threshold = 0.25
|
| 35 |
+
text_threshold = 0.2
|
| 36 |
+
|
| 37 |
+
import torch.distributed as dist
|
| 38 |
+
|
| 39 |
+
dist.init_process_group(backend="nccl", init_method="env://")
|
| 40 |
+
local_rank = torch.distributed.get_rank() % torch.cuda.device_count()
|
| 41 |
+
device = f"cuda:{local_rank}"
|
| 42 |
+
torch.cuda.set_device(local_rank)
|
| 43 |
+
|
| 44 |
+
ram_model = ram(pretrained=args.ram_checkpoint, image_size=384, vit="swin_l").cuda().eval()
|
| 45 |
+
ram_processor = TS.Compose(
|
| 46 |
+
[TS.Resize((384, 384)), TS.ToTensor(), TS.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
grounding_dino_processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-base")
|
| 50 |
+
grounding_dino_model = AutoModelForZeroShotObjectDetection.from_pretrained(
|
| 51 |
+
"IDEA-Research/grounding-dino-base"
|
| 52 |
+
).cuda()
|
| 53 |
+
|
| 54 |
+
blip2_processor = Blip2Processor.from_pretrained("Salesforce/blip2-flan-t5-xxl")
|
| 55 |
+
blip2_model = Blip2ForConditionalGeneration.from_pretrained(
|
| 56 |
+
"Salesforce/blip2-flan-t5-xxl", torch_dtype=torch.float16
|
| 57 |
+
).cuda()
|
| 58 |
+
|
| 59 |
+
clip_text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").cuda()
|
| 60 |
+
clip_tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
| 61 |
+
|
| 62 |
+
image_paths = [os.path.join(args.data_root, x) for x in os.listdir(args.data_root)]
|
| 63 |
+
random.shuffle(image_paths)
|
| 64 |
+
|
| 65 |
+
for image_path in tqdm.tqdm(image_paths):
|
| 66 |
+
pth_path = os.path.join(args.save_root, os.path.basename(image_path))
|
| 67 |
+
if os.path.exists(pth_path):
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
sample = {"file_path": os.path.basename(image_path), "annos": []}
|
| 71 |
+
|
| 72 |
+
raw_image = Image.open(image_path).convert("RGB")
|
| 73 |
+
|
| 74 |
+
res = inference_ram(ram_processor(raw_image).unsqueeze(0).cuda(), ram_model)
|
| 75 |
+
|
| 76 |
+
text = res[0].replace(" |", ".")
|
| 77 |
+
|
| 78 |
+
inputs = grounding_dino_processor(images=raw_image, text=text, return_tensors="pt")
|
| 79 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
| 80 |
+
outputs = grounding_dino_model(**inputs)
|
| 81 |
+
|
| 82 |
+
results = grounding_dino_processor.post_process_grounded_object_detection(
|
| 83 |
+
outputs,
|
| 84 |
+
inputs["input_ids"],
|
| 85 |
+
box_threshold=box_threshold,
|
| 86 |
+
text_threshold=text_threshold,
|
| 87 |
+
target_sizes=[raw_image.size[::-1]],
|
| 88 |
+
)
|
| 89 |
+
boxes = results[0]["boxes"]
|
| 90 |
+
labels = results[0]["labels"]
|
| 91 |
+
scores = results[0]["scores"]
|
| 92 |
+
indices = torchvision.ops.nms(boxes, scores, 0.5)
|
| 93 |
+
boxes = boxes[indices]
|
| 94 |
+
category_names = [labels[i] for i in indices]
|
| 95 |
+
|
| 96 |
+
for i, bbox in enumerate(boxes):
|
| 97 |
+
bbox = bbox.tolist()
|
| 98 |
+
inputs = blip2_processor(images=raw_image.crop(bbox), return_tensors="pt")
|
| 99 |
+
inputs = {k: v.cuda().to(torch.float16) for k, v in inputs.items()}
|
| 100 |
+
outputs = blip2_model.generate(**inputs)
|
| 101 |
+
caption = blip2_processor.decode(outputs[0], skip_special_tokens=True)
|
| 102 |
+
inputs = clip_tokenizer(
|
| 103 |
+
caption,
|
| 104 |
+
padding="max_length",
|
| 105 |
+
max_length=clip_tokenizer.model_max_length,
|
| 106 |
+
truncation=True,
|
| 107 |
+
return_tensors="pt",
|
| 108 |
+
)
|
| 109 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
| 110 |
+
text_embeddings_before_projection = clip_text_encoder(**inputs).pooler_output.squeeze(0)
|
| 111 |
+
|
| 112 |
+
sample["annos"].append(
|
| 113 |
+
{
|
| 114 |
+
"caption": caption,
|
| 115 |
+
"bbox": bbox,
|
| 116 |
+
"text_embeddings_before_projection": text_embeddings_before_projection,
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
torch.save(sample, pth_path)
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.16.0
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.25.1
|
| 4 |
+
ftfy
|
| 5 |
+
tensorboard
|
| 6 |
+
Jinja2
|
| 7 |
+
diffusers
|
| 8 |
+
scipy
|
| 9 |
+
timm
|
| 10 |
+
fairscale
|
| 11 |
+
wandb
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/gligen/train_gligen_text.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
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-9ca70b8463d4/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/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right 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"\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 `huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py
ADDED
|
@@ -0,0 +1,646 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 `huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py
ADDED
|
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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="runwayml/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="runwayml/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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-9ca70b8463d4/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-9ca70b8463d4/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 |
+
huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/lora/train_text_to_image_lora.py
ADDED
|
@@ -0,0 +1,1026 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"\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 `huggingface-cli 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-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth/README.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth/train_multi_subject_dreambooth.py
ADDED
|
@@ -0,0 +1,1195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 `huggingface-cli 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-9ca70b8463d4/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 requieres 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: [](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 |
+

|
| 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="runwayml/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 [](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 |
+

|
tasks/tasksmith-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/multi_subject_dreambooth_inpainting/train_multi_subject_dreambooth_inpainting.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-9ca70b8463d4/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 |
+
[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb)
|
| 24 |
+
|
| 25 |
+
Colab for inference
|
| 26 |
+
[](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 |
+
huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/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-9ca70b8463d4/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 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import logging
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import PIL
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
import torch.utils.checkpoint
|
| 28 |
+
import transformers
|
| 29 |
+
from accelerate import Accelerator
|
| 30 |
+
from accelerate.logging import get_logger
|
| 31 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 32 |
+
from huggingface_hub import create_repo, upload_folder
|
| 33 |
+
from multi_token_clip import MultiTokenCLIPTokenizer
|
| 34 |
+
|
| 35 |
+
# TODO: remove and import from diffusers.utils when the new version of diffusers is released
|
| 36 |
+
from packaging import version
|
| 37 |
+
from PIL import Image
|
| 38 |
+
from torch.utils.data import Dataset
|
| 39 |
+
from torchvision import transforms
|
| 40 |
+
from tqdm.auto import tqdm
|
| 41 |
+
from transformers import CLIPTextModel
|
| 42 |
+
|
| 43 |
+
import diffusers
|
| 44 |
+
from diffusers import (
|
| 45 |
+
AutoencoderKL,
|
| 46 |
+
DDPMScheduler,
|
| 47 |
+
DiffusionPipeline,
|
| 48 |
+
DPMSolverMultistepScheduler,
|
| 49 |
+
StableDiffusionPipeline,
|
| 50 |
+
UNet2DConditionModel,
|
| 51 |
+
)
|
| 52 |
+
from diffusers.optimization import get_scheduler
|
| 53 |
+
from diffusers.utils import check_min_version, is_wandb_available
|
| 54 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
|
| 58 |
+
PIL_INTERPOLATION = {
|
| 59 |
+
"linear": PIL.Image.Resampling.BILINEAR,
|
| 60 |
+
"bilinear": PIL.Image.Resampling.BILINEAR,
|
| 61 |
+
"bicubic": PIL.Image.Resampling.BICUBIC,
|
| 62 |
+
"lanczos": PIL.Image.Resampling.LANCZOS,
|
| 63 |
+
"nearest": PIL.Image.Resampling.NEAREST,
|
| 64 |
+
}
|
| 65 |
+
else:
|
| 66 |
+
PIL_INTERPOLATION = {
|
| 67 |
+
"linear": PIL.Image.LINEAR,
|
| 68 |
+
"bilinear": PIL.Image.BILINEAR,
|
| 69 |
+
"bicubic": PIL.Image.BICUBIC,
|
| 70 |
+
"lanczos": PIL.Image.LANCZOS,
|
| 71 |
+
"nearest": PIL.Image.NEAREST,
|
| 72 |
+
}
|
| 73 |
+
# ------------------------------------------------------------------------------
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 77 |
+
check_min_version("0.14.0.dev0")
|
| 78 |
+
|
| 79 |
+
logger = get_logger(__name__)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def add_tokens(tokenizer, text_encoder, placeholder_token, num_vec_per_token=1, initializer_token=None):
|
| 83 |
+
"""
|
| 84 |
+
Add tokens to the tokenizer and set the initial value of token embeddings
|
| 85 |
+
"""
|
| 86 |
+
tokenizer.add_placeholder_tokens(placeholder_token, num_vec_per_token=num_vec_per_token)
|
| 87 |
+
text_encoder.resize_token_embeddings(len(tokenizer))
|
| 88 |
+
token_embeds = text_encoder.get_input_embeddings().weight.data
|
| 89 |
+
placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
|
| 90 |
+
if initializer_token:
|
| 91 |
+
token_ids = tokenizer.encode(initializer_token, add_special_tokens=False)
|
| 92 |
+
for i, placeholder_token_id in enumerate(placeholder_token_ids):
|
| 93 |
+
token_embeds[placeholder_token_id] = token_embeds[token_ids[i * len(token_ids) // num_vec_per_token]]
|
| 94 |
+
else:
|
| 95 |
+
for i, placeholder_token_id in enumerate(placeholder_token_ids):
|
| 96 |
+
token_embeds[placeholder_token_id] = torch.randn_like(token_embeds[placeholder_token_id])
|
| 97 |
+
return placeholder_token
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def save_progress(tokenizer, text_encoder, accelerator, save_path):
|
| 101 |
+
for placeholder_token in tokenizer.token_map:
|
| 102 |
+
placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
|
| 103 |
+
learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_ids]
|
| 104 |
+
if len(placeholder_token_ids) == 1:
|
| 105 |
+
learned_embeds = learned_embeds[None]
|
| 106 |
+
learned_embeds_dict = {placeholder_token: learned_embeds.detach().cpu()}
|
| 107 |
+
torch.save(learned_embeds_dict, save_path)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def load_multitoken_tokenizer(tokenizer, text_encoder, learned_embeds_dict):
|
| 111 |
+
for placeholder_token in learned_embeds_dict:
|
| 112 |
+
placeholder_embeds = learned_embeds_dict[placeholder_token]
|
| 113 |
+
num_vec_per_token = placeholder_embeds.shape[0]
|
| 114 |
+
placeholder_embeds = placeholder_embeds.to(dtype=text_encoder.dtype)
|
| 115 |
+
add_tokens(tokenizer, text_encoder, placeholder_token, num_vec_per_token=num_vec_per_token)
|
| 116 |
+
placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
|
| 117 |
+
token_embeds = text_encoder.get_input_embeddings().weight.data
|
| 118 |
+
for i, placeholder_token_id in enumerate(placeholder_token_ids):
|
| 119 |
+
token_embeds[placeholder_token_id] = placeholder_embeds[i]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def load_multitoken_tokenizer_from_automatic(tokenizer, text_encoder, automatic_dict, placeholder_token):
|
| 123 |
+
"""
|
| 124 |
+
Automatic1111's tokens have format
|
| 125 |
+
{'string_to_token': {'*': 265}, 'string_to_param': {'*': tensor([[ 0.0833, 0.0030, 0.0057, ..., -0.0264, -0.0616, -0.0529],
|
| 126 |
+
[ 0.0058, -0.0190, -0.0584, ..., -0.0025, -0.0945, -0.0490],
|
| 127 |
+
[ 0.0916, 0.0025, 0.0365, ..., -0.0685, -0.0124, 0.0728],
|
| 128 |
+
[ 0.0812, -0.0199, -0.0100, ..., -0.0581, -0.0780, 0.0254]],
|
| 129 |
+
requires_grad=True)}, 'name': 'FloralMarble-400', 'step': 399, 'sd_checkpoint': '4bdfc29c', 'sd_checkpoint_name': 'SD2.1-768'}
|
| 130 |
+
"""
|
| 131 |
+
learned_embeds_dict = {}
|
| 132 |
+
learned_embeds_dict[placeholder_token] = automatic_dict["string_to_param"]["*"]
|
| 133 |
+
load_multitoken_tokenizer(tokenizer, text_encoder, learned_embeds_dict)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def get_mask(tokenizer, accelerator):
|
| 137 |
+
# Get the mask of the weights that won't change
|
| 138 |
+
mask = torch.ones(len(tokenizer)).to(accelerator.device, dtype=torch.bool)
|
| 139 |
+
for placeholder_token in tokenizer.token_map:
|
| 140 |
+
placeholder_token_ids = tokenizer.encode(placeholder_token, add_special_tokens=False)
|
| 141 |
+
for i in range(len(placeholder_token_ids)):
|
| 142 |
+
mask = mask & (torch.arange(len(tokenizer)) != placeholder_token_ids[i]).to(accelerator.device)
|
| 143 |
+
return mask
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def parse_args():
|
| 147 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--progressive_tokens_max_steps",
|
| 150 |
+
type=int,
|
| 151 |
+
default=2000,
|
| 152 |
+
help="The number of steps until all tokens will be used.",
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument(
|
| 155 |
+
"--progressive_tokens",
|
| 156 |
+
action="store_true",
|
| 157 |
+
help="Progressively train the tokens. For example, first train for 1 token, then 2 tokens and so on.",
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument("--vector_shuffle", action="store_true", help="Shuffling tokens durint training")
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--num_vec_per_token",
|
| 162 |
+
type=int,
|
| 163 |
+
default=1,
|
| 164 |
+
help=(
|
| 165 |
+
"The number of vectors used to represent the placeholder token. The higher the number, the better the"
|
| 166 |
+
" result at the cost of editability. This can be fixed by prompt editing."
|
| 167 |
+
),
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--save_steps",
|
| 171 |
+
type=int,
|
| 172 |
+
default=500,
|
| 173 |
+
help="Save learned_embeds.bin every X updates steps.",
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--only_save_embeds",
|
| 177 |
+
action="store_true",
|
| 178 |
+
default=False,
|
| 179 |
+
help="Save only the embeddings for the new concept.",
|
| 180 |
+
)
|
| 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 |
+
"--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
|
| 203 |
+
)
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--placeholder_token",
|
| 206 |
+
type=str,
|
| 207 |
+
default=None,
|
| 208 |
+
required=True,
|
| 209 |
+
help="A token to use as a placeholder for the concept.",
|
| 210 |
+
)
|
| 211 |
+
parser.add_argument(
|
| 212 |
+
"--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
|
| 213 |
+
)
|
| 214 |
+
parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
|
| 215 |
+
parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
|
| 216 |
+
parser.add_argument(
|
| 217 |
+
"--output_dir",
|
| 218 |
+
type=str,
|
| 219 |
+
default="text-inversion-model",
|
| 220 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--resolution",
|
| 225 |
+
type=int,
|
| 226 |
+
default=512,
|
| 227 |
+
help=(
|
| 228 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 229 |
+
" resolution"
|
| 230 |
+
),
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 237 |
+
)
|
| 238 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--max_train_steps",
|
| 241 |
+
type=int,
|
| 242 |
+
default=5000,
|
| 243 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 244 |
+
)
|
| 245 |
+
parser.add_argument(
|
| 246 |
+
"--gradient_accumulation_steps",
|
| 247 |
+
type=int,
|
| 248 |
+
default=1,
|
| 249 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 250 |
+
)
|
| 251 |
+
parser.add_argument(
|
| 252 |
+
"--gradient_checkpointing",
|
| 253 |
+
action="store_true",
|
| 254 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"--learning_rate",
|
| 258 |
+
type=float,
|
| 259 |
+
default=1e-4,
|
| 260 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 261 |
+
)
|
| 262 |
+
parser.add_argument(
|
| 263 |
+
"--scale_lr",
|
| 264 |
+
action="store_true",
|
| 265 |
+
default=False,
|
| 266 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 267 |
+
)
|
| 268 |
+
parser.add_argument(
|
| 269 |
+
"--lr_scheduler",
|
| 270 |
+
type=str,
|
| 271 |
+
default="constant",
|
| 272 |
+
help=(
|
| 273 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 274 |
+
' "constant", "constant_with_warmup"]'
|
| 275 |
+
),
|
| 276 |
+
)
|
| 277 |
+
parser.add_argument(
|
| 278 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--dataloader_num_workers",
|
| 282 |
+
type=int,
|
| 283 |
+
default=0,
|
| 284 |
+
help=(
|
| 285 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 286 |
+
),
|
| 287 |
+
)
|
| 288 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 289 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 290 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 291 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 292 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 293 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--hub_model_id",
|
| 296 |
+
type=str,
|
| 297 |
+
default=None,
|
| 298 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 299 |
+
)
|
| 300 |
+
parser.add_argument(
|
| 301 |
+
"--logging_dir",
|
| 302 |
+
type=str,
|
| 303 |
+
default="logs",
|
| 304 |
+
help=(
|
| 305 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 306 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 307 |
+
),
|
| 308 |
+
)
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"--mixed_precision",
|
| 311 |
+
type=str,
|
| 312 |
+
default="no",
|
| 313 |
+
choices=["no", "fp16", "bf16"],
|
| 314 |
+
help=(
|
| 315 |
+
"Whether to use mixed precision. Choose"
|
| 316 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 317 |
+
"and an Nvidia Ampere GPU."
|
| 318 |
+
),
|
| 319 |
+
)
|
| 320 |
+
parser.add_argument(
|
| 321 |
+
"--allow_tf32",
|
| 322 |
+
action="store_true",
|
| 323 |
+
help=(
|
| 324 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 325 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 326 |
+
),
|
| 327 |
+
)
|
| 328 |
+
parser.add_argument(
|
| 329 |
+
"--report_to",
|
| 330 |
+
type=str,
|
| 331 |
+
default="tensorboard",
|
| 332 |
+
help=(
|
| 333 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 334 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 335 |
+
),
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--validation_prompt",
|
| 339 |
+
type=str,
|
| 340 |
+
default=None,
|
| 341 |
+
help="A prompt that is used during validation to verify that the model is learning.",
|
| 342 |
+
)
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--num_validation_images",
|
| 345 |
+
type=int,
|
| 346 |
+
default=4,
|
| 347 |
+
help="Number of images that should be generated during validation with `validation_prompt`.",
|
| 348 |
+
)
|
| 349 |
+
parser.add_argument(
|
| 350 |
+
"--validation_epochs",
|
| 351 |
+
type=int,
|
| 352 |
+
default=50,
|
| 353 |
+
help=(
|
| 354 |
+
"Run validation every X epochs. Validation consists of running the prompt"
|
| 355 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`"
|
| 356 |
+
" and logging the images."
|
| 357 |
+
),
|
| 358 |
+
)
|
| 359 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 360 |
+
parser.add_argument(
|
| 361 |
+
"--checkpointing_steps",
|
| 362 |
+
type=int,
|
| 363 |
+
default=500,
|
| 364 |
+
help=(
|
| 365 |
+
"Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
|
| 366 |
+
" training using `--resume_from_checkpoint`."
|
| 367 |
+
),
|
| 368 |
+
)
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--checkpoints_total_limit",
|
| 371 |
+
type=int,
|
| 372 |
+
default=None,
|
| 373 |
+
help=(
|
| 374 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 375 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 376 |
+
" for more docs"
|
| 377 |
+
),
|
| 378 |
+
)
|
| 379 |
+
parser.add_argument(
|
| 380 |
+
"--resume_from_checkpoint",
|
| 381 |
+
type=str,
|
| 382 |
+
default=None,
|
| 383 |
+
help=(
|
| 384 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 385 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 386 |
+
),
|
| 387 |
+
)
|
| 388 |
+
parser.add_argument(
|
| 389 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
args = parser.parse_args()
|
| 393 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 394 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 395 |
+
args.local_rank = env_local_rank
|
| 396 |
+
|
| 397 |
+
if args.train_data_dir is None:
|
| 398 |
+
raise ValueError("You must specify a train data directory.")
|
| 399 |
+
|
| 400 |
+
return args
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
imagenet_templates_small = [
|
| 404 |
+
"a photo of a {}",
|
| 405 |
+
"a rendering of a {}",
|
| 406 |
+
"a cropped photo of the {}",
|
| 407 |
+
"the photo of a {}",
|
| 408 |
+
"a photo of a clean {}",
|
| 409 |
+
"a photo of a dirty {}",
|
| 410 |
+
"a dark photo of the {}",
|
| 411 |
+
"a photo of my {}",
|
| 412 |
+
"a photo of the cool {}",
|
| 413 |
+
"a close-up photo of a {}",
|
| 414 |
+
"a bright photo of the {}",
|
| 415 |
+
"a cropped photo of a {}",
|
| 416 |
+
"a photo of the {}",
|
| 417 |
+
"a good photo of the {}",
|
| 418 |
+
"a photo of one {}",
|
| 419 |
+
"a close-up photo of the {}",
|
| 420 |
+
"a rendition of the {}",
|
| 421 |
+
"a photo of the clean {}",
|
| 422 |
+
"a rendition of a {}",
|
| 423 |
+
"a photo of a nice {}",
|
| 424 |
+
"a good photo of a {}",
|
| 425 |
+
"a photo of the nice {}",
|
| 426 |
+
"a photo of the small {}",
|
| 427 |
+
"a photo of the weird {}",
|
| 428 |
+
"a photo of the large {}",
|
| 429 |
+
"a photo of a cool {}",
|
| 430 |
+
"a photo of a small {}",
|
| 431 |
+
]
|
| 432 |
+
|
| 433 |
+
imagenet_style_templates_small = [
|
| 434 |
+
"a painting in the style of {}",
|
| 435 |
+
"a rendering in the style of {}",
|
| 436 |
+
"a cropped painting in the style of {}",
|
| 437 |
+
"the painting in the style of {}",
|
| 438 |
+
"a clean painting in the style of {}",
|
| 439 |
+
"a dirty painting in the style of {}",
|
| 440 |
+
"a dark painting in the style of {}",
|
| 441 |
+
"a picture in the style of {}",
|
| 442 |
+
"a cool painting in the style of {}",
|
| 443 |
+
"a close-up painting in the style of {}",
|
| 444 |
+
"a bright painting in the style of {}",
|
| 445 |
+
"a cropped painting in the style of {}",
|
| 446 |
+
"a good painting in the style of {}",
|
| 447 |
+
"a close-up painting in the style of {}",
|
| 448 |
+
"a rendition in the style of {}",
|
| 449 |
+
"a nice painting in the style of {}",
|
| 450 |
+
"a small painting in the style of {}",
|
| 451 |
+
"a weird painting in the style of {}",
|
| 452 |
+
"a large painting in the style of {}",
|
| 453 |
+
]
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class TextualInversionDataset(Dataset):
|
| 457 |
+
def __init__(
|
| 458 |
+
self,
|
| 459 |
+
data_root,
|
| 460 |
+
tokenizer,
|
| 461 |
+
learnable_property="object", # [object, style]
|
| 462 |
+
size=512,
|
| 463 |
+
repeats=100,
|
| 464 |
+
interpolation="bicubic",
|
| 465 |
+
flip_p=0.5,
|
| 466 |
+
set="train",
|
| 467 |
+
placeholder_token="*",
|
| 468 |
+
center_crop=False,
|
| 469 |
+
vector_shuffle=False,
|
| 470 |
+
progressive_tokens=False,
|
| 471 |
+
):
|
| 472 |
+
self.data_root = data_root
|
| 473 |
+
self.tokenizer = tokenizer
|
| 474 |
+
self.learnable_property = learnable_property
|
| 475 |
+
self.size = size
|
| 476 |
+
self.placeholder_token = placeholder_token
|
| 477 |
+
self.center_crop = center_crop
|
| 478 |
+
self.flip_p = flip_p
|
| 479 |
+
self.vector_shuffle = vector_shuffle
|
| 480 |
+
self.progressive_tokens = progressive_tokens
|
| 481 |
+
self.prop_tokens_to_load = 0
|
| 482 |
+
|
| 483 |
+
self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
|
| 484 |
+
|
| 485 |
+
self.num_images = len(self.image_paths)
|
| 486 |
+
self._length = self.num_images
|
| 487 |
+
|
| 488 |
+
if set == "train":
|
| 489 |
+
self._length = self.num_images * repeats
|
| 490 |
+
|
| 491 |
+
self.interpolation = {
|
| 492 |
+
"linear": PIL_INTERPOLATION["linear"],
|
| 493 |
+
"bilinear": PIL_INTERPOLATION["bilinear"],
|
| 494 |
+
"bicubic": PIL_INTERPOLATION["bicubic"],
|
| 495 |
+
"lanczos": PIL_INTERPOLATION["lanczos"],
|
| 496 |
+
}[interpolation]
|
| 497 |
+
|
| 498 |
+
self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
|
| 499 |
+
self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
|
| 500 |
+
|
| 501 |
+
def __len__(self):
|
| 502 |
+
return self._length
|
| 503 |
+
|
| 504 |
+
def __getitem__(self, i):
|
| 505 |
+
example = {}
|
| 506 |
+
image = Image.open(self.image_paths[i % self.num_images])
|
| 507 |
+
|
| 508 |
+
if not image.mode == "RGB":
|
| 509 |
+
image = image.convert("RGB")
|
| 510 |
+
|
| 511 |
+
placeholder_string = self.placeholder_token
|
| 512 |
+
text = random.choice(self.templates).format(placeholder_string)
|
| 513 |
+
|
| 514 |
+
example["input_ids"] = self.tokenizer.encode(
|
| 515 |
+
text,
|
| 516 |
+
padding="max_length",
|
| 517 |
+
truncation=True,
|
| 518 |
+
max_length=self.tokenizer.model_max_length,
|
| 519 |
+
return_tensors="pt",
|
| 520 |
+
vector_shuffle=self.vector_shuffle,
|
| 521 |
+
prop_tokens_to_load=self.prop_tokens_to_load if self.progressive_tokens else 1.0,
|
| 522 |
+
)[0]
|
| 523 |
+
|
| 524 |
+
# default to score-sde preprocessing
|
| 525 |
+
img = np.array(image).astype(np.uint8)
|
| 526 |
+
|
| 527 |
+
if self.center_crop:
|
| 528 |
+
crop = min(img.shape[0], img.shape[1])
|
| 529 |
+
(
|
| 530 |
+
h,
|
| 531 |
+
w,
|
| 532 |
+
) = (
|
| 533 |
+
img.shape[0],
|
| 534 |
+
img.shape[1],
|
| 535 |
+
)
|
| 536 |
+
img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
|
| 537 |
+
|
| 538 |
+
image = Image.fromarray(img)
|
| 539 |
+
image = image.resize((self.size, self.size), resample=self.interpolation)
|
| 540 |
+
|
| 541 |
+
image = self.flip_transform(image)
|
| 542 |
+
image = np.array(image).astype(np.uint8)
|
| 543 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
| 544 |
+
|
| 545 |
+
example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
|
| 546 |
+
return example
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def main():
|
| 550 |
+
args = parse_args()
|
| 551 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 552 |
+
raise ValueError(
|
| 553 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 554 |
+
" Please use `huggingface-cli login` to authenticate with the Hub."
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 558 |
+
accelerator_project_config = ProjectConfiguration(
|
| 559 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
accelerator = Accelerator(
|
| 563 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 564 |
+
mixed_precision=args.mixed_precision,
|
| 565 |
+
log_with=args.report_to,
|
| 566 |
+
project_config=accelerator_project_config,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# Disable AMP for MPS.
|
| 570 |
+
if torch.backends.mps.is_available():
|
| 571 |
+
accelerator.native_amp = False
|
| 572 |
+
|
| 573 |
+
if args.report_to == "wandb":
|
| 574 |
+
if not is_wandb_available():
|
| 575 |
+
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
|
| 576 |
+
import wandb
|
| 577 |
+
|
| 578 |
+
# Make one log on every process with the configuration for debugging.
|
| 579 |
+
logging.basicConfig(
|
| 580 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 581 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 582 |
+
level=logging.INFO,
|
| 583 |
+
)
|
| 584 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 585 |
+
if accelerator.is_local_main_process:
|
| 586 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 587 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 588 |
+
else:
|
| 589 |
+
transformers.utils.logging.set_verbosity_error()
|
| 590 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 591 |
+
|
| 592 |
+
# If passed along, set the training seed now.
|
| 593 |
+
if args.seed is not None:
|
| 594 |
+
set_seed(args.seed)
|
| 595 |
+
|
| 596 |
+
# Handle the repository creation
|
| 597 |
+
if accelerator.is_main_process:
|
| 598 |
+
if args.output_dir is not None:
|
| 599 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 600 |
+
|
| 601 |
+
if args.push_to_hub:
|
| 602 |
+
repo_id = create_repo(
|
| 603 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 604 |
+
).repo_id
|
| 605 |
+
|
| 606 |
+
# Load tokenizer
|
| 607 |
+
if args.tokenizer_name:
|
| 608 |
+
tokenizer = MultiTokenCLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 609 |
+
elif args.pretrained_model_name_or_path:
|
| 610 |
+
tokenizer = MultiTokenCLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 611 |
+
|
| 612 |
+
# Load scheduler and models
|
| 613 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 614 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 615 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 616 |
+
)
|
| 617 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
|
| 618 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 619 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 620 |
+
)
|
| 621 |
+
if is_xformers_available():
|
| 622 |
+
try:
|
| 623 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 624 |
+
except Exception as e:
|
| 625 |
+
logger.warning(
|
| 626 |
+
"Could not enable memory efficient attention. Make sure xformers is installed"
|
| 627 |
+
f" correctly and a GPU is available: {e}"
|
| 628 |
+
)
|
| 629 |
+
add_tokens(tokenizer, text_encoder, args.placeholder_token, args.num_vec_per_token, args.initializer_token)
|
| 630 |
+
|
| 631 |
+
# Freeze vae and unet
|
| 632 |
+
vae.requires_grad_(False)
|
| 633 |
+
unet.requires_grad_(False)
|
| 634 |
+
# Freeze all parameters except for the token embeddings in text encoder
|
| 635 |
+
text_encoder.text_model.encoder.requires_grad_(False)
|
| 636 |
+
text_encoder.text_model.final_layer_norm.requires_grad_(False)
|
| 637 |
+
text_encoder.text_model.embeddings.position_embedding.requires_grad_(False)
|
| 638 |
+
|
| 639 |
+
if args.gradient_checkpointing:
|
| 640 |
+
# Keep unet in train mode if we are using gradient checkpointing to save memory.
|
| 641 |
+
# The dropout cannot be != 0 so it doesn't matter if we are in eval or train mode.
|
| 642 |
+
unet.train()
|
| 643 |
+
text_encoder.gradient_checkpointing_enable()
|
| 644 |
+
unet.enable_gradient_checkpointing()
|
| 645 |
+
|
| 646 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 647 |
+
if is_xformers_available():
|
| 648 |
+
import xformers
|
| 649 |
+
|
| 650 |
+
xformers_version = version.parse(xformers.__version__)
|
| 651 |
+
if xformers_version == version.parse("0.0.16"):
|
| 652 |
+
logger.warning(
|
| 653 |
+
"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."
|
| 654 |
+
)
|
| 655 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 656 |
+
else:
|
| 657 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 658 |
+
|
| 659 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 660 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 661 |
+
if args.allow_tf32:
|
| 662 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 663 |
+
|
| 664 |
+
if args.scale_lr:
|
| 665 |
+
args.learning_rate = (
|
| 666 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
# Initialize the optimizer
|
| 670 |
+
optimizer = torch.optim.AdamW(
|
| 671 |
+
text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
|
| 672 |
+
lr=args.learning_rate,
|
| 673 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 674 |
+
weight_decay=args.adam_weight_decay,
|
| 675 |
+
eps=args.adam_epsilon,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Dataset and DataLoaders creation:
|
| 679 |
+
train_dataset = TextualInversionDataset(
|
| 680 |
+
data_root=args.train_data_dir,
|
| 681 |
+
tokenizer=tokenizer,
|
| 682 |
+
size=args.resolution,
|
| 683 |
+
placeholder_token=args.placeholder_token,
|
| 684 |
+
repeats=args.repeats,
|
| 685 |
+
learnable_property=args.learnable_property,
|
| 686 |
+
center_crop=args.center_crop,
|
| 687 |
+
set="train",
|
| 688 |
+
)
|
| 689 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 690 |
+
train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
# Scheduler and math around the number of training steps.
|
| 694 |
+
overrode_max_train_steps = False
|
| 695 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 696 |
+
if args.max_train_steps is None:
|
| 697 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 698 |
+
overrode_max_train_steps = True
|
| 699 |
+
|
| 700 |
+
lr_scheduler = get_scheduler(
|
| 701 |
+
args.lr_scheduler,
|
| 702 |
+
optimizer=optimizer,
|
| 703 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 704 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
# Prepare everything with our `accelerator`.
|
| 708 |
+
text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 709 |
+
text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
# For mixed precision training we cast the unet and vae weights to half-precision
|
| 713 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 714 |
+
weight_dtype = torch.float32
|
| 715 |
+
if accelerator.mixed_precision == "fp16":
|
| 716 |
+
weight_dtype = torch.float16
|
| 717 |
+
elif accelerator.mixed_precision == "bf16":
|
| 718 |
+
weight_dtype = torch.bfloat16
|
| 719 |
+
|
| 720 |
+
# Move vae and unet to device and cast to weight_dtype
|
| 721 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 722 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 723 |
+
|
| 724 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 725 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 726 |
+
if overrode_max_train_steps:
|
| 727 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 728 |
+
# Afterwards we recalculate our number of training epochs
|
| 729 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 730 |
+
|
| 731 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 732 |
+
# The trackers initializes automatically on the main process.
|
| 733 |
+
if accelerator.is_main_process:
|
| 734 |
+
accelerator.init_trackers("textual_inversion", config=vars(args))
|
| 735 |
+
|
| 736 |
+
# Train!
|
| 737 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 738 |
+
|
| 739 |
+
logger.info("***** Running training *****")
|
| 740 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 741 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 742 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 743 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 744 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 745 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 746 |
+
global_step = 0
|
| 747 |
+
first_epoch = 0
|
| 748 |
+
|
| 749 |
+
# Potentially load in the weights and states from a previous save
|
| 750 |
+
if args.resume_from_checkpoint:
|
| 751 |
+
if args.resume_from_checkpoint != "latest":
|
| 752 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 753 |
+
else:
|
| 754 |
+
# Get the most recent checkpoint
|
| 755 |
+
dirs = os.listdir(args.output_dir)
|
| 756 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 757 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 758 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 759 |
+
|
| 760 |
+
if path is None:
|
| 761 |
+
accelerator.print(
|
| 762 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 763 |
+
)
|
| 764 |
+
args.resume_from_checkpoint = None
|
| 765 |
+
else:
|
| 766 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 767 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 768 |
+
global_step = int(path.split("-")[1])
|
| 769 |
+
|
| 770 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 771 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 772 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 773 |
+
|
| 774 |
+
# Only show the progress bar once on each machine.
|
| 775 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 776 |
+
progress_bar.set_description("Steps")
|
| 777 |
+
|
| 778 |
+
# keep original embeddings as reference
|
| 779 |
+
orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.clone()
|
| 780 |
+
|
| 781 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 782 |
+
text_encoder.train()
|
| 783 |
+
for step, batch in enumerate(train_dataloader):
|
| 784 |
+
# Skip steps until we reach the resumed step
|
| 785 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 786 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 787 |
+
progress_bar.update(1)
|
| 788 |
+
continue
|
| 789 |
+
if args.progressive_tokens:
|
| 790 |
+
train_dataset.prop_tokens_to_load = float(global_step) / args.progressive_tokens_max_steps
|
| 791 |
+
|
| 792 |
+
with accelerator.accumulate(text_encoder):
|
| 793 |
+
# Convert images to latent space
|
| 794 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample().detach()
|
| 795 |
+
latents = latents * vae.config.scaling_factor
|
| 796 |
+
|
| 797 |
+
# Sample noise that we'll add to the latents
|
| 798 |
+
noise = torch.randn_like(latents)
|
| 799 |
+
bsz = latents.shape[0]
|
| 800 |
+
# Sample a random timestep for each image
|
| 801 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 802 |
+
timesteps = timesteps.long()
|
| 803 |
+
|
| 804 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 805 |
+
# (this is the forward diffusion process)
|
| 806 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 807 |
+
|
| 808 |
+
# Get the text embedding for conditioning
|
| 809 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0].to(dtype=weight_dtype)
|
| 810 |
+
|
| 811 |
+
# Predict the noise residual
|
| 812 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 813 |
+
|
| 814 |
+
# Get the target for loss depending on the prediction type
|
| 815 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 816 |
+
target = noise
|
| 817 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 818 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 819 |
+
else:
|
| 820 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 821 |
+
|
| 822 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 823 |
+
|
| 824 |
+
accelerator.backward(loss)
|
| 825 |
+
|
| 826 |
+
optimizer.step()
|
| 827 |
+
lr_scheduler.step()
|
| 828 |
+
optimizer.zero_grad()
|
| 829 |
+
|
| 830 |
+
# Let's make sure we don't update any embedding weights besides the newly added token
|
| 831 |
+
index_no_updates = get_mask(tokenizer, accelerator)
|
| 832 |
+
with torch.no_grad():
|
| 833 |
+
accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[index_no_updates] = (
|
| 834 |
+
orig_embeds_params[index_no_updates]
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 838 |
+
if accelerator.sync_gradients:
|
| 839 |
+
progress_bar.update(1)
|
| 840 |
+
global_step += 1
|
| 841 |
+
if global_step % args.save_steps == 0:
|
| 842 |
+
save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
|
| 843 |
+
save_progress(tokenizer, text_encoder, accelerator, save_path)
|
| 844 |
+
|
| 845 |
+
if global_step % args.checkpointing_steps == 0:
|
| 846 |
+
if accelerator.is_main_process:
|
| 847 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 848 |
+
accelerator.save_state(save_path)
|
| 849 |
+
logger.info(f"Saved state to {save_path}")
|
| 850 |
+
|
| 851 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 852 |
+
progress_bar.set_postfix(**logs)
|
| 853 |
+
accelerator.log(logs, step=global_step)
|
| 854 |
+
|
| 855 |
+
if global_step >= args.max_train_steps:
|
| 856 |
+
break
|
| 857 |
+
|
| 858 |
+
if accelerator.is_main_process and args.validation_prompt is not None and epoch % args.validation_epochs == 0:
|
| 859 |
+
logger.info(
|
| 860 |
+
f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
|
| 861 |
+
f" {args.validation_prompt}."
|
| 862 |
+
)
|
| 863 |
+
# create pipeline (note: unet and vae are loaded again in float32)
|
| 864 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 865 |
+
args.pretrained_model_name_or_path,
|
| 866 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 867 |
+
tokenizer=tokenizer,
|
| 868 |
+
unet=unet,
|
| 869 |
+
vae=vae,
|
| 870 |
+
revision=args.revision,
|
| 871 |
+
torch_dtype=weight_dtype,
|
| 872 |
+
)
|
| 873 |
+
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
|
| 874 |
+
pipeline = pipeline.to(accelerator.device)
|
| 875 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 876 |
+
|
| 877 |
+
# run inference
|
| 878 |
+
generator = (
|
| 879 |
+
None if args.seed is None else torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 880 |
+
)
|
| 881 |
+
images = []
|
| 882 |
+
for _ in range(args.num_validation_images):
|
| 883 |
+
with torch.autocast("cuda"):
|
| 884 |
+
image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
|
| 885 |
+
images.append(image)
|
| 886 |
+
|
| 887 |
+
for tracker in accelerator.trackers:
|
| 888 |
+
if tracker.name == "tensorboard":
|
| 889 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 890 |
+
tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
|
| 891 |
+
if tracker.name == "wandb":
|
| 892 |
+
tracker.log(
|
| 893 |
+
{
|
| 894 |
+
"validation": [
|
| 895 |
+
wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
|
| 896 |
+
for i, image in enumerate(images)
|
| 897 |
+
]
|
| 898 |
+
}
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
del pipeline
|
| 902 |
+
torch.cuda.empty_cache()
|
| 903 |
+
|
| 904 |
+
# Create the pipeline using using the trained modules and save it.
|
| 905 |
+
accelerator.wait_for_everyone()
|
| 906 |
+
if accelerator.is_main_process:
|
| 907 |
+
if args.push_to_hub and args.only_save_embeds:
|
| 908 |
+
logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
|
| 909 |
+
save_full_model = True
|
| 910 |
+
else:
|
| 911 |
+
save_full_model = not args.only_save_embeds
|
| 912 |
+
if save_full_model:
|
| 913 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 914 |
+
args.pretrained_model_name_or_path,
|
| 915 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 916 |
+
vae=vae,
|
| 917 |
+
unet=unet,
|
| 918 |
+
tokenizer=tokenizer,
|
| 919 |
+
)
|
| 920 |
+
pipeline.save_pretrained(args.output_dir)
|
| 921 |
+
# Save the newly trained embeddings
|
| 922 |
+
save_path = os.path.join(args.output_dir, "learned_embeds.bin")
|
| 923 |
+
save_progress(tokenizer, text_encoder, accelerator, save_path)
|
| 924 |
+
|
| 925 |
+
if args.push_to_hub:
|
| 926 |
+
upload_folder(
|
| 927 |
+
repo_id=repo_id,
|
| 928 |
+
folder_path=args.output_dir,
|
| 929 |
+
commit_message="End of training",
|
| 930 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
accelerator.end_training()
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
if __name__ == "__main__":
|
| 937 |
+
main()
|
tasks/tasksmith-9ca70b8463d4/tests/source/examples/research_projects/multi_token_textual_inversion/textual_inversion_flax.py
AD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py 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 `huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/text_to_image/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stable Diffusion text-to-image fine-tuning
|
| 2 |
+
|
| 3 |
+
The `train_text_to_image.py` script shows how to fine-tune stable diffusion model on your own dataset.
|
| 4 |
+
|
| 5 |
+
___Note___:
|
| 6 |
+
|
| 7 |
+
___This script is experimental. The script fine-tunes the whole model and often times the model overfits and runs into issues like catastrophic forgetting. It's recommended to try different hyperparamters to get the best result on your dataset.___
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
## Running locally with PyTorch
|
| 11 |
+
### Installing the dependencies
|
| 12 |
+
|
| 13 |
+
Before running the scripts, make sure to install the library's training dependencies:
|
| 14 |
+
|
| 15 |
+
**Important**
|
| 16 |
+
|
| 17 |
+
To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
|
| 18 |
+
```bash
|
| 19 |
+
git clone https://github.com/huggingface/diffusers
|
| 20 |
+
cd diffusers
|
| 21 |
+
pip install .
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
Then cd in the example folder and run
|
| 25 |
+
```bash
|
| 26 |
+
pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
accelerate config
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
### Naruto example
|
| 36 |
+
|
| 37 |
+
You need to accept the model license before downloading or using the weights. In this example we'll use model version `v1-4`, so you'll need to visit [its card](https://huggingface.co/CompVis/stable-diffusion-v1-4), read the license and tick the checkbox if you agree.
|
| 38 |
+
|
| 39 |
+
You have to be a registered user in 🤗 Hugging Face Hub, and you'll also need to use an access token for the code to work. For more information on access tokens, please refer to [this section of the documentation](https://huggingface.co/docs/hub/security-tokens).
|
| 40 |
+
|
| 41 |
+
Run the following command to authenticate your token
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
huggingface-cli 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-9ca70b8463d4/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-9ca70b8463d4/tests/source/examples/research_projects/onnxruntime/text_to_image/train_text_to_image.py
ADDED
|
@@ -0,0 +1,954 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import logging
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
import random
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import accelerate
|
| 24 |
+
import datasets
|
| 25 |
+
import numpy as np
|
| 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.state import AcceleratorState
|
| 33 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 34 |
+
from datasets import load_dataset
|
| 35 |
+
from huggingface_hub import create_repo, upload_folder
|
| 36 |
+
from onnxruntime.training.optim.fp16_optimizer import FP16_Optimizer as ORT_FP16_Optimizer
|
| 37 |
+
from onnxruntime.training.ortmodule import ORTModule
|
| 38 |
+
from packaging import version
|
| 39 |
+
from torchvision import transforms
|
| 40 |
+
from tqdm.auto import tqdm
|
| 41 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 42 |
+
from transformers.utils import ContextManagers
|
| 43 |
+
|
| 44 |
+
import diffusers
|
| 45 |
+
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
| 46 |
+
from diffusers.optimization import get_scheduler
|
| 47 |
+
from diffusers.training_utils import EMAModel, compute_snr
|
| 48 |
+
from diffusers.utils import check_min_version, deprecate, is_wandb_available
|
| 49 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
if is_wandb_available():
|
| 53 |
+
import wandb
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 57 |
+
check_min_version("0.17.0.dev0")
|
| 58 |
+
|
| 59 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 60 |
+
|
| 61 |
+
DATASET_NAME_MAPPING = {
|
| 62 |
+
"lambdalabs/naruto-blip-captions": ("image", "text"),
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def log_validation(vae, text_encoder, tokenizer, unet, args, accelerator, weight_dtype, epoch):
|
| 67 |
+
logger.info("Running validation... ")
|
| 68 |
+
|
| 69 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 70 |
+
args.pretrained_model_name_or_path,
|
| 71 |
+
vae=accelerator.unwrap_model(vae),
|
| 72 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 73 |
+
tokenizer=tokenizer,
|
| 74 |
+
unet=accelerator.unwrap_model(unet),
|
| 75 |
+
safety_checker=None,
|
| 76 |
+
revision=args.revision,
|
| 77 |
+
torch_dtype=weight_dtype,
|
| 78 |
+
)
|
| 79 |
+
pipeline = pipeline.to(accelerator.device)
|
| 80 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 81 |
+
|
| 82 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 83 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 84 |
+
|
| 85 |
+
if args.seed is None:
|
| 86 |
+
generator = None
|
| 87 |
+
else:
|
| 88 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 89 |
+
|
| 90 |
+
images = []
|
| 91 |
+
for i in range(len(args.validation_prompts)):
|
| 92 |
+
with torch.autocast("cuda"):
|
| 93 |
+
image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0]
|
| 94 |
+
|
| 95 |
+
images.append(image)
|
| 96 |
+
|
| 97 |
+
for tracker in accelerator.trackers:
|
| 98 |
+
if tracker.name == "tensorboard":
|
| 99 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 100 |
+
tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
|
| 101 |
+
elif tracker.name == "wandb":
|
| 102 |
+
tracker.log(
|
| 103 |
+
{
|
| 104 |
+
"validation": [
|
| 105 |
+
wandb.Image(image, caption=f"{i}: {args.validation_prompts[i]}")
|
| 106 |
+
for i, image in enumerate(images)
|
| 107 |
+
]
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
else:
|
| 111 |
+
logger.warning(f"image logging not implemented for {tracker.name}")
|
| 112 |
+
|
| 113 |
+
del pipeline
|
| 114 |
+
torch.cuda.empty_cache()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def parse_args():
|
| 118 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--input_pertubation", type=float, default=0, help="The scale of input pretubation. Recommended 0.1."
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--pretrained_model_name_or_path",
|
| 124 |
+
type=str,
|
| 125 |
+
default=None,
|
| 126 |
+
required=True,
|
| 127 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--revision",
|
| 131 |
+
type=str,
|
| 132 |
+
default=None,
|
| 133 |
+
required=False,
|
| 134 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 135 |
+
)
|
| 136 |
+
parser.add_argument(
|
| 137 |
+
"--dataset_name",
|
| 138 |
+
type=str,
|
| 139 |
+
default=None,
|
| 140 |
+
help=(
|
| 141 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 142 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 143 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 144 |
+
),
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--dataset_config_name",
|
| 148 |
+
type=str,
|
| 149 |
+
default=None,
|
| 150 |
+
help="The config of the Dataset, leave as None if there's only one config.",
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--train_data_dir",
|
| 154 |
+
type=str,
|
| 155 |
+
default=None,
|
| 156 |
+
help=(
|
| 157 |
+
"A folder containing the training data. Folder contents must follow the structure described in"
|
| 158 |
+
" https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
|
| 159 |
+
" must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
|
| 160 |
+
),
|
| 161 |
+
)
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--image_column", type=str, default="image", help="The column of the dataset containing an image."
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--caption_column",
|
| 167 |
+
type=str,
|
| 168 |
+
default="text",
|
| 169 |
+
help="The column of the dataset containing a caption or a list of captions.",
|
| 170 |
+
)
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--max_train_samples",
|
| 173 |
+
type=int,
|
| 174 |
+
default=None,
|
| 175 |
+
help=(
|
| 176 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 177 |
+
"value if set."
|
| 178 |
+
),
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--validation_prompts",
|
| 182 |
+
type=str,
|
| 183 |
+
default=None,
|
| 184 |
+
nargs="+",
|
| 185 |
+
help=("A set of prompts evaluated every `--validation_epochs` and logged to `--report_to`."),
|
| 186 |
+
)
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--output_dir",
|
| 189 |
+
type=str,
|
| 190 |
+
default="sd-model-finetuned",
|
| 191 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument(
|
| 194 |
+
"--cache_dir",
|
| 195 |
+
type=str,
|
| 196 |
+
default=None,
|
| 197 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--resolution",
|
| 202 |
+
type=int,
|
| 203 |
+
default=512,
|
| 204 |
+
help=(
|
| 205 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 206 |
+
" resolution"
|
| 207 |
+
),
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--center_crop",
|
| 211 |
+
default=False,
|
| 212 |
+
action="store_true",
|
| 213 |
+
help=(
|
| 214 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 215 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 216 |
+
),
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--random_flip",
|
| 220 |
+
action="store_true",
|
| 221 |
+
help="whether to randomly flip images horizontally",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 225 |
+
)
|
| 226 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--max_train_steps",
|
| 229 |
+
type=int,
|
| 230 |
+
default=None,
|
| 231 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 232 |
+
)
|
| 233 |
+
parser.add_argument(
|
| 234 |
+
"--gradient_accumulation_steps",
|
| 235 |
+
type=int,
|
| 236 |
+
default=1,
|
| 237 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--gradient_checkpointing",
|
| 241 |
+
action="store_true",
|
| 242 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 243 |
+
)
|
| 244 |
+
parser.add_argument(
|
| 245 |
+
"--learning_rate",
|
| 246 |
+
type=float,
|
| 247 |
+
default=1e-4,
|
| 248 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"--scale_lr",
|
| 252 |
+
action="store_true",
|
| 253 |
+
default=False,
|
| 254 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"--lr_scheduler",
|
| 258 |
+
type=str,
|
| 259 |
+
default="constant",
|
| 260 |
+
help=(
|
| 261 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 262 |
+
' "constant", "constant_with_warmup"]'
|
| 263 |
+
),
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 267 |
+
)
|
| 268 |
+
parser.add_argument(
|
| 269 |
+
"--snr_gamma",
|
| 270 |
+
type=float,
|
| 271 |
+
default=None,
|
| 272 |
+
help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
|
| 273 |
+
"More details here: https://huggingface.co/papers/2303.09556.",
|
| 274 |
+
)
|
| 275 |
+
parser.add_argument(
|
| 276 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 277 |
+
)
|
| 278 |
+
parser.add_argument(
|
| 279 |
+
"--allow_tf32",
|
| 280 |
+
action="store_true",
|
| 281 |
+
help=(
|
| 282 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 283 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 284 |
+
),
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--non_ema_revision",
|
| 289 |
+
type=str,
|
| 290 |
+
default=None,
|
| 291 |
+
required=False,
|
| 292 |
+
help=(
|
| 293 |
+
"Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
|
| 294 |
+
" remote repository specified with --pretrained_model_name_or_path."
|
| 295 |
+
),
|
| 296 |
+
)
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--dataloader_num_workers",
|
| 299 |
+
type=int,
|
| 300 |
+
default=0,
|
| 301 |
+
help=(
|
| 302 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 303 |
+
),
|
| 304 |
+
)
|
| 305 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 306 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 307 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 308 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 309 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 310 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 311 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 312 |
+
parser.add_argument(
|
| 313 |
+
"--hub_model_id",
|
| 314 |
+
type=str,
|
| 315 |
+
default=None,
|
| 316 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 317 |
+
)
|
| 318 |
+
parser.add_argument(
|
| 319 |
+
"--logging_dir",
|
| 320 |
+
type=str,
|
| 321 |
+
default="logs",
|
| 322 |
+
help=(
|
| 323 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 324 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 325 |
+
),
|
| 326 |
+
)
|
| 327 |
+
parser.add_argument(
|
| 328 |
+
"--mixed_precision",
|
| 329 |
+
type=str,
|
| 330 |
+
default=None,
|
| 331 |
+
choices=["no", "fp16", "bf16"],
|
| 332 |
+
help=(
|
| 333 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 334 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 335 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 336 |
+
),
|
| 337 |
+
)
|
| 338 |
+
parser.add_argument(
|
| 339 |
+
"--report_to",
|
| 340 |
+
type=str,
|
| 341 |
+
default="tensorboard",
|
| 342 |
+
help=(
|
| 343 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 344 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 345 |
+
),
|
| 346 |
+
)
|
| 347 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 348 |
+
parser.add_argument(
|
| 349 |
+
"--checkpointing_steps",
|
| 350 |
+
type=int,
|
| 351 |
+
default=500,
|
| 352 |
+
help=(
|
| 353 |
+
"Save a checkpoint of the training state every X updates. These checkpoints are only 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=(
|
| 362 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 363 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 364 |
+
" for more docs"
|
| 365 |
+
),
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument(
|
| 368 |
+
"--resume_from_checkpoint",
|
| 369 |
+
type=str,
|
| 370 |
+
default=None,
|
| 371 |
+
help=(
|
| 372 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 373 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 374 |
+
),
|
| 375 |
+
)
|
| 376 |
+
parser.add_argument(
|
| 377 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 378 |
+
)
|
| 379 |
+
parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
|
| 380 |
+
parser.add_argument(
|
| 381 |
+
"--validation_epochs",
|
| 382 |
+
type=int,
|
| 383 |
+
default=5,
|
| 384 |
+
help="Run validation every X epochs.",
|
| 385 |
+
)
|
| 386 |
+
parser.add_argument(
|
| 387 |
+
"--tracker_project_name",
|
| 388 |
+
type=str,
|
| 389 |
+
default="text2image-fine-tune",
|
| 390 |
+
help=(
|
| 391 |
+
"The `project_name` argument passed to Accelerator.init_trackers for"
|
| 392 |
+
" more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
|
| 393 |
+
),
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
args = parser.parse_args()
|
| 397 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 398 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 399 |
+
args.local_rank = env_local_rank
|
| 400 |
+
|
| 401 |
+
# Sanity checks
|
| 402 |
+
if args.dataset_name is None and args.train_data_dir is None:
|
| 403 |
+
raise ValueError("Need either a dataset name or a training folder.")
|
| 404 |
+
|
| 405 |
+
# default to using the same revision for the non-ema model if not specified
|
| 406 |
+
if args.non_ema_revision is None:
|
| 407 |
+
args.non_ema_revision = args.revision
|
| 408 |
+
|
| 409 |
+
return args
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def main():
|
| 413 |
+
args = parse_args()
|
| 414 |
+
|
| 415 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 416 |
+
raise ValueError(
|
| 417 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 418 |
+
" Please use `huggingface-cli login` to authenticate with the Hub."
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
if args.non_ema_revision is not None:
|
| 422 |
+
deprecate(
|
| 423 |
+
"non_ema_revision!=None",
|
| 424 |
+
"0.15.0",
|
| 425 |
+
message=(
|
| 426 |
+
"Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
|
| 427 |
+
" use `--variant=non_ema` instead."
|
| 428 |
+
),
|
| 429 |
+
)
|
| 430 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 431 |
+
accelerator_project_config = ProjectConfiguration(
|
| 432 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
accelerator = Accelerator(
|
| 436 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 437 |
+
mixed_precision=args.mixed_precision,
|
| 438 |
+
log_with=args.report_to,
|
| 439 |
+
project_config=accelerator_project_config,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Disable AMP for MPS.
|
| 443 |
+
if torch.backends.mps.is_available():
|
| 444 |
+
accelerator.native_amp = False
|
| 445 |
+
|
| 446 |
+
# Make one log on every process with the configuration for debugging.
|
| 447 |
+
logging.basicConfig(
|
| 448 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 449 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 450 |
+
level=logging.INFO,
|
| 451 |
+
)
|
| 452 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 453 |
+
if accelerator.is_local_main_process:
|
| 454 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 455 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 456 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 457 |
+
else:
|
| 458 |
+
datasets.utils.logging.set_verbosity_error()
|
| 459 |
+
transformers.utils.logging.set_verbosity_error()
|
| 460 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 461 |
+
|
| 462 |
+
# If passed along, set the training seed now.
|
| 463 |
+
if args.seed is not None:
|
| 464 |
+
set_seed(args.seed)
|
| 465 |
+
|
| 466 |
+
# Handle the repository creation
|
| 467 |
+
if accelerator.is_main_process:
|
| 468 |
+
if args.output_dir is not None:
|
| 469 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 470 |
+
|
| 471 |
+
if args.push_to_hub:
|
| 472 |
+
repo_id = create_repo(
|
| 473 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 474 |
+
).repo_id
|
| 475 |
+
|
| 476 |
+
# Load scheduler, tokenizer and models.
|
| 477 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 478 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 479 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
def deepspeed_zero_init_disabled_context_manager():
|
| 483 |
+
"""
|
| 484 |
+
returns either a context list that includes one that will disable zero.Init or an empty context list
|
| 485 |
+
"""
|
| 486 |
+
deepspeed_plugin = AcceleratorState().deepspeed_plugin if accelerate.state.is_initialized() else None
|
| 487 |
+
if deepspeed_plugin is None:
|
| 488 |
+
return []
|
| 489 |
+
|
| 490 |
+
return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
|
| 491 |
+
|
| 492 |
+
# Currently Accelerate doesn't know how to handle multiple models under Deepspeed ZeRO stage 3.
|
| 493 |
+
# For this to work properly all models must be run through `accelerate.prepare`. But accelerate
|
| 494 |
+
# will try to assign the same optimizer with the same weights to all models during
|
| 495 |
+
# `deepspeed.initialize`, which of course doesn't work.
|
| 496 |
+
#
|
| 497 |
+
# For now the following workaround will partially support Deepspeed ZeRO-3, by excluding the 2
|
| 498 |
+
# frozen models from being partitioned during `zero.Init` which gets called during
|
| 499 |
+
# `from_pretrained` So CLIPTextModel and AutoencoderKL will not enjoy the parameter sharding
|
| 500 |
+
# across multiple gpus and only UNet2DConditionModel will get ZeRO sharded.
|
| 501 |
+
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
|
| 502 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 503 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 504 |
+
)
|
| 505 |
+
vae = AutoencoderKL.from_pretrained(
|
| 506 |
+
args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 510 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Freeze vae and text_encoder
|
| 514 |
+
vae.requires_grad_(False)
|
| 515 |
+
text_encoder.requires_grad_(False)
|
| 516 |
+
|
| 517 |
+
# Create EMA for the unet.
|
| 518 |
+
if args.use_ema:
|
| 519 |
+
ema_unet = UNet2DConditionModel.from_pretrained(
|
| 520 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 521 |
+
)
|
| 522 |
+
ema_unet = EMAModel(ema_unet.parameters(), model_cls=UNet2DConditionModel, model_config=ema_unet.config)
|
| 523 |
+
|
| 524 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 525 |
+
if is_xformers_available():
|
| 526 |
+
import xformers
|
| 527 |
+
|
| 528 |
+
xformers_version = version.parse(xformers.__version__)
|
| 529 |
+
if xformers_version == version.parse("0.0.16"):
|
| 530 |
+
logger.warning(
|
| 531 |
+
"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."
|
| 532 |
+
)
|
| 533 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 534 |
+
else:
|
| 535 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 536 |
+
|
| 537 |
+
# `accelerate` 0.16.0 will have better support for customized saving
|
| 538 |
+
if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
|
| 539 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 540 |
+
def save_model_hook(models, weights, output_dir):
|
| 541 |
+
if accelerator.is_main_process:
|
| 542 |
+
if args.use_ema:
|
| 543 |
+
ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
|
| 544 |
+
|
| 545 |
+
for i, model in enumerate(models):
|
| 546 |
+
model.save_pretrained(os.path.join(output_dir, "unet"))
|
| 547 |
+
|
| 548 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 549 |
+
weights.pop()
|
| 550 |
+
|
| 551 |
+
def load_model_hook(models, input_dir):
|
| 552 |
+
if args.use_ema:
|
| 553 |
+
load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
|
| 554 |
+
ema_unet.load_state_dict(load_model.state_dict())
|
| 555 |
+
ema_unet.to(accelerator.device)
|
| 556 |
+
del load_model
|
| 557 |
+
|
| 558 |
+
for i in range(len(models)):
|
| 559 |
+
# pop models so that they are not loaded again
|
| 560 |
+
model = models.pop()
|
| 561 |
+
|
| 562 |
+
# load diffusers style into model
|
| 563 |
+
load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
|
| 564 |
+
model.register_to_config(**load_model.config)
|
| 565 |
+
|
| 566 |
+
model.load_state_dict(load_model.state_dict())
|
| 567 |
+
del load_model
|
| 568 |
+
|
| 569 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 570 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 571 |
+
|
| 572 |
+
if args.gradient_checkpointing:
|
| 573 |
+
unet.enable_gradient_checkpointing()
|
| 574 |
+
|
| 575 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 576 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 577 |
+
if args.allow_tf32:
|
| 578 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 579 |
+
|
| 580 |
+
if args.scale_lr:
|
| 581 |
+
args.learning_rate = (
|
| 582 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
# Initialize the optimizer
|
| 586 |
+
if args.use_8bit_adam:
|
| 587 |
+
try:
|
| 588 |
+
import bitsandbytes as bnb
|
| 589 |
+
except ImportError:
|
| 590 |
+
raise ImportError(
|
| 591 |
+
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
optimizer_cls = bnb.optim.AdamW8bit
|
| 595 |
+
else:
|
| 596 |
+
optimizer_cls = torch.optim.AdamW
|
| 597 |
+
|
| 598 |
+
optimizer = optimizer_cls(
|
| 599 |
+
unet.parameters(),
|
| 600 |
+
lr=args.learning_rate,
|
| 601 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 602 |
+
weight_decay=args.adam_weight_decay,
|
| 603 |
+
eps=args.adam_epsilon,
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
optimizer = ORT_FP16_Optimizer(optimizer)
|
| 607 |
+
|
| 608 |
+
# Get the datasets: you can either provide your own training and evaluation files (see below)
|
| 609 |
+
# or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
|
| 610 |
+
|
| 611 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
| 612 |
+
# download the dataset.
|
| 613 |
+
if args.dataset_name is not None:
|
| 614 |
+
# Downloading and loading a dataset from the hub.
|
| 615 |
+
dataset = load_dataset(
|
| 616 |
+
args.dataset_name,
|
| 617 |
+
args.dataset_config_name,
|
| 618 |
+
cache_dir=args.cache_dir,
|
| 619 |
+
)
|
| 620 |
+
else:
|
| 621 |
+
data_files = {}
|
| 622 |
+
if args.train_data_dir is not None:
|
| 623 |
+
data_files["train"] = os.path.join(args.train_data_dir, "**")
|
| 624 |
+
dataset = load_dataset(
|
| 625 |
+
"imagefolder",
|
| 626 |
+
data_files=data_files,
|
| 627 |
+
cache_dir=args.cache_dir,
|
| 628 |
+
)
|
| 629 |
+
# See more about loading custom images at
|
| 630 |
+
# https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
|
| 631 |
+
|
| 632 |
+
# Preprocessing the datasets.
|
| 633 |
+
# We need to tokenize inputs and targets.
|
| 634 |
+
column_names = dataset["train"].column_names
|
| 635 |
+
|
| 636 |
+
# 6. Get the column names for input/target.
|
| 637 |
+
dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
|
| 638 |
+
if args.image_column is None:
|
| 639 |
+
image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
|
| 640 |
+
else:
|
| 641 |
+
image_column = args.image_column
|
| 642 |
+
if image_column not in column_names:
|
| 643 |
+
raise ValueError(
|
| 644 |
+
f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
|
| 645 |
+
)
|
| 646 |
+
if args.caption_column is None:
|
| 647 |
+
caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
|
| 648 |
+
else:
|
| 649 |
+
caption_column = args.caption_column
|
| 650 |
+
if caption_column not in column_names:
|
| 651 |
+
raise ValueError(
|
| 652 |
+
f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
# Preprocessing the datasets.
|
| 656 |
+
# We need to tokenize input captions and transform the images.
|
| 657 |
+
def tokenize_captions(examples, is_train=True):
|
| 658 |
+
captions = []
|
| 659 |
+
for caption in examples[caption_column]:
|
| 660 |
+
if isinstance(caption, str):
|
| 661 |
+
captions.append(caption)
|
| 662 |
+
elif isinstance(caption, (list, np.ndarray)):
|
| 663 |
+
# take a random caption if there are multiple
|
| 664 |
+
captions.append(random.choice(caption) if is_train else caption[0])
|
| 665 |
+
else:
|
| 666 |
+
raise ValueError(
|
| 667 |
+
f"Caption column `{caption_column}` should contain either strings or lists of strings."
|
| 668 |
+
)
|
| 669 |
+
inputs = tokenizer(
|
| 670 |
+
captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
|
| 671 |
+
)
|
| 672 |
+
return inputs.input_ids
|
| 673 |
+
|
| 674 |
+
# Preprocessing the datasets.
|
| 675 |
+
train_transforms = transforms.Compose(
|
| 676 |
+
[
|
| 677 |
+
transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 678 |
+
transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
|
| 679 |
+
transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
|
| 680 |
+
transforms.ToTensor(),
|
| 681 |
+
transforms.Normalize([0.5], [0.5]),
|
| 682 |
+
]
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
def preprocess_train(examples):
|
| 686 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 687 |
+
examples["pixel_values"] = [train_transforms(image) for image in images]
|
| 688 |
+
examples["input_ids"] = tokenize_captions(examples)
|
| 689 |
+
return examples
|
| 690 |
+
|
| 691 |
+
with accelerator.main_process_first():
|
| 692 |
+
if args.max_train_samples is not None:
|
| 693 |
+
dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 694 |
+
# Set the training transforms
|
| 695 |
+
train_dataset = dataset["train"].with_transform(preprocess_train)
|
| 696 |
+
|
| 697 |
+
def collate_fn(examples):
|
| 698 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 699 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 700 |
+
input_ids = torch.stack([example["input_ids"] for example in examples])
|
| 701 |
+
return {"pixel_values": pixel_values, "input_ids": input_ids}
|
| 702 |
+
|
| 703 |
+
# DataLoaders creation:
|
| 704 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 705 |
+
train_dataset,
|
| 706 |
+
shuffle=True,
|
| 707 |
+
collate_fn=collate_fn,
|
| 708 |
+
batch_size=args.train_batch_size,
|
| 709 |
+
num_workers=args.dataloader_num_workers,
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
# Scheduler and math around the number of training steps.
|
| 713 |
+
overrode_max_train_steps = False
|
| 714 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 715 |
+
if args.max_train_steps is None:
|
| 716 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 717 |
+
overrode_max_train_steps = True
|
| 718 |
+
|
| 719 |
+
lr_scheduler = get_scheduler(
|
| 720 |
+
args.lr_scheduler,
|
| 721 |
+
optimizer=optimizer,
|
| 722 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 723 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# Prepare everything with our `accelerator`.
|
| 727 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 728 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
if args.use_ema:
|
| 732 |
+
ema_unet.to(accelerator.device)
|
| 733 |
+
|
| 734 |
+
unet = ORTModule(unet)
|
| 735 |
+
|
| 736 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 737 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 738 |
+
weight_dtype = torch.float32
|
| 739 |
+
if accelerator.mixed_precision == "fp16":
|
| 740 |
+
weight_dtype = torch.float16
|
| 741 |
+
elif accelerator.mixed_precision == "bf16":
|
| 742 |
+
weight_dtype = torch.bfloat16
|
| 743 |
+
|
| 744 |
+
# Move text_encode and vae to gpu and cast to weight_dtype
|
| 745 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 746 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 747 |
+
|
| 748 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 749 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 750 |
+
if overrode_max_train_steps:
|
| 751 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 752 |
+
# Afterwards we recalculate our number of training epochs
|
| 753 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 754 |
+
|
| 755 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 756 |
+
# The trackers initializes automatically on the main process.
|
| 757 |
+
if accelerator.is_main_process:
|
| 758 |
+
tracker_config = dict(vars(args))
|
| 759 |
+
tracker_config.pop("validation_prompts")
|
| 760 |
+
accelerator.init_trackers(args.tracker_project_name, tracker_config)
|
| 761 |
+
|
| 762 |
+
# Train!
|
| 763 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 764 |
+
|
| 765 |
+
logger.info("***** Running training *****")
|
| 766 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 767 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 768 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 769 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 770 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 771 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 772 |
+
global_step = 0
|
| 773 |
+
first_epoch = 0
|
| 774 |
+
|
| 775 |
+
# Potentially load in the weights and states from a previous save
|
| 776 |
+
if args.resume_from_checkpoint:
|
| 777 |
+
if args.resume_from_checkpoint != "latest":
|
| 778 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 779 |
+
else:
|
| 780 |
+
# Get the most recent checkpoint
|
| 781 |
+
dirs = os.listdir(args.output_dir)
|
| 782 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 783 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 784 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 785 |
+
|
| 786 |
+
if path is None:
|
| 787 |
+
accelerator.print(
|
| 788 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 789 |
+
)
|
| 790 |
+
args.resume_from_checkpoint = None
|
| 791 |
+
else:
|
| 792 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 793 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 794 |
+
global_step = int(path.split("-")[1])
|
| 795 |
+
|
| 796 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 797 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 798 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 799 |
+
|
| 800 |
+
# Only show the progress bar once on each machine.
|
| 801 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 802 |
+
progress_bar.set_description("Steps")
|
| 803 |
+
|
| 804 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 805 |
+
unet.train()
|
| 806 |
+
train_loss = 0.0
|
| 807 |
+
for step, batch in enumerate(train_dataloader):
|
| 808 |
+
# Skip steps until we reach the resumed step
|
| 809 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 810 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 811 |
+
progress_bar.update(1)
|
| 812 |
+
continue
|
| 813 |
+
|
| 814 |
+
with accelerator.accumulate(unet):
|
| 815 |
+
# Convert images to latent space
|
| 816 |
+
latents = vae.encode(batch["pixel_values"].to(weight_dtype)).latent_dist.sample()
|
| 817 |
+
latents = latents * vae.config.scaling_factor
|
| 818 |
+
|
| 819 |
+
# Sample noise that we'll add to the latents
|
| 820 |
+
noise = torch.randn_like(latents)
|
| 821 |
+
if args.noise_offset:
|
| 822 |
+
# https://www.crosslabs.org//blog/diffusion-with-offset-noise
|
| 823 |
+
noise += args.noise_offset * torch.randn(
|
| 824 |
+
(latents.shape[0], latents.shape[1], 1, 1), device=latents.device
|
| 825 |
+
)
|
| 826 |
+
if args.input_pertubation:
|
| 827 |
+
new_noise = noise + args.input_pertubation * torch.randn_like(noise)
|
| 828 |
+
bsz = latents.shape[0]
|
| 829 |
+
# Sample a random timestep for each image
|
| 830 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 831 |
+
timesteps = timesteps.long()
|
| 832 |
+
|
| 833 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 834 |
+
# (this is the forward diffusion process)
|
| 835 |
+
if args.input_pertubation:
|
| 836 |
+
noisy_latents = noise_scheduler.add_noise(latents, new_noise, timesteps)
|
| 837 |
+
else:
|
| 838 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 839 |
+
|
| 840 |
+
# Get the text embedding for conditioning
|
| 841 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 842 |
+
|
| 843 |
+
# Get the target for loss depending on the prediction type
|
| 844 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 845 |
+
target = noise
|
| 846 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 847 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 848 |
+
else:
|
| 849 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 850 |
+
|
| 851 |
+
# Predict the noise residual and compute loss
|
| 852 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 853 |
+
|
| 854 |
+
if args.snr_gamma is None:
|
| 855 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 856 |
+
else:
|
| 857 |
+
# Compute loss-weights as per Section 3.4 of https://huggingface.co/papers/2303.09556.
|
| 858 |
+
# Since we predict the noise instead of x_0, the original formulation is slightly changed.
|
| 859 |
+
# This is discussed in Section 4.2 of the same paper.
|
| 860 |
+
snr = compute_snr(noise_scheduler, timesteps)
|
| 861 |
+
mse_loss_weights = torch.stack([snr, args.snr_gamma * torch.ones_like(timesteps)], dim=1).min(
|
| 862 |
+
dim=1
|
| 863 |
+
)[0]
|
| 864 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 865 |
+
mse_loss_weights = mse_loss_weights / snr
|
| 866 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 867 |
+
mse_loss_weights = mse_loss_weights / (snr + 1)
|
| 868 |
+
|
| 869 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
| 870 |
+
loss = loss.mean(dim=list(range(1, len(loss.shape)))) * mse_loss_weights
|
| 871 |
+
loss = loss.mean()
|
| 872 |
+
|
| 873 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 874 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
|
| 875 |
+
train_loss += avg_loss.item() / args.gradient_accumulation_steps
|
| 876 |
+
|
| 877 |
+
# Backpropagate
|
| 878 |
+
accelerator.backward(loss)
|
| 879 |
+
if accelerator.sync_gradients:
|
| 880 |
+
accelerator.clip_grad_norm_(unet.parameters(), args.max_grad_norm)
|
| 881 |
+
optimizer.step()
|
| 882 |
+
lr_scheduler.step()
|
| 883 |
+
optimizer.zero_grad()
|
| 884 |
+
|
| 885 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 886 |
+
if accelerator.sync_gradients:
|
| 887 |
+
if args.use_ema:
|
| 888 |
+
ema_unet.step(unet.parameters())
|
| 889 |
+
progress_bar.update(1)
|
| 890 |
+
global_step += 1
|
| 891 |
+
accelerator.log({"train_loss": train_loss}, step=global_step)
|
| 892 |
+
train_loss = 0.0
|
| 893 |
+
|
| 894 |
+
if global_step % args.checkpointing_steps == 0:
|
| 895 |
+
if accelerator.is_main_process:
|
| 896 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 897 |
+
accelerator.save_state(save_path)
|
| 898 |
+
logger.info(f"Saved state to {save_path}")
|
| 899 |
+
|
| 900 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 901 |
+
progress_bar.set_postfix(**logs)
|
| 902 |
+
|
| 903 |
+
if global_step >= args.max_train_steps:
|
| 904 |
+
break
|
| 905 |
+
|
| 906 |
+
if accelerator.is_main_process:
|
| 907 |
+
if args.validation_prompts is not None and epoch % args.validation_epochs == 0:
|
| 908 |
+
if args.use_ema:
|
| 909 |
+
# Store the UNet parameters temporarily and load the EMA parameters to perform inference.
|
| 910 |
+
ema_unet.store(unet.parameters())
|
| 911 |
+
ema_unet.copy_to(unet.parameters())
|
| 912 |
+
log_validation(
|
| 913 |
+
vae,
|
| 914 |
+
text_encoder,
|
| 915 |
+
tokenizer,
|
| 916 |
+
unet,
|
| 917 |
+
args,
|
| 918 |
+
accelerator,
|
| 919 |
+
weight_dtype,
|
| 920 |
+
global_step,
|
| 921 |
+
)
|
| 922 |
+
if args.use_ema:
|
| 923 |
+
# Switch back to the original UNet parameters.
|
| 924 |
+
ema_unet.restore(unet.parameters())
|
| 925 |
+
|
| 926 |
+
# Create the pipeline using the trained modules and save it.
|
| 927 |
+
accelerator.wait_for_everyone()
|
| 928 |
+
if accelerator.is_main_process:
|
| 929 |
+
unet = accelerator.unwrap_model(unet)
|
| 930 |
+
if args.use_ema:
|
| 931 |
+
ema_unet.copy_to(unet.parameters())
|
| 932 |
+
|
| 933 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 934 |
+
args.pretrained_model_name_or_path,
|
| 935 |
+
text_encoder=text_encoder,
|
| 936 |
+
vae=vae,
|
| 937 |
+
unet=unet,
|
| 938 |
+
revision=args.revision,
|
| 939 |
+
)
|
| 940 |
+
pipeline.save_pretrained(args.output_dir)
|
| 941 |
+
|
| 942 |
+
if args.push_to_hub:
|
| 943 |
+
upload_folder(
|
| 944 |
+
repo_id=repo_id,
|
| 945 |
+
folder_path=args.output_dir,
|
| 946 |
+
commit_message="End of training",
|
| 947 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 948 |
+
)
|
| 949 |
+
|
| 950 |
+
accelerator.end_training()
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
if __name__ == "__main__":
|
| 954 |
+
main()
|