Skip to content

Commit c002731

Browse files
[examples] add controlnet sd3 example (#9249)
* add controlnet sd3 example * add controlnet sd3 example * update controlnet sd3 example * add controlnet sd3 example test * fix quality and style * update test * update test --------- Co-authored-by: Sayak Paul <[email protected]>
1 parent adf1f91 commit c002731

File tree

4 files changed

+1596
-0
lines changed

4 files changed

+1596
-0
lines changed

examples/controlnet/README_sd3.md

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# ControlNet training example for Stable Diffusion 3 (SD3)
2+
3+
The `train_controlnet_sd3.py` script shows how to implement the ControlNet training procedure and adapt it for [Stable Diffusion 3](https://arxiv.org/abs/2403.03206).
4+
5+
## Running 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 `examples/controlnet` folder and run
22+
```bash
23+
pip install -r requirements_sd3.txt
24+
```
25+
26+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
27+
28+
```bash
29+
accelerate config
30+
```
31+
32+
Or for a default accelerate configuration without answering questions about your environment
33+
34+
```bash
35+
accelerate config default
36+
```
37+
38+
Or if your environment doesn't support an interactive shell (e.g., a notebook)
39+
40+
```python
41+
from accelerate.utils import write_basic_config
42+
write_basic_config()
43+
```
44+
45+
When running `accelerate config`, if we specify torch compile mode to True there can be dramatic speedups.
46+
47+
## Circle filling dataset
48+
49+
The original dataset is hosted in the [ControlNet repo](https://huggingface.co/lllyasviel/ControlNet/blob/main/training/fill50k.zip). We re-uploaded it to be compatible with `datasets` [here](https://huggingface.co/datasets/fusing/fill50k). Note that `datasets` handles dataloading within the training script.
50+
Please download the dataset and unzip it in the directory `fill50k` in the `examples/controlnet` folder.
51+
52+
## Training
53+
54+
First download the SD3 model from [Hugging Face Hub](https://huggingface.co/stabilityai/stable-diffusion-3-medium). We will use it as a base model for the ControlNet training.
55+
> [!NOTE]
56+
> As the model is gated, before using it with diffusers you first need to go to the [Stable Diffusion 3 Medium Hugging Face page](https://huggingface.co/stabilityai/stable-diffusion-3-medium-diffusers), fill in the form and accept the gate. Once you are in, you need to log in so that your system knows you’ve accepted the gate. Use the command below to log in:
57+
58+
```bash
59+
huggingface-cli login
60+
```
61+
62+
This will also allow us to push the trained model parameters to the Hugging Face Hub platform.
63+
64+
65+
Our training examples use two test conditioning images. They can be downloaded by running
66+
67+
```sh
68+
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png
69+
70+
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_2.png
71+
```
72+
73+
Then run the following commands to train a ControlNet model.
74+
75+
```bash
76+
export MODEL_DIR="stabilityai/stable-diffusion-3-medium-diffusers"
77+
export OUTPUT_DIR="sd3-controlnet-out"
78+
79+
accelerate launch train_controlnet_sd3.py \
80+
--pretrained_model_name_or_path=$MODEL_DIR \
81+
--output_dir=$OUTPUT_DIR \
82+
--train_data_dir="fill50k" \
83+
--resolution=1024 \
84+
--learning_rate=1e-5 \
85+
--max_train_steps=15000 \
86+
--validation_image "./conditioning_image_1.png" "./conditioning_image_2.png" \
87+
--validation_prompt "red circle with blue background" "cyan circle with brown floral background" \
88+
--validation_steps=100 \
89+
--train_batch_size=1 \
90+
--gradient_accumulation_steps=4
91+
```
92+
93+
To better track our training experiments, we're using flags `validation_image`, `validation_prompt`, and `validation_steps` to allow the script to do a few validation inference runs. This allows us to qualitatively check if the training is progressing as expected.
94+
95+
Our experiments were conducted on a single 40GB A100 GPU.
96+
97+
### Inference
98+
99+
Once training is done, we can perform inference like so:
100+
101+
```python
102+
from diffusers import StableDiffusion3ControlNetPipeline, SD3ControlNetModel
103+
from diffusers.utils import load_image
104+
import torch
105+
106+
base_model_path = "stabilityai/stable-diffusion-3-medium-diffusers"
107+
controlnet_path = "sd3-controlnet-out/checkpoint-6500/controlnet"
108+
109+
controlnet = SD3ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
110+
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
111+
base_model_path, controlnet=controlnet
112+
)
113+
pipe.to("cuda", torch.float16)
114+
115+
116+
control_image = load_image("./conditioning_image_1.png").resize((1024, 1024))
117+
prompt = "pale golden rod circle with old lace background"
118+
119+
# generate image
120+
generator = torch.manual_seed(0)
121+
image = pipe(
122+
prompt, num_inference_steps=20, generator=generator, control_image=control_image
123+
).images[0]
124+
image.save("./output.png")
125+
```
126+
127+
## Notes
128+
129+
### GPU usage
130+
131+
SD3 is a large model and requires a lot of GPU memory.
132+
We recommend using one GPU with at least 80GB of memory.
133+
Make sure to use the right GPU when configuring the [accelerator](https://huggingface.co/docs/transformers/en/accelerate).
134+
135+
136+
## Example results
137+
138+
#### After 500 steps with batch size 8
139+
140+
| | |
141+
|-------------------|:-------------------------:|
142+
|| pale golden rod circle with old lace background |
143+
![conditioning image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png) | ![pale golden rod circle with old lace background](https://huggingface.co/datasets/DavyMorgan/sd3-controlnet-results/resolve/main/step-500.png) |
144+
145+
146+
#### After 6500 steps with batch size 8:
147+
148+
| | |
149+
|-------------------|:-------------------------:|
150+
|| pale golden rod circle with old lace background |
151+
![conditioning image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png) | ![pale golden rod circle with old lace background](https://huggingface.co/datasets/DavyMorgan/sd3-controlnet-results/resolve/main/step-6500.png) |
152+
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
accelerate>=0.16.0
2+
torchvision
3+
transformers>=4.25.1
4+
ftfy
5+
tensorboard
6+
Jinja2
7+
datasets
8+
wandb

examples/controlnet/test_controlnet.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,24 @@ def test_controlnet_sdxl(self):
115115
run_command(self._launch_args + test_args)
116116

117117
self.assertTrue(os.path.isfile(os.path.join(tmpdir, "diffusion_pytorch_model.safetensors")))
118+
119+
120+
class ControlNetSD3(ExamplesTestsAccelerate):
121+
def test_controlnet_sd3(self):
122+
with tempfile.TemporaryDirectory() as tmpdir:
123+
test_args = f"""
124+
examples/controlnet/train_controlnet_sd3.py
125+
--pretrained_model_name_or_path=DavyMorgan/tiny-sd3-pipe
126+
--dataset_name=hf-internal-testing/fill10
127+
--output_dir={tmpdir}
128+
--resolution=64
129+
--train_batch_size=1
130+
--gradient_accumulation_steps=1
131+
--controlnet_model_name_or_path=DavyMorgan/tiny-controlnet-sd3
132+
--max_train_steps=4
133+
--checkpointing_steps=2
134+
""".split()
135+
136+
run_command(self._launch_args + test_args)
137+
138+
self.assertTrue(os.path.isfile(os.path.join(tmpdir, "diffusion_pytorch_model.safetensors")))

0 commit comments

Comments
 (0)