Skip to content

Commit bc8a08f

Browse files
authored
[docs] Loader docs (huggingface#5473)
* first draft * make fix-copies * add peft section * manual fix * make fix-copies again * manually revert changes to other files
1 parent dbce14d commit bc8a08f

File tree

2 files changed

+302
-0
lines changed

2 files changed

+302
-0
lines changed

docs/source/en/_toctree.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
title: Load safetensors
3535
- local: using-diffusers/other-formats
3636
title: Load different Stable Diffusion formats
37+
- local: using-diffusers/loading_adapters
38+
title: Load adapters
3739
- local: using-diffusers/push_to_hub
3840
title: Push files to the Hub
3941
title: Loading & Hub
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# Load adapters
14+
15+
[[open-in-colab]]
16+
17+
There are several [training](../training/overview) techniques for personalizing diffusion models to generate images of a specific subject or images in certain styles. Each of these training methods produce a different type of adapter. Some of the adapters generate an entirely new model, while other adapters only modify a smaller set of embeddings or weights. This means the loading process for each adapter is also different.
18+
19+
This guide will show you how to load DreamBooth, textual inversion, and LoRA weights.
20+
21+
<Tip>
22+
23+
Feel free to browse the [Stable Diffusion Conceptualizer](https://huggingface.co/spaces/sd-concepts-library/stable-diffusion-conceptualizer), [LoRA the Explorer](multimodalart/LoraTheExplorer), and the [Diffusers Models Gallery](https://huggingface.co/spaces/huggingface-projects/diffusers-gallery) for checkpoints and embeddings to use.
24+
25+
</Tip>
26+
27+
## DreamBooth
28+
29+
[DreamBooth](https://dreambooth.github.io/) finetunes an *entire diffusion model* on just several images of a subject to generate images of that subject in new styles and settings. This method works by using a special word in the prompt that the model learns to associate with the subject image. Of all the training methods, DreamBooth produces the largest file size (usually a few GBs) because it is a full checkpoint model.
30+
31+
Let's load the [herge_style](https://huggingface.co/sd-dreambooth-library/herge-style) checkpoint, which is trained on just 10 images drawn by Hergé, to generate images in that style. For it to work, you need to include the special word `herge_style` in your prompt to trigger the checkpoint:
32+
33+
```py
34+
from diffusers import AutoPipelineForText2Image
35+
import torch
36+
37+
pipeline = AutoPipelineForText2Image.from_pretrained("sd-dreambooth-library/herge-style", torch_dtype=torch.float16).to("cuda")
38+
prompt = "A cute herge_style brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
39+
image = pipeline(prompt).images[0]
40+
```
41+
42+
<div class="flex justify-center">
43+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_dreambooth.png" />
44+
</div>
45+
46+
## Textual inversion
47+
48+
[Textual inversion](https://textual-inversion.github.io/) is very similar to DreamBooth and it can also personalize a diffusion model to generate certain concepts (styles, objects) from just a few images. This method works by training and finding new embeddings that represent the images you provide with a special word in the prompt. As a result, the diffusion model weights stays the same and the training process produces a relatively tiny (a few KBs) file.
49+
50+
Because textual inversion creates embeddings, it cannot be used on its own like DreamBooth and requires another model.
51+
52+
```py
53+
from diffusers import AutoPipelineForText2Image
54+
import torch
55+
56+
pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
57+
```
58+
59+
Now you can load the textual inversion embeddings with the [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] method and generate some images. Let's load the [sd-concepts-library/gta5-artwork](https://huggingface.co/sd-concepts-library/gta5-artwork) embeddings and you'll need to include the special word `<gta5-artwork>` in your prompt to trigger it:
60+
61+
```py
62+
pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
63+
prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration, <gta5-artwork> style"
64+
image = pipeline(prompt).images[0]
65+
```
66+
67+
<div class="flex justify-center">
68+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_txt_embed.png" />
69+
</div>
70+
71+
Textual inversion can also be trained on undesirable things to create *negative embeddings* to discourage a model from generating images with those undesirable things like blurry images or extra fingers on a hand. This can be a easy way to quickly improve your prompt. You'll also load the embeddings with [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`], but this time, you'll need two more parameters:
72+
73+
- `weight_name`: specifies the weight file to load if the file was saved in the 🤗 Diffusers format with a specific name or if the file is stored in the A1111 format
74+
- `token`: specifies the special word to use in the prompt to trigger the embeddings
75+
76+
Let's load the [sayakpaul/EasyNegative-test](https://huggingface.co/sayakpaul/EasyNegative-test) embeddings:
77+
78+
```py
79+
pipeline.load_textual_inversion(
80+
"sayakpaul/EasyNegative-test", weight_name="EasyNegative.safetensors", token="EasyNegative"
81+
)
82+
```
83+
84+
Now you can use the `token` to generate an image with the negative embeddings:
85+
86+
```py
87+
prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration, EasyNegative"
88+
negative_prompt = "EasyNegative"
89+
90+
image = pipeline(prompt, negative_prompt=negative_prompt, num_inference_steps=50).images[0]
91+
```
92+
93+
<div class="flex justify-center">
94+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_neg_embed.png" />
95+
</div>
96+
97+
## LoRA
98+
99+
[Low-Rank Adaptation (LoRA)](https://huggingface.co/papers/2106.09685) is a popular training technique because it is fast and generates smaller file sizes (a couple hundred MBs). Like the other methods in this guide, LoRA can train a model to learn new styles from just a few images. It works by inserting new weights into the diffusion model and then only the new weights are trained instead of the entire model. This makes LoRAs faster to train and easier to store.
100+
101+
<Tip>
102+
103+
LoRA is a very general training technique that can be used with other training methods. For example, it is common to train a model with DreamBooth and LoRA.
104+
105+
</Tip>
106+
107+
LoRAs also need to be used with another model:
108+
109+
```py
110+
from diffusers import AutoPipelineForText2Image
111+
import torch
112+
113+
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
114+
```
115+
116+
Then use the [`~loaders.LoraLoaderMixin.load_lora_weights`] method to load the [ostris/super-cereal-sdxl-lora](https://huggingface.co/ostris/super-cereal-sdxl-lora) weights and specify the weights filename from the repository:
117+
118+
```py
119+
pipeline.load_lora_weights("ostris/super-cereal-sdxl-lora", weight_name="cereal_box_sdxl_v1.safetensors")
120+
prompt = "bears, pizza bites"
121+
image = pipeline(prompt).images[0]
122+
```
123+
124+
<div class="flex justify-center">
125+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_lora.png" />
126+
</div>
127+
128+
The [`~loaders.LoraLoaderMixin.load_lora_weights`] method loads LoRA weights into both the UNet and text encoder. It is the preferred way for loading LoRAs because it can handle cases where:
129+
130+
- the LoRA weights don't have separate identifiers for the UNet and text encoder
131+
- the LoRA weights have separate identifiers for the UNet and text encoder
132+
133+
But if you only need to load LoRA weights into the UNet, then you can use the [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method. Let's load the [jbilcke-hf/sdxl-cinematic-1](https://huggingface.co/jbilcke-hf/sdxl-cinematic-1) LoRA:
134+
135+
```py
136+
from diffusers import AutoPipelineForText2Image
137+
import torch
138+
139+
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
140+
pipeline.unet.load_attn_procs("jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors")
141+
142+
# use cnmt in the prompt to trigger the LoRA
143+
prompt = "A cute cnmt eating a slice of pizza, stunning color scheme, masterpiece, illustration"
144+
image = pipeline(prompt).images[0]
145+
```
146+
147+
<div class="flex justify-center">
148+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_attn_proc.png" />
149+
</div>
150+
151+
<Tip>
152+
153+
For both [`~loaders.LoraLoaderMixin.load_lora_weights`] and [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`], you can pass the `cross_attention_kwargs={"scale": 0.5}` parameter to adjust how much of the LoRA weights to use. A value of `0` is the same as only using the base model weights, and a value of `1` is equivalent to using the fully finetuned LoRA.
154+
155+
</Tip>
156+
157+
To unload the LoRA weights, use the [`~loaders.LoraLoaderMixin.unload_lora_weights`] method to discard the LoRA weights and restore the model to its original weights:
158+
159+
```py
160+
pipeline.unload_lora_weights()
161+
```
162+
163+
### Load multiple LoRAs
164+
165+
It can be fun to use multiple LoRAs together to create something entirely new and unique. The [`~loaders.LoraLoaderMixin.fuse_lora`] method allows you to fuse the LoRA weights with the original weights of the underlying model.
166+
167+
<Tip>
168+
169+
Fusing the weights can lead to a speedup in inference latency because you don't need to separately load the base model and LoRA! You can save your fused pipeline with [`~DiffusionPipeline.save_pretrained`] to avoid loading and fusing the weights every time you want to use the model.
170+
171+
</Tip>
172+
173+
Load an initial model:
174+
175+
```py
176+
from diffusers import StableDiffusionXLPipeline, AutoencoderKL
177+
import torch
178+
179+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
180+
pipeline = StableDiffusionXLPipeline.from_pretrained(
181+
"stabilityai/stable-diffusion-xl-base-1.0",
182+
vae=vae,
183+
torch_dtype=torch.float16,
184+
).to("cuda")
185+
```
186+
187+
Then load the LoRA checkpoint and fuse it with the original weights. The `lora_scale` parameter controls how much to scale the output by with the LoRA weights. It is important to make the `lora_scale` adjustments in the [`~loaders.LoraLoaderMixin.fuse_lora`] method because it won't work if you try to pass `scale` to the `cross_attention_kwargs` in the pipeline.
188+
189+
If you need to reset the original model weights for any reason (use a different `lora_scale`), you should use the [`~loaders.LoraLoaderMixin.unfuse_lora`] method.
190+
191+
```py
192+
pipeline.load_lora_weights("ostris/ikea-instructions-lora-sdxl")
193+
pipeline.fuse_lora(lora_scale=0.7)
194+
195+
# to unfuse the LoRA weights
196+
pipeline.unfuse_lora()
197+
```
198+
199+
Then fuse this pipeline with the next set of LoRA weights:
200+
201+
```py
202+
pipeline.load_lora_weights("ostris/super-cereal-sdxl-lora")
203+
pipeline.fuse_lora(lora_scale=0.7)
204+
```
205+
206+
<Tip warning={true}>
207+
208+
You can't unfuse multiple LoRA checkpoints so if you need to reset the model to its original weights, you'll need to reload it.
209+
210+
</Tip>
211+
212+
Now you can generate an image that uses the weights from both LoRAs:
213+
214+
```py
215+
prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
216+
image = pipeline(prompt).images[0]
217+
```
218+
219+
### 🤗 PEFT
220+
221+
<Tip>
222+
223+
Read the [Inference with 🤗 PEFT](../tutorials/using_peft_for_inference) tutorial to learn more its integration with 🤗 Diffusers and how you can easily work with and juggle multiple adapters.
224+
225+
</Tip>
226+
227+
Another way you can load and use multiple LoRAs is to specify the `adapter_name` parameter in [`~loaders.LoraLoaderMixin.load_lora_weights`]. This method takes advantage of the 🤗 PEFT integration. For example, load and name both LoRA weights:
228+
229+
```py
230+
from diffusers import DiffusionPipeline
231+
import torch
232+
233+
pipeline = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
234+
pipeline.load_lora_weights("ostris/ikea-instructions-lora-sdxl", weight_name="ikea_instructions_xl_v1_5.safetensors", adapter_name="ikea")
235+
pipeline.load_lora_weights("ostris/super-cereal-sdxl-lora", weight_name="cereal_box_sdxl_v1.safetensors", adapter_name="cereal")
236+
```
237+
238+
Now use the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] to activate both LoRAs, and you can configure how much weight each LoRA should have on the output:
239+
240+
```py
241+
pipeline.set_adapters(["ikea", "cereal"], adapter_weights=[0.7, 0.5])
242+
```
243+
244+
Then generate an image:
245+
246+
```py
247+
prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
248+
image = pipeline(prompt, num_inference_steps=30, cross_attention_kwargs={"scale": 1.0}).images[0]
249+
```
250+
251+
### Kohya and TheLastBen
252+
253+
Other popular LoRA trainers from the community include those by [Kohya](https://github.com/kohya-ss/sd-scripts/) and [TheLastBen](https://github.com/TheLastBen/fast-stable-diffusion). These trainers create different LoRA checkpoints than those trained by 🤗 Diffusers, but they can still be loaded in the same way.
254+
255+
Let's download the [Blueprintify SD XL 1.0](https://civitai.com/models/150986/blueprintify-sd-xl-10) checkpoint from [Civitai](https://civitai.com/):
256+
257+
```py
258+
!wget https://civitai.com/api/download/models/168776 -O blueprintify-sd-xl-10.safetensors
259+
```
260+
261+
Load the LoRA checkpoint with the [`~loaders.LoraLoaderMixin.load_lora_weights`] method, and specify the filename in the `weight_name` parameter:
262+
263+
```py
264+
from diffusers import AutoPipelineForText2Image
265+
import torch
266+
267+
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0").to("cuda")
268+
pipeline.load_lora_weights("path/to/weights", weight_name="blueprintify-sd-xl-10.safetensors")
269+
```
270+
271+
Generate an image:
272+
273+
```py
274+
# use bl3uprint in the prompt to trigger the LoRA
275+
prompt = "bl3uprint, a highly detailed blueprint of the eiffel tower, explaining how to build all parts, many txt, blueprint grid backdrop"
276+
image = pipeline(prompt).images[0]
277+
```
278+
279+
<Tip warning={true}>
280+
281+
Some limitations of using Kohya LoRAs with 🤗 Diffusers include:
282+
283+
- Images may not look like those generated by UIs - like ComfyUI - for multiple reasons which are explained [here](https://github.com/huggingface/diffusers/pull/4287/#issuecomment-1655110736).
284+
- [LyCORIS checkpoints](https://github.com/KohakuBlueleaf/LyCORIS) aren't fully supported. The [`~loaders.LoraLoaderMixin.load_lora_weights`] method loads LyCORIS checkpoints with LoRA and LoCon modules, but Hada and LoKR are not supported.
285+
286+
</Tip>
287+
288+
Loading a checkpoint from TheLastBen is very similar. For example, to load the [TheLastBen/William_Eggleston_Style_SDXL](https://huggingface.co/TheLastBen/William_Eggleston_Style_SDXL) checkpoint:
289+
290+
```py
291+
from diffusers import AutoPipelineForText2Image
292+
import torch
293+
294+
pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16).to("cuda")
295+
pipeline.load_lora_weights("TheLastBen/William_Eggleston_Style_SDXL", weight_name="wegg.safetensors")
296+
297+
# use by william eggleston in the prompt to trigger the LoRA
298+
prompt = "a house by william eggleston, sunrays, beautiful, sunlight, sunrays, beautiful"
299+
image = pipeline(prompt=prompt).images[0]
300+
```

0 commit comments

Comments
 (0)