Skip to content

Commit 7f0eb35

Browse files
Research project multi subject dreambooth (huggingface#1948)
* implemented multi subject dreambooth in research_projects * minor edits to readme * added style and quality fixes Co-authored-by: Krista Opsahl-Ong <[email protected]>
1 parent 40aa162 commit 7f0eb35

File tree

3 files changed

+1166
-0
lines changed

3 files changed

+1166
-0
lines changed
Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
# Multi Subject DreamBooth training
2+
3+
[DreamBooth](https://arxiv.org/abs/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+
### Inference
90+
91+
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.
92+
93+
```python
94+
from diffusers import StableDiffusionPipeline
95+
import torch
96+
97+
model_id = "path-to-your-trained-model"
98+
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
99+
100+
prompt = "A photo of a t@y person petting an sks dog"
101+
image = pipe(prompt, num_inference_steps=200, guidance_scale=7.5).images[0]
102+
103+
image.save("person-petting-dog.png")
104+
```
105+
106+
### Inference from a training checkpoint
107+
108+
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.
109+
110+
## Additional Dreambooth documentation
111+
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.
112+
113+
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.
114+
115+
### Single subject dog toy example
116+
117+
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.
118+
119+
And launch the training using
120+
121+
**___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
122+
123+
```bash
124+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
125+
export INSTANCE_DIR="path-to-instance-images"
126+
export OUTPUT_DIR="path-to-save-model"
127+
128+
accelerate launch train_dreambooth.py \
129+
--pretrained_model_name_or_path=$MODEL_NAME \
130+
--instance_data_dir=$INSTANCE_DIR \
131+
--output_dir=$OUTPUT_DIR \
132+
--instance_prompt="a photo of sks dog" \
133+
--resolution=512 \
134+
--train_batch_size=1 \
135+
--gradient_accumulation_steps=1 \
136+
--learning_rate=5e-6 \
137+
--lr_scheduler="constant" \
138+
--lr_warmup_steps=0 \
139+
--max_train_steps=400
140+
```
141+
142+
### Training with prior-preservation loss
143+
144+
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.
145+
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.
146+
147+
```bash
148+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
149+
export INSTANCE_DIR="path-to-instance-images"
150+
export CLASS_DIR="path-to-class-images"
151+
export OUTPUT_DIR="path-to-save-model"
152+
153+
accelerate launch train_dreambooth.py \
154+
--pretrained_model_name_or_path=$MODEL_NAME \
155+
--instance_data_dir=$INSTANCE_DIR \
156+
--class_data_dir=$CLASS_DIR \
157+
--output_dir=$OUTPUT_DIR \
158+
--with_prior_preservation --prior_loss_weight=1.0 \
159+
--instance_prompt="a photo of sks dog" \
160+
--class_prompt="a photo of dog" \
161+
--resolution=512 \
162+
--train_batch_size=1 \
163+
--gradient_accumulation_steps=1 \
164+
--learning_rate=5e-6 \
165+
--lr_scheduler="constant" \
166+
--lr_warmup_steps=0 \
167+
--num_class_images=200 \
168+
--max_train_steps=800
169+
```
170+
171+
172+
### Training on a 16GB GPU:
173+
174+
With the help of gradient checkpointing and the 8-bit optimizer from bitsandbytes it's possible to run train dreambooth on a 16GB GPU.
175+
176+
To install `bitandbytes` please refer to this [readme](https://github.com/TimDettmers/bitsandbytes#requirements--installation).
177+
178+
```bash
179+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
180+
export INSTANCE_DIR="path-to-instance-images"
181+
export CLASS_DIR="path-to-class-images"
182+
export OUTPUT_DIR="path-to-save-model"
183+
184+
accelerate launch train_dreambooth.py \
185+
--pretrained_model_name_or_path=$MODEL_NAME \
186+
--instance_data_dir=$INSTANCE_DIR \
187+
--class_data_dir=$CLASS_DIR \
188+
--output_dir=$OUTPUT_DIR \
189+
--with_prior_preservation --prior_loss_weight=1.0 \
190+
--instance_prompt="a photo of sks dog" \
191+
--class_prompt="a photo of dog" \
192+
--resolution=512 \
193+
--train_batch_size=1 \
194+
--gradient_accumulation_steps=2 --gradient_checkpointing \
195+
--use_8bit_adam \
196+
--learning_rate=5e-6 \
197+
--lr_scheduler="constant" \
198+
--lr_warmup_steps=0 \
199+
--num_class_images=200 \
200+
--max_train_steps=800
201+
```
202+
203+
### Training on a 8 GB GPU:
204+
205+
By using [DeepSpeed](https://www.deepspeed.ai/) it's possible to offload some
206+
tensors from VRAM to either CPU or NVME allowing to train with less VRAM.
207+
208+
DeepSpeed needs to be enabled with `accelerate config`. During configuration
209+
answer yes to "Do you want to use DeepSpeed?". With DeepSpeed stage 2, fp16
210+
mixed precision and offloading both parameters and optimizer state to cpu it's
211+
possible to train on under 8 GB VRAM with a drawback of requiring significantly
212+
more RAM (about 25 GB). See [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more DeepSpeed configuration options.
213+
214+
Changing the default Adam optimizer to DeepSpeed's special version of Adam
215+
`deepspeed.ops.adam.DeepSpeedCPUAdam` gives a substantial speedup but enabling
216+
it requires CUDA toolchain with the same version as pytorch. 8-bit optimizer
217+
does not seem to be compatible with DeepSpeed at the moment.
218+
219+
```bash
220+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
221+
export INSTANCE_DIR="path-to-instance-images"
222+
export CLASS_DIR="path-to-class-images"
223+
export OUTPUT_DIR="path-to-save-model"
224+
225+
accelerate launch --mixed_precision="fp16" train_dreambooth.py \
226+
--pretrained_model_name_or_path=$MODEL_NAME \
227+
--instance_data_dir=$INSTANCE_DIR \
228+
--class_data_dir=$CLASS_DIR \
229+
--output_dir=$OUTPUT_DIR \
230+
--with_prior_preservation --prior_loss_weight=1.0 \
231+
--instance_prompt="a photo of sks dog" \
232+
--class_prompt="a photo of dog" \
233+
--resolution=512 \
234+
--train_batch_size=1 \
235+
--sample_batch_size=1 \
236+
--gradient_accumulation_steps=1 --gradient_checkpointing \
237+
--learning_rate=5e-6 \
238+
--lr_scheduler="constant" \
239+
--lr_warmup_steps=0 \
240+
--num_class_images=200 \
241+
--max_train_steps=800
242+
```
243+
244+
### Fine-tune text encoder with the UNet.
245+
246+
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.
247+
Pass the `--train_text_encoder` argument to the script to enable training `text_encoder`.
248+
249+
___Note: Training text encoder requires more memory, with this option the training won't fit on 16GB GPU. It needs at least 24GB VRAM.___
250+
251+
```bash
252+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
253+
export INSTANCE_DIR="path-to-instance-images"
254+
export CLASS_DIR="path-to-class-images"
255+
export OUTPUT_DIR="path-to-save-model"
256+
257+
accelerate launch train_dreambooth.py \
258+
--pretrained_model_name_or_path=$MODEL_NAME \
259+
--train_text_encoder \
260+
--instance_data_dir=$INSTANCE_DIR \
261+
--class_data_dir=$CLASS_DIR \
262+
--output_dir=$OUTPUT_DIR \
263+
--with_prior_preservation --prior_loss_weight=1.0 \
264+
--instance_prompt="a photo of sks dog" \
265+
--class_prompt="a photo of dog" \
266+
--resolution=512 \
267+
--train_batch_size=1 \
268+
--use_8bit_adam \
269+
--gradient_checkpointing \
270+
--learning_rate=2e-6 \
271+
--lr_scheduler="constant" \
272+
--lr_warmup_steps=0 \
273+
--num_class_images=200 \
274+
--max_train_steps=800
275+
```
276+
277+
### Using DreamBooth for other pipelines than Stable Diffusion
278+
279+
Altdiffusion also support dreambooth now, the runing comman is basically the same as abouve, all you need to do is replace the `MODEL_NAME` like this:
280+
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).
281+
282+
```
283+
export MODEL_NAME="CompVis/stable-diffusion-v1-4" --> export MODEL_NAME="BAAI/AltDiffusion-m9"
284+
or
285+
export MODEL_NAME="CompVis/stable-diffusion-v1-4" --> export MODEL_NAME="BAAI/AltDiffusion"
286+
```
287+
288+
### Training with xformers:
289+
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.
290+
291+
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).
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
accelerate
2+
torchvision
3+
transformers>=4.25.1
4+
ftfy
5+
tensorboard
6+
modelcards

0 commit comments

Comments
 (0)