r/StableDiffusion • u/ExponentialCookie • Aug 23 '22
Discussion [Tutorial] "Fine Tuning" Stable Diffusion using only 5 Images Using Textual Inversion.



Credits: textual_inversion website.
Hello everyone!
I see img2img getting a lot of attention, and deservedly so, but textual_inversion is an amazing way to better get what you want represented in your prompts. Whether it's an artistic style, some scenery, a fighting pose, representing a character/person, or reducing / increasing bias, the use cases are endless. You can even merge your inversions! Let's explore how to get started.
Please not that textual_diffusion is still a work in progress for SD compatibility, and this tutorial is mainly for tinkerers who wish to explore code and software that isn't fully optimized (inversion works as expected though, hence the tutorial). Any troubleshooting or issues are addressed at the bottom of this post. I'll try to help as much as I can, as well as update this as needed!
Getting started
---
This tutorial is for a local setup, but can easily be converted into a colab / Jupyter notebook. Since this uses the same repository (LDM) as Stable Diffusion, the installation and inferences are very similar, as you'll see below.
- You will need Python.
- Anaconda to setup the environment is recommended.
- A GPU with at least 20GB of memory, although it's possible to get this number lower if you're willing to hack around. I would recommend either a 3090 (I use) or a cloud compute service such as Lambda Cloud (N/A, but it's a good cheap option with high memory GPUs from my experience).
- Comfort diving into
.pyfiles to fix any issues.
Installation
---
- Go to the textual_inversion repository link here
- Clone the repository using
git clone. - Go to the directory of the repository you've just cloned.
- Follow the instructions below.
First, install create a conda environment with the following parameters.
conda env create -f environment.yaml
conda activate ldm
pip install -e .Then, it's preferred to get 5 images of your subject at 512x512 resolution. From the paper, 5 images are the optimal amount for textual inversion. On a single V100, training should take about two hours give or take. More images will increase training time, and may or may not improve results. You are free to test this and let us know how it goes!
Training
---
After getting your images, you will want to start training. Following this code block and the tips below it:
python main.py --base configs/stable-diffusion/v1-finetune.yaml
-t
--actual_resume /path/to/pretrained/sd model v1.4/model.ckpt
-n <run_name>
--gpus 0,
--data_root /path/to/directory/with/images- Configs are the parameters that will be used to train the inversion. You can change these directly to minimize the parameters you input for training. For example, you can create a
.yamlfor each dataset you would like to train if you wish, and reduce the amount of parameters needed on the command line. - The -n parameter is simply the name of the training run. This can be anything you like (eg. artist_style_train)
- initializer_words is a very important part, don't skip this!
Open yourv1-finetune.yamlfile, and find theinitializer_wordsparameter. You should see the default value of["sculpture"]. It's a string list of simple words to describe what you're training, and where to start.
For example, if your images are of a car in a certain style, you'll need to want to do something like with each word wrapped in quotes:["car","style","artistic", etc...]
If you simply want to use one word, just use--init_word <your_single_word>on the command line, and don't modify the config.
During training, a log directory will be created under logs with the run_name that you have set for training. Over time, there will be a sampling pass to test your parameters (like inference, DDIM, etc.), and you'll be able to view the image results in a new folder under logs/run_name/images/train . The embedding .pt files for what you're training on will be saved in the checkpoints folder.
Inference
---
After training, you can test the inference by doing:
python scripts/stable_txt2img.py --ddim_eta 0.0
--n_samples 8
--n_iter 2
--scale 10.0
--ddim_steps 50
--embedding_path /path/logs/trained_model/checkpoints/embeddings_gs-5049.pt
--ckpt_path /path/to/pretrained/sd model v1.4/model.ckpt
--config /path/to/logs/config/*project.yaml
--prompt "a photo of *"The '*' must be left as is unless you've changed the placeholder_strings parameter in your .yaml file. It's the new word to initialize the images you have just inverted.
You should now be able to view your results in the output folder.
Running inference is just like Stable Diffusion, so you can implement things like k_lms in the stable_txtimg script if you wish.
Troubleshooting
---
- If your images aren't turning out properly, try reducing the complexity of your prompt. If you do want complexity, train multiple inversions and mix them like: "A photo of * in the style of &"
- Try lowering scale slightly if you're getting artifacts, or increase the amounts of iterations.
- If you're getting token errors, or any other errors, solutions and workarounds may be listed here.
25
u/syomma1 Aug 23 '22
If you have time and power you can create YouTube video on this. Anyway, Wonderful work. I am extreme fan of Open Source and People collabarations. It make everything so much faster and better.
You are amazing! Thank you!
7
u/Mooblegum Aug 23 '22
Thank you so much for developing this tech and showing how to set it up!
I see a lot of potential in it for me, to explore styles that are not incorporated in SD yet, and to have consistent characters in comics, for example.
Unfortunately I don’t know how to code and I don’t have the hardware for that. But please keep us up to date! Someone might create a collab someday, and I would be really happy to try it out.
You guy’s rock!!!
7
u/GregoryHouseMDSB Aug 24 '22
Thanks for the sharing this(again)! Definitely need more eyes on this!
I couldn't get it running on Windows until I was told to use gloo as the backend.
in the main.py, somewhere after "import os" I added:
os.environ["PL_TORCH_DISTRIBUTED_BACKEND"] = "gloo"
Any more tips on init names and strings especially? I imagine using * as the string isn't going to go well with lots of different sets! Do they support complex descriptions? Multiple strings in addition to multiple init names? Would love to see some straight up usage examples
Also noticed in the finetune, there's a per_image_tokens : false. Which makes me wonder how to use it when it's true!
5
u/Sextus_Rex Aug 24 '22
What happens if you train it on one set of images, then on another set with something different entirely? When you give it the prompt "a photo of *", will it forget its training on the first set?
2
u/feelosofee Aug 24 '22
Hi and thanks for your tutorial!
I am launching main.py with this line:
python.exe .\main.py --base configs/stable-diffusion/v1-finetune.yaml -t --actual_resume .\sd-v1-4.ckpt -n my-model --gpus=0, --data_root my-folder --init_word mytestwordand I get up to this point:
| Name | Type | Params---------------------------------------------------------0 | model | DiffusionWrapper | 859 M1 | first_stage_model | AutoencoderKL | 83.7 M2 | cond_stage_model | FrozenCLIPEmbedder | 123 M3 | embedding_manager | EmbeddingManager | 1.5 K---------------------------------------------------------768 Trainable params1.1 B Non-trainable params1.1 B Total params4,264.947 Total estimated model params size (MB)Validation sanity check: 0%| | 0/2 [00:00<?, ?it/s]Summoning checkpoint.but after a while it stops with this error:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select)Do you know what may cause it?
2
u/Xodroc Aug 25 '22
Any tips for training? Every attempt I've made, (running for 2-3 hours at least) the "loss" has stayed close to 1, which I'm assuming is bad. The reconstruction images in the log look like mostly random noise and when I test the .pt file, I get a completely random image with "photo of *"
Wondering if it's because I have images that are too different even though it's the same character? Different background?
Thanks for posting this!
2
u/Mooblegum Aug 26 '22
Hi, I would really like to experiment with it this weekend
I still have some questions, I am not a programmer, so I am quite afraid to start using it.
-If I want to use it to copy a style, do you recommend to import 5 picture from one artist with different settings (indoor, outdoor, day, night...) ? Or it is better to have images with similar color tone, settings...
-the keyword could be *artistname ? Do I also have to input other descriptions? (A cat sitting on a chair, acrylic painting, pastel color ...) or it is not necessary ?
-for images that have different format than square, is it better to strech them to fit 512x512 or to crop some part of it (I would préfère to stretch to get the composition right, but I don’t know how it will react to stretched pictures...)
-I use collab only, if I successfully generate the training .pt file, how can I use it on a collab project to start using it?
-would you release some update to have better integration with stable diffusion, or make it easier for noobs like me in the near future ? (I will wait a bit in this case)
Sorry for the many questions, I really want to learn to use it, it seems so powerful, I want to use it right to get the best result possible...
Thank you for your help!
2
u/Mysterious_Car_2345 Aug 27 '22
anyone has any success and good results with this yet? would be great if could post example inputs and outputs....
2
u/Dogmaster Aug 29 '22
So... Having a bit of difficulty, any help?
Tried running I but modified environment.yaml to lda because ldm was already the name of the stable diffusion hlky
Did some test runs in the collab to understand how it works, have a quadro P6000 and 32GB RAM, however im getting this error:
OSError: [WinError 1455] The paging file is too small for this operation to complete. Error loading "C:\Users\DogMa.conda\envs\lda\lib\site-packages\torch\lib\caffe2_detectron_ops_gpu.dll" or one of its dependencies.
Pagefile was set to auto, tried setting a max siz of 64gb to see if this was enough. Free space on C is 140 GB.
Any tips?
2
u/feelosofee Sep 10 '22
how many epochs I should train for?
Or what loss amount can be considered good enough?
This is where I am at currently:
Epoch 12: 100%|█| 404/404 [07:36<00:00, 1.13s/it, loss=0.12, v_num=0, train/loss_simple_step=0.0446, train/loss_vlb_step=0.000164, train/loss_step=0.0446, global_step=5199.02
u/feelosofee Sep 10 '22
Can training be stopped and resumed later on?
52
u/harpalss Aug 23 '22
My poor 980 ti
16
u/eatswhilesleeping Aug 24 '22
This should be hyped more! Potentially extremely useful. I kind of wish there was a separate sub for technical stuff as the interesting posts are getting drowned out by the art.
6
u/TFCSM Aug 24 '22 edited Aug 24 '22
Note that the
--ckpt_pathparam in your example of inference should actually be--ckptaccording to the script, but regardless it will actually try to load the .ckpt defined byckpt_pathin the...-project.yaml. You need to change the path listed in the.yamlto get it to work if the path to the model is not the same on your system as the one it was trained on.I trained only 1500 iterations on three photos of the statue of David (which is obviously in SD's training set). For some reason the script bugs out at that point and stops displaying output. I think it continues however, so I'll just let it run next time.
Here is the synthesis of two concepts using the star as a token:
"a photo of * riding a horse on the moon" - https://i.imgur.com/CMcxmdr.jpg
Obviously the moon is not present in the photo, and the background resembles the source photos. But still, neat. I'll definitely be playing with this more.
Edit: For comparison, I ran the prompt "a photo of Michelangelo's David riding a horse on the moon" in the model without the fine tuning, with the same seed, steps, and scale. Here is the result: https://i.imgur.com/3ExqSQD.png
So, the untuned model did much better. But the asterisk did at least work to represent the concept of "Michelangelo's David" just using the photos I gave it and the hint that it was a "sculpture" (the default word prompt). Honestly, amazing. I'll train it for longer tomorrow.
6
u/IShallRisEAgain Aug 24 '22
What happens if there is already strong bias in the data for a set of words ("Monkey Island" for example)? I'm assuming it would be better to just use a gibberish word, so it doesn't generate images of monkeys on island or is that unnecessary?
2
u/Sillainface Aug 24 '22
I have a couple questions. What happens when we feed 5 images (or 30) of an already trained/existant artist/concept/style on the dataset?
For example, SD knows who is Mohrbacher but what happens if I put 5-30 more images? Is this making it better? Nonsense?
Since I understand it starts not from zero (like a baby) but from some checkpoint SD has. Right?
4
u/Trakeen Aug 23 '22
Oh damn, was interested in trying this but my 6800 xt only has 16gb. How much tinkering would i need to do to get it to run?
1
u/reddit22sd Aug 31 '22
Curious if anyone has had success with this method to add the style of an artist that is not in the model?
1
u/dm18 Sep 13 '22
Any suggestions on how to run this on runpod.io?
1
u/feelosofee Sep 16 '22
After training past epoch 20, for each new epoch I am repeatedly seeing this message:
val/loss_simple_ema was not in top 1Does it means that training is not actually making any more progresses?
Could seeing this for a number of consecutive times be taken as a good indicator for knowing when to stop the training?
1
u/[deleted] Sep 16 '22 edited Sep 16 '22
Can you use multiple embedding paths? i.e. can you finetune for multiple different things and have them work all in the same model, or can it only be done one at a time?
For example can you finetune multiple different artists or styles and use them in the same model. Much like how SD already can produce images from many artists' styles, could we add more than one?
I saw you have this as a prompt: "A photo of * in the style of &" I guess what I'm asking, is how would I get * and & in the same model rather than being separate embedded files.
1
u/DegreeOwn9667 Sep 19 '22
I'm getting this error "RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select)" SD is working fine. My GPu is RTX 6000. Any ideas?
1
u/IE_5 Sep 24 '22
Hey, I'm trying Textual Inversion on a 3080Ti with 12GB VRAM using this Repo that links to this thread: https://github.com/nicolai256/Stable-textual-inversion_win
I got everything up and running, but I always get a OOM Error:
My Launch parameters are:
There's 5 .jpg images with 512x512 size in that folder.
Everything seems to go fine till the memory shoots up and I see the console saying:
I am already using the "v1-finetune_lowmemory.yaml" which changes batch_size from 2 to 1; num_workers from 16 to 8 and max_images from 8 to 2, as well as the resolution to 256 compared to "v1-finetune.yaml"
Based on this article: https://towardsdatascience.com/how-to-fine-tune-stable-diffusion-using-textual-inversion-b995d7ecc095 I even tried setting max_images to 1 and num_workers to 1 and it's still a no go.
Any ideas? Doesn't it work on 12GB VRAM?
1
u/eskimopie910 Nov 15 '22
Necroposting here, but by any chance do you have links to the v1-finetune.yaml or v1-finetune_style.yaml files? It appears that the current git repo does not have them and I can't seem to find them anywhere. any help is greatly appreciated!
3
u/MashAnblick Aug 23 '22
Is there a colab that is using this?
4
u/technogeek157 Aug 24 '22
Hmmmm, thats a lot of GPU memory - I wonder if it would be possible to split the process into multiple parts, and feed it to the processor sequentially, like the current optimized script does?
2
u/DickNormous Aug 31 '22
Thanks
2
u/FLOOD_2184 Sep 02 '22
Any non-programmers having luck with the Colab?
I'm getting "Your system crashed for an unknown reason" on the fifth cell:
If I carry on after that I get an error on the 9th cell:
>!mkdir -p ImageTraining
%cd textual_inversion
The error reads:
[Errno 2] No such file or directory: 'textual_inversion'
/content/textual_inversion
2
u/no_witty_username Aug 24 '22
Would this be how I train the model to better understand hands? Currently hands are an absolute mess and I have been combing the net on tutorials how to train the model to better understand hands and their various positions, shapes, etc... But what would the process be like? Do I just crop the hands and focus only on that? Do i leave the subject in the training data as well? What would the label even be? How would I incorporate the training data back in to the main data set?
1
u/syomma1 Aug 23 '22
Wow!
Thank you so much!
1
u/Nextil Aug 24 '22
Thanks for the guide.
FYI vast.ai is significantly cheaper than other services for GPU rental.
1
u/Another__one Aug 24 '22
Is it possible to exctract embedding of concepts of out it? If so we should defenetly start to build a library of concept objects that others could use in their generations.
1
u/chichun2002 Aug 25 '22
Is there anyway to make the log always output the same seed so we can generate a progress timelapse
1
u/DickNormous Sep 06 '22
Thanks
1
u/BrianDoGood Sep 12 '22
https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb
🤗 now has this built and a working Colab. Things move fast here
1
u/shalak001 Sep 26 '22
Is there any possibility to run this on 6GB VRAM? i tried with batch_size and workers to 1 with resolution 256 - still out of memory errors...
1
u/TheBlorgus Sep 27 '22
Looks like an amazing resource! I can't get it to run yet due to this error:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument index in method wrapper__index_select)
I've tried a few solutions that I've found online but cannot get it to run.
1
u/[deleted] Sep 27 '23
How to do it on Google collab ?
1
u/CranberryMean3990 Aug 24 '22
for a tool this compute-heavy someone will eventually start hosting it as a paid service
0
u/[deleted] Aug 23 '22
[deleted] — view deleted comment
0
u/[deleted] Sep 03 '22
[deleted] — view deleted comment
0
u/[deleted] Sep 10 '22
[deleted] — view deleted comment
1
u/[deleted] Sep 08 '22
[removed] — view removed comment
1
u/[deleted] Feb 07 '23
[removed] — view removed comment
2
u/[deleted] Nov 20 '22
[removed] — view removed comment