Textual Inversion
Last updated
Last updated
Textual Inversion is a technique for capturing novel concepts from a small number of example images. While the technique was originally demonstrated with a latent diffusion model, it has since been applied to other model variants like Stable Diffusion. The learned concepts can be used to better control the images generated from text-to-image pipelines. It learns new “words” in the text encoder’s embedding space, which are used within text prompts for personalized image generation.
By using just 3-5 images you can teach new concepts to a model such as Stable Diffusion for personalized image generation (image source).
This guide will show you how to train a runwayml/stable-diffusion-v1-5
model with Textual Inversion. All the training scripts for Textual Inversion used in this guide can be found here if you’re interested in taking a closer look at how things work under the hood.
There is a community-created collection of trained Textual Inversion models in the Stable Diffusion Textual Inversion Concepts Library which are readily available for inference. Over time, this’ll hopefully grow into a useful resource as more concepts are added!
Before you begin, make sure you install the library’s training dependencies:
Copied
After all the dependencies have been set up, initialize a 🌍 Accelerate environment with:
Copied
To setup a default 🌍 Accelerate environment without choosing any configurations:
Copied
Or if your environment doesn’t support an interactive shell like a notebook, you can use:
Copied
Finally, you try and install xFormers to reduce your memory footprint with xFormers memory-efficient attention. Once you have xFormers installed, add the --enable_xformers_memory_efficient_attention
argument to the training script. xFormers is not supported for Flax.
If you want to store your model on the Hub, add the following argument to the training script:
Copied
It is often a good idea to regularly save checkpoints of your model during training. This way, you can resume training from a saved checkpoint if your training is interrupted for any reason. To save a checkpoint, pass the following argument to the training script to save the full training state in a subfolder in output_dir
every 500 steps:
Copied
To resume training from a saved checkpoint, pass the following argument to the training script and the specific checkpoint you’d like to resume from:
Copied
For your training dataset, download these images of a cat toy and store them in a directory. To use your own dataset, take a look at the Create a dataset for training guide.
Copied
Specify the MODEL_NAME
environment variable (either a Hub model repository id or a path to the directory containing the model weights) and pass it to the pretrained_model_name_or_path
argument, and the DATA_DIR
environment variable to the path of the directory containing the images.
Now you can launch the training script. The script creates and saves the following files to your repository: learned_embeds.bin
, token_identifier.txt
, and type_of_concept.txt
.
💡 A full training run takes ~1 hour on one V100 GPU. While you’re waiting for the training to complete, feel free to check out how Textual Inversion works in the section below if you’re curious!
PytorchHide Pytorch contentCopied
💡 If you want to increase the trainable capacity, you can associate your placeholder token, e.g. <cat-toy>
to multiple embedding vectors. This can help the model to better capture the style of more (complex) images. To enable training multiple embedding vectors, simply pass:
Copied
JAXHide JAX content
If you have access to TPUs, try out the Flax training script to train even faster (this’ll also work for GPUs). With the same configuration settings, the Flax training script should be at least 70% faster than the PyTorch training script! ⚡️
Before you begin, make sure you install the Flax specific dependencies:
Copied
Specify the MODEL_NAME
environment variable (either a Hub model repository id or a path to the directory containing the model weights) and pass it to the pretrained_model_name_or_path
argument.
Then you can launch the training script:
Copied
If you’re interested in following along with your model training progress, you can save the generated images from the training process. Add the following arguments to the training script to enable intermediate logging:
validation_prompt
, the prompt used to generate samples (this is set to None
by default and intermediate logging is disabled)
num_validation_images
, the number of sample images to generate
validation_steps
, the number of steps before generating num_validation_images
from the validation_prompt
Copied
Once you have trained a model, you can use it for inference with the StableDiffusionPipeline.
The textual inversion script will by default only save the textual inversion embedding vector(s) that have been added to the text encoder embedding matrix and consequently been trained.
PytorchHide Pytorch content
💡 The community has created a large library of different textual inversion embedding vectors, called sd-concepts-library. Instead of training textual inversion embeddings from scratch you can also see whether a fitting textual inversion embedding has already been added to the libary.
To load the textual inversion embeddings you first need to load the base model that was used when training your textual inversion embedding vectors. Here we assume that runwayml/stable-diffusion-v1-5
was used as a base model so we load it first:
Copied
Next, we need to load the textual inversion embedding vector which can be done via the TextualInversionLoaderMixin.load_textual_inversion
function. Here we’ll load the embeddings of the ”” example from before.
Copied
Now we can run the pipeline making sure that the placeholder token <cat-toy>
is used in our prompt.
Copied
The function TextualInversionLoaderMixin.load_textual_inversion
can not only load textual embedding vectors saved in Diffusers’ format, but also embedding vectors saved in Automatic1111 format. To do so, you can first download an embedding vector from civitAI and then load it locally:
Copied
JAXHide JAX content
Currently there is no load_textual_inversion
function for Flax so one has to make sure the textual inversion embedding vector is saved as part of the model after training.
The model can then be run just like any other Flax model:
Copied
Architecture overview from the Textual Inversion blog post.
Usually, text prompts are tokenized into an embedding before being passed to a model, which is often a transformer. Textual Inversion does something similar, but it learns a new token embedding, v*
, from a special token S*
in the diagram above. The model output is used to condition the diffusion model, which helps the diffusion model understand the prompt and new concepts from just a few example images.
To do this, Textual Inversion uses a generator model and noisy versions of the training images. The generator tries to predict less noisy versions of the images, and the token embedding v*
is optimized based on how well the generator does. If the token embedding successfully captures the new concept, it gives more useful information to the diffusion model and helps create clearer images with less noise. This optimization process typically occurs after several thousand steps of exposure to a variety of prompt and image variants.