diff --git a/README.md b/README.md index 8d108733ea7..277918f7432 100644 --- a/README.md +++ b/README.md @@ -5,13 +5,13 @@ text-to-image generator. The original has been improved in several ways: ## Interactive command-line interface similar to the Discord bot -The *dream.py* script, located in scripts/dream.py, +The _dream.py_ script, located in scripts/dream.py, provides an interactive interface to image generation similar to the "dream mothership" bot that Stable AI provided on its Discord server. Unlike the txt2img.py and img2img.py scripts provided in the original CompViz/stable-diffusion source code repository, the time-consuming initialization of the AI model -initialization only happens once. After that image generation +initialization only happens once. After that image generation from the command-line interface is very fast. The script uses the readline library to allow for in-line editing, @@ -25,7 +25,7 @@ The script is confirmed to work on Linux and Windows systems. It should work on MacOSX as well, but this is not confirmed. Note that this script runs from the command-line (CMD or Terminal window), and does not have a GUI. -~~~~ +``` (ldm) ~/stable-diffusion$ python3 ./scripts/dream.py * Initializing, be patient... Loading model from models/ldm/text2img-large/model.ckpt @@ -47,13 +47,13 @@ dream> q 00009.png: "ashley judd riding a camel" -s150 -S 416354203 00010.png: "ashley judd riding a camel" -s150 -S 1362479620 00011.png: "there's a fly in my soup" -n6 -g -S 2685670268 -~~~~ +``` The dream> prompt's arguments are pretty much identical to those used in the Discord bot, except you don't need to type "!dream" (it doesn't hurt if you do). A significant change is that creation of individual images is now the default unless --grid (-g) is given. For backward -compatibility, the -i switch is recognized. For command-line help +compatibility, the -i switch is recognized. For command-line help type -h (or --help) at the dream> prompt. The script itself also recognizes a series of command-line switches @@ -65,12 +65,12 @@ image outputs and the location of the model weight files. This script also provides an img2img feature that lets you seed your creations with a drawing or photo. This is a really cool feature that tells stable diffusion to build the prompt on top of the image you provide, preserving -the original's basic shape and layout. To use it, provide the --init_img +the original's basic shape and layout. To use it, provide the --init_img option as shown here: -~~~~ +``` dream> "waterfall and rainbow" --init_img=./init-images/crude_drawing.png --strength=0.5 -s100 -n4 -~~~~ +``` The --init_img (-I) option gives the path to the seed picture. --strength (-f) controls how much the original will be modified, ranging from 0.0 (keep the original intact), to 1.0 (ignore the original @@ -80,86 +80,90 @@ You may also pass a -v option to generate count variants on the original passing the first generated image back into img2img the requested number of times. It generates interesting variants. -## GFPGAN Support +## GFPGAN and Real-ESRGAN Support -This script also provides the ability to invoke GFPGAN after image -generation. Doing so will enhance faces and optionally upscale the -image to a higher resolution. +The script also provides the ability to do face restoration and upscaling with the help of GFPGAN and Real-ESRGAN respectively. -To use the ability, clone the [GFPGAN -repository](https://github.com/TencentARC/GFPGAN) and follow their +To use the ability, clone the **[GFPGAN +repository](https://github.com/TencentARC/GFPGAN)** and follow their installation instructions. By default, we expect GFPGAN to be -installed in a 'GFPGAN' sibling directory. Be sure that the "ldm" +installed in a 'GFPGAN' sibling directory. Be sure that the `"ldm"` conda environment is active as you install GFPGAN. -You may also want to install Real-ESRGAN, if you want to enhance -non-face regions in the image, by installing the pip Real-ESRGAN -package. +You can use the `--gfpgan_dir` argument with `dream.py` to set a custom path to your GFPGAN directory. _There are other GFPGAN related boot arguments if you wish to customize further._ + +You can install **Real-ESRGAN** by typing the following command. ``` pip install realesrgan - ``` -Users whose GPU machines are isolated from the Internet (e.g. on a -University cluster) should be aware that the first time you run -dream.py with GFPGAN turned on, it will try to download model files -from the Internet. To rectify this, you may run `python3 -scripts/preload_models.pl` after you have installed GFPGAN and all its -dependencies. +**Preloading Models** + +Users whose GPU machines are isolated from the Internet (e.g. on a University cluster) should be aware that the first time you run +dream.py with GFPGAN and Real-ESRGAN turned on, it will try to download model files from the Internet. To rectify this, you may run `python3 scripts/preload_models.py` after you have installed GFPGAN and all its dependencies. + +**Usage** + +You will now have access to two new prompt arguments. + +**Upscaling** + +`-U : ` -Now, you can run this script by adding the **--gfpgan** option. Any -issues with GFPGAN will be reported on initialization. +The upscaling prompt argument takes two values. The first value is a scaling factor and should be set to either `2` or `4` only. This will either scale the image 2x or 4x respectively using different models. + +You can set the scaling stength between `0` and `1.0` to control intensity of the of the scaling. This is handy because AI upscalers generally tend to smooth out texture details. If you wish to retain some of those for natural looking results, we recommend using values between `0.5 to 0.8`. + +**Face Restoration** + +`-G : ` + +This prompt argument controls the strength of the face restoration that is being applied. Similar to upscaling, values between `0.5 to 0.8` are recommended. + +You can use either one or both without any conflicts. In cases where you use both, the image will be first upscaled and then the face restoration process will be executed to ensure you get the highest quality facial features. + +`-save_orig` + +When you use either `-U` or `-G`, the final result you get is upscaled or face modified. If you want to save the original Stable Diffusion generation, you can use the `-save_orig` prompt argument to save the original unaffected version too. + +**Example Usage** + +``` +dream > superman dancing with a panda bear -U 2 0.6 -G 0.4 +``` -~~~~ +``` (ldm) ~/stable-diffusion$ python3 ./scripts/dream.py --gfpgan * Initializing, be patient... (...more initialization messages...) * --gfpgan was specified, loading gfpgan... (...even more initialization messages...) * Initialization done! Awaiting your command... -~~~~ - -When generating prompts, add a -G or --gfpgan_strenth option to -control the strength of the GFPGAN enhancement. 0.0 is no -enhancement, 1.0 is maximum enhancement. - -So for instance, to apply the maximum strength: -~~~~ -dream> a man wearing a pineapple hat -G 1 -~~~~ +``` This also works with img2img: -~~~ -dream> a man wearing a pineapple hat -I path/to/your/file.png -G 1 -~~~ -That's it! +``` +dream> a man wearing a pineapple hat -I path/to/your/file.png -U 2 0.5 -G 0.6 +``` -There's also a bunch of options to control GFPGAN settings when -starting the script for different configs that you can read about in -the help text. This will let you control where GFPGAN is installed, if -upsampling is enabled, the upsampler to use and the model path. +**Note** -By default, images will be upscaled by 2-fold, meaning that the old -Stable Diffusion default size of 512x512 will now be a glorious -detailed 1024x1024. The extent of upscaling is set when you run the -script, and can't be changed while it's running. However, at any time -you may specify **-G0** to turn off upscaling and facial enhancement -for that image or set of images. +GFPGAN and Real-ESRGAN are both memory intensive. In order to avoid crashes and memory overloads during the Stable Diffusion process, these effects are applied after Stable Diffusion has completed its work. -Note that loading GFPGAN consumes additional GPU memory, and will add -a few seconds to image generation. However, if can afford a 3090s with -24Gi, the results are well worth it. +In single image generations, you will see the output right away but when you are using multiple iterations, the images will first be generated and then upscaled and face restored after that process is complete. While the image generation is taking place, you will still be able to preview the base images. + +If you wish to stop during the image generation but want to upscale or face restore a particular generated image, pass it again with the same prompt and generated seed along with the `-U` and `-G` prompt arguments to perform those actions. ## Barebones Web Server As of version 1.10, this distribution comes with a bare bones web server (see screenshot). To use it, run the command: -~~~~ +``` (ldm) ~/stable-diffusion$ python3 scripts/dream_web.py -~~~~ +``` You can then connect to the server by pointing your web browser at http://localhost:9090, or to the network name or IP address of the server. @@ -176,17 +180,17 @@ you want to run, one line per prompt. The text file must be composed with a text editor (e.g. Notepad) and not a word processor. Each line should look like what you would type at the dream> prompt: -~~~~ +``` a beautiful sunny day in the park, children playing -n4 -C10 stormy weather on a mountain top, goats grazing -s100 innovative packaging for a squid's dinner -S137038382 -~~~~ +``` Then pass this file's name to dream.py when you invoke it: -~~~~ +``` (ldm) ~/stable-diffusion$ python3 scripts/dream.py --from_file="path/to/prompts.txt" -~~~~ +``` ## Shortcut for reusing seeds from the previous command @@ -202,7 +206,7 @@ Here's an example of using this to do a quick refinement. It also illustrates using the new **-G** switch to turn on upscaling and face enhancement (see previous section): -~~~~ +``` dream> a cute child playing hopscotch -G0.5 [...] outputs/img-samples/000039.3498014304.png: "a cute child playing hopscotch" -s50 -b1 -W512 -H512 -C7.5 -mk_lms -S3498014304 @@ -212,9 +216,7 @@ dream> a cute child playing hopscotch -G1.0 -s100 -S -1 reusing previous seed 3498014304 [...] outputs/img-samples/000040.3498014304.png: "a cute child playing hopscotch" -G1.0 -s100 -b1 -W512 -H512 -C7.5 -mk_lms -S3498014304 -~~~~ - - +``` ## Weighted Prompts @@ -222,9 +224,9 @@ You may weight different sections of the prompt to tell the sampler to attach di priority to them, by adding :(number) to the end of the section you wish to up- or downweight. For example consider this prompt: -~~~~ +``` tabby cat:0.25 white duck:0.75 hybrid -~~~~ +``` This will tell the sampler to invest 25% of its effort on the tabby cat aspect of the image and 75% on the white duck aspect @@ -239,7 +241,7 @@ and introducing a new vocabulary to the fixed model. To train, prepare a folder that contains images sized at 512x512 and execute the following: -~~~~ +``` # As the default backend is not available on Windows, if you're using that platform, execute SET PL_TORCH_DISTRIBUTED_BACKEND=gloo (ldm) ~/stable-diffusion$ python3 ./main.py --base ./configs/stable-diffusion/v1-finetune.yaml \ -t \ @@ -248,14 +250,14 @@ To train, prepare a folder that contains images sized at 512x512 and execute the --gpus 0, \ --data_root D:/textual-inversion/my_cat \ --init_word 'cat' -~~~~ +``` During the training process, files will be created in /logs/[project][time][project]/ where you can see the process. -conditioning* contains the training prompts +conditioning\* contains the training prompts inputs, reconstruction the input images for the training epoch -samples, samples scaled for a sample of the prompt and one with the init word provided +samples, samples scaled for a sample of the prompt and one with the init word provided On a RTX3090, the process for SD will take ~1h @1.6 iterations/sec. @@ -269,28 +271,29 @@ heat death of the universe, when you find a low loss epoch or around Once the model is trained, specify the trained .pt file when starting dream using -~~~~ +``` (ldm) ~/stable-diffusion$ python3 ./scripts/dream.py --embedding_path /path/to/embedding.pt --full_precision -~~~~ +``` Then, to utilize your subject at the dream prompt -~~~ +``` dream> "a photo of *" -~~~ +``` this also works with image2image -~~~~ + +``` dream> "waterfall and rainbow in the style of *" --init_img=./init-images/crude_drawing.png --strength=0.5 -s100 -n4 -~~~~ +``` It's also possible to train multiple tokens (modify the placeholder string in configs/stable-diffusion/v1-finetune.yaml) and combine LDM checkpoints using: -~~~~ +``` (ldm) ~/stable-diffusion$ python3 ./scripts/merge_embeddings.py \ --manager_ckpts /path/to/first/embedding.pt /path/to/second/embedding.pt [...] \ --output_path /path/to/output/embedding.pt -~~~~ +``` Credit goes to @rinongal and the repository located at https://github.com/rinongal/textual_inversion Please see the @@ -298,80 +301,81 @@ repository and associated paper for details and limitations. ## Changes - * v1.11 (26 August 2022) - * NEW FEATURE: Support upscaling and face enhancement using the GFPGAN module. (kudos to [Oceanswave](https://github.com/Oceanswave) - * You now can specify a seed of -1 to use the previous image's seed, -2 to use the seed for the image generated before that, etc. - Seed memory only extends back to the previous command, but will work on all images generated with the -n# switch. - * Variant generation support temporarily disabled pending more general solution. - * Created a feature branch named **yunsaki-morphing-dream** which adds experimental support for - iteratively modifying the prompt and its parameters. Please see[ Pull Request #86](https://github.com/lstein/stable-diffusion/pull/86) - for a synopsis of how this works. Note that when this feature is eventually added to the main branch, it will may be modified - significantly. - -* v1.10 (25 August 2022) - * A barebones but fully functional interactive web server for online generation of txt2img and img2img. - -* v1.09 (24 August 2022) - * A new -v option allows you to generate multiple variants of an initial image - in img2img mode. (kudos to [Oceanswave](https://github.com/Oceanswave). [ - See this discussion in the PR for examples and details on use](https://github.com/lstein/stable-diffusion/pull/71#issuecomment-1226700810)) - * Added ability to personalize text to image generation (kudos to [Oceanswave](https://github.com/Oceanswave) and [nicolai256](https://github.com/nicolai256)) - * Enabled all of the samplers from k_diffusion - -* v1.08 (24 August 2022) - * Escape single quotes on the dream> command before trying to parse. This avoids - parse errors. - * Removed instruction to get Python3.8 as first step in Windows install. - Anaconda3 does it for you. - * Added bounds checks for numeric arguments that could cause crashes. - * Cleaned up the copyright and license agreement files. - -* v1.07 (23 August 2022) - * Image filenames will now never fill gaps in the sequence, but will be assigned the - next higher name in the chosen directory. This ensures that the alphabetic and chronological - sort orders are the same. - -* v1.06 (23 August 2022) - * Added weighted prompt support contributed by [xraxra](https://github.com/xraxra) - * Example of using weighted prompts to tweak a demonic figure contributed by [bmaltais](https://github.com/bmaltais) - -* v1.05 (22 August 2022 - after the drop) - * Filenames now use the following formats: - 000010.95183149.png -- Two files produced by the same command (e.g. -n2), - 000010.26742632.png -- distinguished by a different seed. - - 000011.455191342.01.png -- Two files produced by the same command using - 000011.455191342.02.png -- a batch size>1 (e.g. -b2). They have the same seed. - - 000011.4160627868.grid#1-4.png -- a grid of four images (-g); the whole grid can - be regenerated with the indicated key - - * It should no longer be possible for one image to overwrite another - * You can use the "cd" and "pwd" commands at the dream> prompt to set and retrieve - the path of the output directory. - -* v1.04 (22 August 2022 - after the drop) - * Updated README to reflect installation of the released weights. - * Suppressed very noisy and inconsequential warning when loading the frozen CLIP - tokenizer. - -* v1.03 (22 August 2022) - * The original txt2img and img2img scripts from the CompViz repository have been moved into - a subfolder named "orig_scripts", to reduce confusion. - -* v1.02 (21 August 2022) - * A copy of the prompt and all of its switches and options is now stored in the corresponding +- v1.11 (26 August 2022) + - NEW FEATURE: Support upscaling and face enhancement using the GFPGAN module. (kudos to [Oceanswave](https://github.com/Oceanswave) + - You now can specify a seed of -1 to use the previous image's seed, -2 to use the seed for the image generated before that, etc. + Seed memory only extends back to the previous command, but will work on all images generated with the -n# switch. + - Variant generation support temporarily disabled pending more general solution. + - Created a feature branch named **yunsaki-morphing-dream** which adds experimental support for + iteratively modifying the prompt and its parameters. Please see[ Pull Request #86](https://github.com/lstein/stable-diffusion/pull/86) + for a synopsis of how this works. Note that when this feature is eventually added to the main branch, it will may be modified + significantly. +- v1.10 (25 August 2022) + - A barebones but fully functional interactive web server for online generation of txt2img and img2img. +- v1.09 (24 August 2022) + - A new -v option allows you to generate multiple variants of an initial image + in img2img mode. (kudos to [Oceanswave](https://github.com/Oceanswave). [ + See this discussion in the PR for examples and details on use](https://github.com/lstein/stable-diffusion/pull/71#issuecomment-1226700810)) + - Added ability to personalize text to image generation (kudos to [Oceanswave](https://github.com/Oceanswave) and [nicolai256](https://github.com/nicolai256)) + - Enabled all of the samplers from k_diffusion +- v1.08 (24 August 2022) + + - Escape single quotes on the dream> command before trying to parse. This avoids + parse errors. + - Removed instruction to get Python3.8 as first step in Windows install. + Anaconda3 does it for you. + - Added bounds checks for numeric arguments that could cause crashes. + - Cleaned up the copyright and license agreement files. + +- v1.07 (23 August 2022) + + - Image filenames will now never fill gaps in the sequence, but will be assigned the + next higher name in the chosen directory. This ensures that the alphabetic and chronological + sort orders are the same. + +- v1.06 (23 August 2022) + + - Added weighted prompt support contributed by [xraxra](https://github.com/xraxra) + - Example of using weighted prompts to tweak a demonic figure contributed by [bmaltais](https://github.com/bmaltais) + +- v1.05 (22 August 2022 - after the drop) + + - Filenames now use the following formats: + 000010.95183149.png -- Two files produced by the same command (e.g. -n2), + 000010.26742632.png -- distinguished by a different seed. + + 000011.455191342.01.png -- Two files produced by the same command using + 000011.455191342.02.png -- a batch size>1 (e.g. -b2). They have the same seed. + + 000011.4160627868.grid#1-4.png -- a grid of four images (-g); the whole grid can + be regenerated with the indicated key + + - It should no longer be possible for one image to overwrite another + - You can use the "cd" and "pwd" commands at the dream> prompt to set and retrieve + the path of the output directory. + +- v1.04 (22 August 2022 - after the drop) + + - Updated README to reflect installation of the released weights. + - Suppressed very noisy and inconsequential warning when loading the frozen CLIP + tokenizer. + +- v1.03 (22 August 2022) + - The original txt2img and img2img scripts from the CompViz repository have been moved into + a subfolder named "orig_scripts", to reduce confusion. +- v1.02 (21 August 2022) + + - A copy of the prompt and all of its switches and options is now stored in the corresponding image in a tEXt metadata field named "Dream". You can read the prompt using scripts/images2prompt.py, or an image editor that allows you to explore the full metadata. - **Please run "conda env update -f environment.yaml" to load the k_lms dependencies!!** + **Please run "conda env update -f environment.yaml" to load the k_lms dependencies!!** -* v1.01 (21 August 2022) - * added k_lms sampling. - **Please run "conda env update -f environment.yaml" to load the k_lms dependencies!!** - * use half precision arithmetic by default, resulting in faster execution and lower memory requirements +- v1.01 (21 August 2022) + - added k_lms sampling. + **Please run "conda env update -f environment.yaml" to load the k_lms dependencies!!** + - use half precision arithmetic by default, resulting in faster execution and lower memory requirements Pass argument --full_precision to dream.py to get slower but more accurate image generation - ## Installation There are separate installation walkthroughs for [Linux/Mac](#linuxmac) and [Windows](#windows). @@ -379,38 +383,48 @@ There are separate installation walkthroughs for [Linux/Mac](#linuxmac) and [Win ### Linux/Mac 1. You will need to install the following prerequisites if they are not already available. Use your -operating system's preferred installer -* Python (version 3.8.5 recommended; higher may work) -* git + operating system's preferred installer + +- Python (version 3.8.5 recommended; higher may work) +- git 2. Install the Python Anaconda environment manager using pip3. + ``` ~$ pip3 install anaconda ``` + After installing anaconda, you should log out of your system and log back in. If the installation worked, your command prompt will be prefixed by the name of the current anaconda environment, "(base)". 3. Copy the stable-diffusion source code from GitHub: + ``` (base) ~$ git clone https://github.com/lstein/stable-diffusion.git ``` + This will create stable-diffusion folder where you will follow the rest of the steps. 4. Enter the newly-created stable-diffusion folder. From this step forward make sure that you are working in the stable-diffusion directory! + ``` (base) ~$ cd stable-diffusion (base) ~/stable-diffusion$ ``` + 5. Use anaconda to copy necessary python packages, create a new python environment named "ldm", -and activate the environment. + and activate the environment. + ``` (base) ~/stable-diffusion$ conda env create -f environment.yaml (base) ~/stable-diffusion$ conda activate ldm (ldm) ~/stable-diffusion$ ``` + After these steps, your command prompt will be prefixed by "(ldm)" as shown above. 6. Load a couple of small machine-learning models required by stable diffusion: + ``` (ldm) ~/stable-diffusion$ python3 scripts/preload_models.py ``` @@ -430,13 +444,14 @@ to a page that prompts you to click the "download" link. Save the file somewhere Now run the following commands from within the stable-diffusion directory. This will create a symbolic link from the stable-diffusion model.ckpt file, to the true location of the sd-v1-4.ckpt file. - + ``` (ldm) ~/stable-diffusion$ mkdir -p models/ldm/stable-diffusion-v1 (ldm) ~/stable-diffusion$ ln -sf /path/to/sd-v1-4.ckpt models/ldm/stable-diffusion-v1/model.ckpt ``` 8. Start generating images! + ``` # for the pre-release weights use the -l or --liaon400m switch (ldm) ~/stable-diffusion$ python3 scripts/dream.py -l @@ -447,15 +462,18 @@ link from the stable-diffusion model.ckpt file, to the true location of the sd-v # for additional configuration switches and arguments, use -h or --help (ldm) ~/stable-diffusion$ python3 scripts/dream.py -h ``` -9. Subsequently, to relaunch the script, be sure to run "conda activate ldm" (step 5, second command), enter the "stable-diffusion" -directory, and then launch the dream script (step 8). If you forget to activate the ldm environment, the script will fail with multiple ModuleNotFound errors. + +9. Subsequently, to relaunch the script, be sure to run "conda activate ldm" (step 5, second command), enter the "stable-diffusion" + directory, and then launch the dream script (step 8). If you forget to activate the ldm environment, the script will fail with multiple ModuleNotFound errors. #### Updating to newer versions of the script This distribution is changing rapidly. If you used the "git clone" method (step 5) to download the stable-diffusion directory, then to update to the latest and greatest version, launch the Anaconda window, enter "stable-diffusion", and type: + ``` (ldm) ~/stable-diffusion$ git pull ``` + This will bring your local copy into sync with the remote one. ### Windows @@ -467,24 +485,30 @@ This will bring your local copy into sync with the remote one. 3. Launch Anaconda from the Windows Start menu. This will bring up a command window. Type all the remaining commands in this window. 4. Run the command: + ``` git clone https://github.com/lstein/stable-diffusion.git ``` + This will create stable-diffusion folder where you will follow the rest of the steps. 5. Enter the newly-created stable-diffusion folder. From this step forward make sure that you are working in the stable-diffusion directory! + ``` cd stable-diffusion ``` 6. Run the following two commands: + ``` conda env create -f environment.yaml (step 6a) conda activate ldm (step 6b) ``` + This will install all python requirements and activate the "ldm" environment which sets PATH and other environment variables properly. 7. Run the command: + ``` python scripts\preload_models.py ``` @@ -497,30 +521,32 @@ downloaded just-in-time) 8. Now you need to install the weights for the big stable diffusion model. For running with the released weights, you will first need to set up -an acount with Hugging Face (https://huggingface.co). Use your +an acount with Hugging Face (https://huggingface.co). Use your credentials to log in, and then point your browser at -https://huggingface.co/CompVis/stable-diffusion-v-1-4-original. You +https://huggingface.co/CompVis/stable-diffusion-v-1-4-original. You may be asked to sign a license agreement at this point. Click on "Files and versions" near the top of the page, and then click on the file named "sd-v1-4.ckpt". You'll be taken to a page that prompts you to click the "download" link. Now save the file somewhere -safe on your local machine. The weight file is >4 GB in size, so +safe on your local machine. The weight file is >4 GB in size, so downloading may take a while. Now run the following commands from **within the stable-diffusion directory** to copy the weights file to the right place: - + ``` mkdir -p models\ldm\stable-diffusion-v1 copy C:\path\to\sd-v1-4.ckpt models\ldm\stable-diffusion-v1\model.ckpt ``` + Please replace "C:\path\to\sd-v1.4.ckpt" with the correct path to wherever -you stashed this file. If you prefer not to copy or move the .ckpt file, +you stashed this file. If you prefer not to copy or move the .ckpt file, you may instead create a shortcut to it from within "models\ldm\stable-diffusion-v1\". 9. Start generating images! + ``` # for the pre-release weights python scripts\dream.py -l @@ -528,14 +554,17 @@ python scripts\dream.py -l # for the post-release weights python scripts\dream.py ``` + 10. Subsequently, to relaunch the script, first activate the Anaconda command window (step 3), enter the stable-diffusion directory (step 5, "cd \path\to\stable-diffusion"), run "conda activate ldm" (step 6b), and then launch the dream script (step 9). #### Updating to newer versions of the script This distribution is changing rapidly. If you used the "git clone" method (step 5) to download the stable-diffusion directory, then to update to the latest and greatest version, launch the Anaconda window, enter "stable-diffusion", and type: + ``` git pull ``` + This will bring your local copy into sync with the remote one. ## Simplified API for text to image generation @@ -544,22 +573,21 @@ For programmers who wish to incorporate stable-diffusion into other products, this repository includes a simplified API for text to image generation, which lets you create images from a prompt in just three lines of code: -~~~~ +``` from ldm.simplet2i import T2I model = T2I() outputs = model.txt2img("a unicorn in manhattan") -~~~~ +``` Outputs is a list of lists in the format [[filename1,seed1],[filename2,seed2]...] Please see ldm/simplet2i.py for more information. - ## Workaround for machines with limited internet connectivity My development machine is a GPU node in a high-performance compute cluster which has no connection to the internet. During model initialization, stable-diffusion tries to download the Bert tokenizer -and a file needed by the kornia library. This obviously didn't work +and a file needed by the kornia library. This obviously didn't work for me. To work around this, I have modified ldm/modules/encoders/modules.py @@ -570,7 +598,7 @@ prior to running the code on an isolated one. This assumes that both machines share a common network-mounted filesystem with a common .cache directory. -~~~~ +``` (ldm) ~/stable-diffusion$ python3 ./scripts/preload_models.py preloading bert tokenizer... Downloading: 100%|██████████████████████████████████| 28.0/28.0 [00:00<00:00, 49.3kB/s] @@ -582,7 +610,7 @@ preloading kornia requirements... Downloading: "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" to /u/lstein/.cache/torch/hub/checkpoints/checkpoint_liberty_with_aug.pth 100%|███████████████████████████████████████████████| 5.10M/5.10M [00:00<00:00, 101MB/s] ...success -~~~~ +``` If you don't need this change and want to download the files just in time, copy over the file ldm/modules/encoders/modules.py from the @@ -595,16 +623,15 @@ For support, please use this repository's GitHub Issues tracking service. Feel free to send me an email if you use and like the script. -*Original Author:* Lincoln D. Stein +_Original Author:_ Lincoln D. Stein -*Contributions by:* +_Contributions by:_ [Peter Kowalczyk](https://github.com/slix), [Henry Harrison](https://github.com/hwharrison), [xraxra](https://github.com/xraxra), [bmaltais](https://github.com/bmaltais), [Sean McLellan](https://github.com/Oceanswave), [nicolai256](https://github.com/nicolai256), [Benjamin Warner](https://github.com/warner-benjamin), [tildebyte](https://github.com/tildebyte), and [Tesseract Cat](https://github.com/TesseractCat) - Original portions of the software are Copyright (c) 2020 Lincoln D. Stein (https://github.com/lstein) #Further Reading diff --git a/TODO.txt b/TODO.txt index 32475b43ba0..40833deb648 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,6 +1,7 @@ Feature requests: -1. "gobig" mode - split image into strips, scale up, add detail using + +1. "gobig" mode - split image into strips, scale up, add detail using - DONE! img2img and reassemble with feathering. Issue #66. See https://github.com/jquesnelle/txt2imghd @@ -15,18 +16,20 @@ Feature requests: 6. Support for loading variations of the stable-diffusion weights #49 -7. Support for klms and other non-ddim samplers in img2img() #36 +7. Support for klms and other non-ddim samplers in img2img() #36 - DONE! 8. Pass a shell command to open up an image viewer on the last batch of images generated #29. +9. Change sampler and outdir after initialization #115 + Code Refactorization: -1. Move the PNG file generation code out of simplet2i and into +1. Move the PNG file generation code out of simplet2i and into - DONE! separate module. txt2img() and img2img() should return Image objects, and parent code is responsible for filenaming logic. -2. Refactor redundant code that is shared between txt2img() and +2. Refactor redundant code that is shared between txt2img() and - DONE! img2img(). -3. Experiment with replacing CompViz code with HuggingFace. +3. Experiment with replacing CompViz code with HuggingFace. - NOT WORTH IT! diff --git a/ldm/dream/pngwriter.py b/ldm/dream/pngwriter.py index 3a3f2055127..28feeef4904 100644 --- a/ldm/dream/pngwriter.py +++ b/ldm/dream/pngwriter.py @@ -23,9 +23,9 @@ def __init__(self, outdir, prompt=None, batch_size=1): self.files_written = [] os.makedirs(outdir, exist_ok=True) - def write_image(self, image, seed): + def write_image(self, image, seed, upscaled=False): self.filepath = self.unique_filename( - seed, self.filepath + seed, upscaled, self.filepath ) # will increment name in some sensible way try: prompt = f'{self.prompt} -S{seed}' @@ -34,7 +34,7 @@ def write_image(self, image, seed): print(e) self.files_written.append([self.filepath, seed]) - def unique_filename(self, seed, previouspath=None): + def unique_filename(self, seed, upscaled, previouspath=None): revision = 1 if previouspath is None: @@ -68,6 +68,8 @@ def unique_filename(self, seed, previouspath=None): if self.batch_size > 1 or os.path.exists( os.path.join(self.outdir, filename) ): + if upscaled: + break filename = f'{basecount:06}.{seed}.{series:02}.png' finished = not os.path.exists( os.path.join(self.outdir, filename) diff --git a/ldm/gfpgan/gfpgan_tools.py b/ldm/gfpgan/gfpgan_tools.py new file mode 100644 index 00000000000..d6dbee6a5ca --- /dev/null +++ b/ldm/gfpgan/gfpgan_tools.py @@ -0,0 +1,132 @@ +import torch +import warnings +import os +import sys +import numpy as np + +from PIL import Image +from scripts.dream import create_argv_parser + +arg_parser = create_argv_parser() +opt = arg_parser.parse_args() + + +def _run_gfpgan(image, strength, prompt, seed, upsampler_scale=4): + print( + f"\n* GFPGAN - Restoring Faces: {prompt} : seed:{seed}") + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=UserWarning) + + try: + model_path = os.path.join( + opt.gfpgan_dir, opt.gfpgan_model_path) + if not os.path.isfile(model_path): + raise Exception( + "GFPGAN model not found at path "+model_path) + + sys.path.append(os.path.abspath(opt.gfpgan_dir)) + from gfpgan import GFPGANer + + bg_upsampler = _load_gfpgan_bg_upsampler( + opt.gfpgan_bg_upsampler, upsampler_scale, opt.gfpgan_bg_tile) + + gfpgan = GFPGANer(model_path=model_path, upscale=upsampler_scale, + arch='clean', channel_multiplier=2, bg_upsampler=bg_upsampler) + except Exception: + import traceback + print("Error loading GFPGAN:", file=sys.stderr) + print(traceback.format_exc(), file=sys.stderr) + + if (gfpgan is None): + print(f"GFPGAN not initialized, it must be loaded via the --gfpgan argument") + return image + + image = image.convert("RGB") + + cropped_faces, restored_faces, restored_img = gfpgan.enhance(np.array( + image, dtype=np.uint8), has_aligned=False, only_center_face=False, paste_back=True) + res = Image.fromarray(restored_img) + + if strength < 1.0: + # Resize the image to the new image if the sizes have changed + if restored_img.size != image.size: + image = image.resize(res.size) + res = Image.blend(image, res, strength) + + if torch.cuda.is_available(): + torch.cuda.empty_cache() + gfpgan = None + + return res + + +def _load_gfpgan_bg_upsampler(bg_upsampler, upsampler_scale, bg_tile=400): + if bg_upsampler == 'realesrgan': + if not torch.cuda.is_available(): # CPU + warnings.warn('The unoptimized RealESRGAN is slow on CPU. We do not use it. ' + 'If you really want to use it, please modify the corresponding codes.') + bg_upsampler = None + else: + model_path = {2: 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth', + 4: 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth'} + + if upsampler_scale not in model_path: + return None + + from basicsr.archs.rrdbnet_arch import RRDBNet + from realesrgan import RealESRGANer + + if (upsampler_scale == 4): + model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, + num_block=23, num_grow_ch=32, scale=4) + if (upsampler_scale == 2): + model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, + num_block=23, num_grow_ch=32, scale=2) + + bg_upsampler = RealESRGANer( + scale=upsampler_scale, + model_path=model_path[upsampler_scale], + model=model, + tile=bg_tile, + tile_pad=10, + pre_pad=0, + half=True) # need to set False in CPU mode + else: + bg_upsampler = None + + return bg_upsampler + + +def real_esrgan_upscale(image, strength, upsampler_scale, prompt, seed): + print( + f"\n* Real-ESRGAN Upscaling: {prompt} : seed:{seed} : scale:{upsampler_scale}x") + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=UserWarning) + + try: + upsampler = _load_gfpgan_bg_upsampler( + opt.gfpgan_bg_upsampler, upsampler_scale, opt.gfpgan_bg_tile) + except Exception: + import traceback + print("Error loading Real-ESRGAN:", file=sys.stderr) + print(traceback.format_exc(), file=sys.stderr) + + output, img_mode = upsampler.enhance(np.array( + image, dtype=np.uint8), outscale=upsampler_scale, alpha_upsampler=opt.gfpgan_bg_upsampler) + + res = Image.fromarray(output) + + if strength < 1.0: + # Resize the image to the new image if the sizes have changed + if output.size != image.size: + image = image.resize(res.size) + res = Image.blend(image, res, strength) + + if torch.cuda.is_available(): + torch.cuda.empty_cache() + upsampler = None + + return res diff --git a/ldm/simplet2i.py b/ldm/simplet2i.py index ffec5fda2b4..ae5dc8ff602 100644 --- a/ldm/simplet2i.py +++ b/ldm/simplet2i.py @@ -7,7 +7,6 @@ import torch import numpy as np import random -import sys import os from omegaconf import OmegaConf from PIL import Image @@ -21,7 +20,7 @@ import transformers import time import re -import traceback + from ldm.util import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler @@ -42,7 +41,8 @@ batch_size = // how many images to generate per sampling (1) steps = // 50 seed = // current system time - sampler_name= ['ddim', 'k_dpm_2_a', 'k_dpm_2', 'k_euler_a', 'k_euler', 'k_heun', 'k_lms', 'plms'] // k_lms + sampler_name= ['ddim', 'k_dpm_2_a', 'k_dpm_2', 'k_euler_a', + 'k_euler', 'k_heun', 'k_lms', 'plms'] // k_lms grid = // false width = // image width, multiple of 64 (512) height = // image height, multiple of 64 (512) @@ -93,50 +93,49 @@ class T2I: """T2I class - Attributes - ---------- - model - config - iterations - batch_size - steps - seed - sampler_name - width - height - cfg_scale - latent_channels - downsampling_factor - precision - strength - embedding_path - - The vast majority of these arguments default to reasonable values. + Attributes + ---------- + model + config + iterations + batch_size + steps + seed + sampler_name + width + height + cfg_scale + latent_channels + downsampling_factor + precision + strength + embedding_path + +The vast majority of these arguments default to reasonable values. """ - def __init__( - self, - batch_size=1, - iterations=1, - steps=50, - seed=None, - cfg_scale=7.5, - weights='models/ldm/stable-diffusion-v1/model.ckpt', - config='configs/stable-diffusion/v1-inference.yaml', - width=512, - height=512, - sampler_name='klms', - latent_channels=4, - downsampling_factor=8, - ddim_eta=0.0, # deterministic - precision='autocast', - full_precision=False, - strength=0.75, # default in scripts/img2img.py - embedding_path=None, - latent_diffusion_weights=False, # just to keep track of this parameter when regenerating prompt - device='cuda', - gfpgan=None, - ): + def __init__(self, + batch_size=1, + iterations=1, + steps=50, + seed=None, + cfg_scale=7.5, + weights="models/ldm/stable-diffusion-v1/model.ckpt", + config="configs/stable-diffusion/v1-inference.yaml", + width=512, + height=512, + sampler_name="klms", + latent_channels=4, + downsampling_factor=8, + ddim_eta=0.0, # deterministic + precision='autocast', + full_precision=False, + strength=0.75, # default in scripts/img2img.py + embedding_path=None, + # just to keep track of this parameter when regenerating prompt + latent_diffusion_weights=False, + device='cuda', + ): self.batch_size = batch_size self.iterations = iterations self.width = width @@ -157,7 +156,7 @@ def __init__( self.sampler = None self.latent_diffusion_weights = latent_diffusion_weights self.device = device - self.gfpgan = gfpgan + if seed is None: self.seed = self._new_seed() else: @@ -165,17 +164,17 @@ def __init__( transformers.logging.set_verbosity_error() def prompt2png(self, prompt, outdir, **kwargs): - """ + ''' Takes a prompt and an output directory, writes out the requested number of PNG files, and returns an array of [[filename,seed],[filename,seed]...] Optional named arguments are the same as those passed to T2I and prompt2image() - """ + ''' results = self.prompt2image(prompt, **kwargs) - pngwriter = PngWriter( - outdir, prompt, kwargs.get('batch_size', self.batch_size) - ) + pngwriter = PngWriter(outdir, prompt, kwargs.get( + 'batch_size', self.batch_size)) for r in results: - metadata_str = f'prompt2png("{prompt}" {kwargs} seed={r[1]}' # gets written into the PNG + # gets written into the PNG + metadata_str = f'prompt2png("{prompt}" {kwargs} seed={r[1]}' pngwriter.write_image(r[0], r[1]) return pngwriter.files_written @@ -185,34 +184,32 @@ def txt2img(self, prompt, **kwargs): def img2img(self, prompt, **kwargs): outdir = kwargs.get('outdir', 'outputs/img-samples') - assert ( - 'init_img' in kwargs - ), 'call to img2img() must include the init_img argument' + assert 'init_img' in kwargs, 'call to img2img() must include the init_img argument' return self.prompt2png(prompt, outdir, **kwargs) - def prompt2image( - self, - # these are common - prompt, - batch_size=None, - iterations=None, - steps=None, - seed=None, - cfg_scale=None, - ddim_eta=None, - skip_normalize=False, - image_callback=None, - # these are specific to txt2img - width=None, - height=None, - # these are specific to img2img - init_img=None, - strength=None, - gfpgan_strength=None, - variants=None, - **args, - ): # eat up additional cruft - """ + def prompt2image(self, + # these are common + prompt, + batch_size=None, + iterations=None, + steps=None, + seed=None, + cfg_scale=None, + ddim_eta=None, + skip_normalize=False, + image_callback=None, + # these are specific to txt2img + width=None, + height=None, + # these are specific to img2img + init_img=None, + strength=None, + gfpgan_strength=None, + save_original=False, + upscale=None, + variants=None, + **args): # eat up additional cruft + ''' ldm.prompt2image() is the common entry point for txt2img() and img2img() It takes the following arguments: prompt // prompt string (no default) @@ -240,7 +237,7 @@ def process_image(image,seed): The callback used by the prompt2png() can be found in ldm/dream_util.py. It contains code to create the requested output directory, select a unique informative name for each image, and write the prompt into the PNG metadata. - """ + ''' steps = steps or self.steps seed = seed or self.seed width = width or self.width @@ -251,23 +248,18 @@ def process_image(image,seed): iterations = iterations or self.iterations strength = strength or self.strength - model = ( - self.load_model() - ) # will instantiate the model or return it from cache - assert cfg_scale > 1.0, 'CFG_Scale (-C) must be >1.0' - assert ( - 0.0 <= strength <= 1.0 - ), 'can only work with strength in [0.0, 1.0]' - w = int(width / 64) * 64 - h = int(height / 64) * 64 + model = self.load_model() # will instantiate the model or return it from cache + assert cfg_scale > 1.0, "CFG_Scale (-C) must be >1.0" + assert 0. <= strength <= 1., 'can only work with strength in [0.0, 1.0]' + w = int(width/64) * 64 + h = int(height/64) * 64 if h != height or w != width: print( - f'Height and width must be multiples of 64. Resizing to {h}x{w}' - ) + f'Height and width must be multiples of 64. Resizing to {h}x{w}') height = h width = w - scope = autocast if self.precision == 'autocast' else nullcontext + scope = autocast if self.precision == "autocast" else nullcontext tic = time.time() results = list() @@ -275,80 +267,74 @@ def process_image(image,seed): try: if init_img: assert os.path.exists(init_img), f'{init_img}: File not found' - images_iterator = self._img2img( - prompt, - precision_scope=scope, - batch_size=batch_size, - steps=steps, - cfg_scale=cfg_scale, - ddim_eta=ddim_eta, - skip_normalize=skip_normalize, - init_img=init_img, - strength=strength, - ) + images_iterator = self._img2img(prompt, + precision_scope=scope, + batch_size=batch_size, + steps=steps, cfg_scale=cfg_scale, ddim_eta=ddim_eta, + skip_normalize=skip_normalize, + init_img=init_img, strength=strength) else: - images_iterator = self._txt2img( - prompt, - precision_scope=scope, - batch_size=batch_size, - steps=steps, - cfg_scale=cfg_scale, - ddim_eta=ddim_eta, - skip_normalize=skip_normalize, - width=width, - height=height, - ) + images_iterator = self._txt2img(prompt, + precision_scope=scope, + batch_size=batch_size, + steps=steps, cfg_scale=cfg_scale, ddim_eta=ddim_eta, + skip_normalize=skip_normalize, + width=width, height=height) with scope(self.device.type), self.model.ema_scope(): - for n in trange(iterations, desc='Sampling'): + for n in trange(iterations, desc="Generating"): seed_everything(seed) iter_images = next(images_iterator) for image in iter_images: - try: - # if gfpgan strength is none or less than or equal to 0.0 then - # don't even attempt to use GFPGAN. - # if the user specified a value of -G that satisifies the condition and - # --gfpgan wasn't specified, at startup then - # the net result is a message gets printed - nothing else happens. - if gfpgan_strength is not None and gfpgan_strength > 0.0: - image = self._run_gfpgan( - image, gfpgan_strength - ) - except Exception as e: - print( - f'Error running GFPGAN - Your image was not enhanced.\n{e}' - ) results.append([image, seed]) if image_callback is not None: image_callback(image, seed) seed = self._new_seed() + if upscale is not None or gfpgan_strength > 0: + for result in results: + image, seed = result + try: + if upscale is not None: + from ldm.gfpgan.gfpgan_tools import real_esrgan_upscale + image = real_esrgan_upscale( + image, upscale[1], int(upscale[0]), prompt, seed) + if gfpgan_strength > 0: + from ldm.gfpgan.gfpgan_tools import _run_gfpgan + image = _run_gfpgan( + image, gfpgan_strength, prompt, seed, 1) + except Exception as e: + print( + f"Error running RealESRGAN - Your image was not upscaled.\n{e}") + if image_callback is not None: + if save_original: + image_callback(image, seed) + else: + image_callback( + image, seed, upscaled=True) + except KeyboardInterrupt: print('*interrupted*') print( - 'Partial results will be returned; if --grid was requested, nothing will be returned.' - ) + 'Partial results will be returned; if --grid was requested, nothing will be returned.') except RuntimeError as e: print(str(e)) print('Are you sure your system has an adequate NVIDIA GPU?') toc = time.time() - print(f'{len(results)} images generated in', '%4.2fs' % (toc - tic)) + + print(f'{len(results)} images generated in', + "%4.2fs" % (toc-tic)) return results @torch.no_grad() - def _txt2img( - self, - prompt, - precision_scope, - batch_size, - steps, - cfg_scale, - ddim_eta, - skip_normalize, - width, - height, - ): + def _txt2img(self, + prompt, + precision_scope, + batch_size, + steps, cfg_scale, ddim_eta, + skip_normalize, + width, height): """ An infinite iterator of images from the prompt. """ @@ -357,36 +343,26 @@ def _txt2img( while True: uc, c = self._get_uc_and_c(prompt, batch_size, skip_normalize) - shape = [ - self.latent_channels, - height // self.downsampling_factor, - width // self.downsampling_factor, - ] - samples, _ = sampler.sample( - S=steps, - conditioning=c, - batch_size=batch_size, - shape=shape, - verbose=False, - unconditional_guidance_scale=cfg_scale, - unconditional_conditioning=uc, - eta=ddim_eta, - ) + shape = [self.latent_channels, height // + self.downsampling_factor, width // self.downsampling_factor] + samples, _ = sampler.sample(S=steps, + conditioning=c, + batch_size=batch_size, + shape=shape, + verbose=False, + unconditional_guidance_scale=cfg_scale, + unconditional_conditioning=uc, + eta=ddim_eta) yield self._samples_to_images(samples) @torch.no_grad() - def _img2img( - self, - prompt, - precision_scope, - batch_size, - steps, - cfg_scale, - ddim_eta, - skip_normalize, - init_img, - strength, - ): + def _img2img(self, + prompt, + precision_scope, + batch_size, + steps, cfg_scale, ddim_eta, + skip_normalize, + init_img, strength): """ An infinite iterator of images from the prompt and the initial image """ @@ -394,8 +370,7 @@ def _img2img( # PLMS sampler not supported yet, so ignore previous sampler if self.sampler_name != 'ddim': print( - f"sampler '{self.sampler_name}' is not yet supported. Using DDM sampler" - ) + f"sampler '{self.sampler_name}' is not yet supported. Using DDM sampler") sampler = DDIMSampler(self.model, device=self.device) else: sampler = self.sampler @@ -404,12 +379,10 @@ def _img2img( init_image = repeat(init_image, '1 ... -> b ...', b=batch_size) with precision_scope(self.device.type): init_latent = self.model.get_first_stage_encoding( - self.model.encode_first_stage(init_image) - ) # move to latent space + self.model.encode_first_stage(init_image)) # move to latent space - sampler.make_schedule( - ddim_num_steps=steps, ddim_eta=ddim_eta, verbose=False - ) + sampler.make_schedule(ddim_num_steps=steps, + ddim_eta=ddim_eta, verbose=False) t_enc = int(strength * steps) # print(f"target t_enc is {t_enc} steps") @@ -419,22 +392,16 @@ def _img2img( # encode (scaled latent) z_enc = sampler.stochastic_encode( - init_latent, torch.tensor([t_enc] * batch_size).to(self.device) - ) + init_latent, torch.tensor([t_enc]*batch_size).to(self.device)) # decode it - samples = sampler.decode( - z_enc, - c, - t_enc, - unconditional_guidance_scale=cfg_scale, - unconditional_conditioning=uc, - ) + samples = sampler.decode(z_enc, c, t_enc, unconditional_guidance_scale=cfg_scale, + unconditional_conditioning=uc,) yield self._samples_to_images(samples) # TODO: does this actually need to run every loop? does anything in it vary by random seed? def _get_uc_and_c(self, prompt, batch_size, skip_normalize): - uc = self.model.get_learned_conditioning(batch_size * ['']) + uc = self.model.get_learned_conditioning(batch_size * [""]) # weighted sub-prompts subprompts, weights = T2I._split_weighted_subprompts(prompt) @@ -448,14 +415,9 @@ def _get_uc_and_c(self, prompt, batch_size, skip_normalize): weight = weights[i] if not skip_normalize: weight = weight / totalWeight - c = torch.add( - c, - self.model.get_learned_conditioning( - batch_size * [subprompts[i]] - ), - alpha=weight, - ) - else: # just standard 1 prompt + c = torch.add(c, self.model.get_learned_conditioning( + batch_size * [subprompts[i]]), alpha=weight) + else: # just standard 1 prompt c = self.model.get_learned_conditioning(batch_size * [prompt]) return (uc, c) @@ -464,9 +426,8 @@ def _samples_to_images(self, samples): x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0) images = list() for x_sample in x_samples: - x_sample = 255.0 * rearrange( - x_sample.cpu().numpy(), 'c h w -> h w c' - ) + x_sample = 255. * \ + rearrange(x_sample.cpu().numpy(), 'c h w -> h w c') image = Image.fromarray(x_sample.astype(np.uint8)) images.append(image) return images @@ -475,17 +436,21 @@ def _new_seed(self): self.seed = random.randrange(0, np.iinfo(np.uint32).max) return self.seed + def _get_device(self): + if torch.cuda.is_available(): + return torch.device('cuda') + elif torch.backends.mps.is_available(): + return torch.device('mps') + else: + return torch.device('cpu') + def load_model(self): - """Load and initialize the model from configuration variables passed at object creation time""" + """ Load and initialize the model from configuration variables passed at object creation time """ if self.model is None: seed_everything(self.seed) try: config = OmegaConf.load(self.config) - self.device = ( - torch.device(self.device) - if torch.cuda.is_available() - else torch.device('cpu') - ) + self.device = self._get_device() model = self._load_model_from_config(config, self.weights) if self.embedding_path is not None: model.embedding_manager.load(self.embedding_path) @@ -502,20 +467,16 @@ def load_model(self): self.sampler = DDIMSampler(self.model, device=self.device) elif self.sampler_name == 'k_dpm_2_a': self.sampler = KSampler( - self.model, 'dpm_2_ancestral', device=self.device - ) + self.model, 'dpm_2_ancestral', device=self.device) elif self.sampler_name == 'k_dpm_2': self.sampler = KSampler( - self.model, 'dpm_2', device=self.device - ) + self.model, 'dpm_2', device=self.device) elif self.sampler_name == 'k_euler_a': self.sampler = KSampler( - self.model, 'euler_ancestral', device=self.device - ) + self.model, 'euler_ancestral', device=self.device) elif self.sampler_name == 'k_euler': self.sampler = KSampler( - self.model, 'euler', device=self.device - ) + self.model, 'euler', device=self.device) elif self.sampler_name == 'k_heun': self.sampler = KSampler(self.model, 'heun', device=self.device) elif self.sampler_name == 'k_lms': @@ -529,38 +490,33 @@ def load_model(self): return self.model def _load_model_from_config(self, config, ckpt): - print(f'Loading model from {ckpt}') - pl_sd = torch.load(ckpt, map_location='cpu') - # if "global_step" in pl_sd: - # print(f"Global Step: {pl_sd['global_step']}") - sd = pl_sd['state_dict'] + print(f"Loading model from {ckpt}") + pl_sd = torch.load(ckpt, map_location="cpu") +# if "global_step" in pl_sd: +# print(f"Global Step: {pl_sd['global_step']}") + sd = pl_sd["state_dict"] model = instantiate_from_config(config.model) m, u = model.load_state_dict(sd, strict=False) model.to(self.device) model.eval() if self.full_precision: - print( - 'Using slower but more accurate full-precision math (--full_precision)' - ) + print('Using slower but more accurate full-precision math (--full_precision)') else: - print( - 'Using half precision math. Call with --full_precision to use slower but more accurate full precision.' - ) + print('Using half precision math. Call with --full_precision to use slower but more accurate full precision.') model.half() return model def _load_img(self, path): - image = Image.open(path).convert('RGB') + image = Image.open(path).convert("RGB") w, h = image.size - print(f'loaded input image of size ({w}, {h}) from {path}') - w, h = map( - lambda x: x - x % 32, (w, h) - ) # resize to integer multiple of 32 + print(f"loaded input image of size ({w}, {h}) from {path}") + # resize to integer multiple of 32 + w, h = map(lambda x: x - x % 32, (w, h)) image = image.resize((w, h), resample=Image.Resampling.LANCZOS) image = np.array(image).astype(np.float32) / 255.0 image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image) - return 2.0 * image - 1.0 + return 2.*image - 1. def _split_weighted_subprompts(text): """ @@ -573,63 +529,37 @@ def _split_weighted_subprompts(text): prompts = [] weights = [] while remaining > 0: - if ':' in text: - idx = text.index(':') # first occurrence from start + if ":" in text: + idx = text.index(":") # first occurrence from start # grab up to index as sub-prompt prompt = text[:idx] remaining -= idx # remove from main text - text = text[idx + 1 :] + text = text[idx+1:] # find value for weight - if ' ' in text: - idx = text.index(' ') # first occurence - else: # no space, read to end + if " " in text: + idx = text.index(" ") # first occurence + else: # no space, read to end idx = len(text) if idx != 0: try: weight = float(text[:idx]) - except: # couldn't treat as float + except: # couldn't treat as float print( - f"Warning: '{text[:idx]}' is not a value, are you missing a space?" - ) + f"Warning: '{text[:idx]}' is not a value, are you missing a space?") weight = 1.0 - else: # no value found + else: # no value found weight = 1.0 # remove from main text remaining -= idx - text = text[idx + 1 :] + text = text[idx+1:] # append the sub-prompt and its weight prompts.append(prompt) weights.append(weight) - else: # no : found - if len(text) > 0: # there is still text though + else: # no : found + if len(text) > 0: # there is still text though # take remainder as weight 1 prompts.append(text) weights.append(1.0) remaining = 0 return prompts, weights - - def _run_gfpgan(self, image, strength): - if self.gfpgan is None: - print( - f'GFPGAN not initialized, it must be loaded via the --gfpgan argument' - ) - return image - - image = image.convert('RGB') - - cropped_faces, restored_faces, restored_img = self.gfpgan.enhance( - np.array(image, dtype=np.uint8), - has_aligned=False, - only_center_face=False, - paste_back=True, - ) - res = Image.fromarray(restored_img) - - if strength < 1.0: - # Resize the image to the new image if the sizes have changed - if restored_img.size != image.size: - image = image.resize(res.size) - res = Image.blend(image, res, strength) - - return res diff --git a/scripts/dream.py b/scripts/dream.py index 5d5e8db4a5a..e84197c5dbf 100755 --- a/scripts/dream.py +++ b/scripts/dream.py @@ -21,14 +21,14 @@ def main(): # defaults suitable to the older latent diffusion weights width = 256 height = 256 - config = 'configs/latent-diffusion/txt2img-1p4B-eval.yaml' - weights = 'models/ldm/text2img-large/model.ckpt' + config = "configs/latent-diffusion/txt2img-1p4B-eval.yaml" + weights = "models/ldm/text2img-large/model.ckpt" else: # some defaults suitable for stable diffusion weights width = 512 height = 512 - config = 'configs/stable-diffusion/v1-inference.yaml' - weights = 'models/ldm/stable-diffusion-v1/model.ckpt' + config = "configs/stable-diffusion/v1-inference.yaml" + weights = "models/ldm/stable-diffusion-v1/model.ckpt" print('* Initializing, be patient...\n') sys.path.append('.') @@ -45,17 +45,17 @@ def main(): # defaults passed on the command line. # additional parameters will be added (or overriden) during # the user input loop - t2i = T2I( - width=width, - height=height, - sampler_name=opt.sampler_name, - weights=weights, - full_precision=opt.full_precision, - config=config, - latent_diffusion_weights=opt.laion400m, # this is solely for recreating the prompt - embedding_path=opt.embedding_path, - device=opt.device, - ) + t2i = T2I(width=width, + height=height, + sampler_name=opt.sampler_name, + weights=weights, + full_precision=opt.full_precision, + config=config, + # this is solely for recreating the prompt + latent_diffusion_weights=opt.laion400m, + embedding_path=opt.embedding_path, + device=opt.device, + ) # make sure the output directory exists if not os.path.exists(opt.outdir): @@ -75,44 +75,7 @@ def main(): # preload the model t2i.load_model() - # load GFPGAN if requested - if opt.use_gfpgan: - print('\n* --gfpgan was specified, loading gfpgan...') - with warnings.catch_warnings(): - warnings.filterwarnings('ignore', category=DeprecationWarning) - - try: - model_path = os.path.join( - opt.gfpgan_dir, opt.gfpgan_model_path - ) - if not os.path.isfile(model_path): - raise Exception( - 'GFPGAN model not found at path ' + model_path - ) - - sys.path.append(os.path.abspath(opt.gfpgan_dir)) - from gfpgan import GFPGANer - - bg_upsampler = load_gfpgan_bg_upsampler( - opt.gfpgan_bg_upsampler, opt.gfpgan_bg_tile - ) - - t2i.gfpgan = GFPGANer( - model_path=model_path, - upscale=opt.gfpgan_upscale, - arch='clean', - channel_multiplier=2, - bg_upsampler=bg_upsampler, - ) - except Exception: - import traceback - - print('Error loading GFPGAN:', file=sys.stderr) - print(traceback.format_exc(), file=sys.stderr) - - print( - "\n* Initialization done! Awaiting your command (-h for help, 'q' to quit, 'cd' to change output dir, 'pwd' to print output dir)..." - ) + print("\n* Initialization done! Awaiting your command (-h for help, 'q' to quit, 'cd' to change output dir, 'pwd' to print output dir)...") log_path = os.path.join(opt.outdir, 'dream_log.txt') with open(log_path, 'a') as log: @@ -124,13 +87,13 @@ def main(): def main_loop(t2i, outdir, parser, log, infile): - """prompt/read/execute loop""" + ''' prompt/read/execute loop ''' done = False last_seeds = [] while not done: try: - command = infile.readline() if infile else input('dream> ') + command = infile.readline() if infile else input("dream> ") except EOFError: done = True break @@ -161,19 +124,18 @@ def main_loop(t2i, outdir, parser, log, infile): if elements[0] == 'cd' and len(elements) > 1: if os.path.exists(elements[1]): - print(f'setting image output directory to {elements[1]}') + print(f"setting image output directory to {elements[1]}") outdir = elements[1] else: print(f'directory {elements[1]} does not exist') continue if elements[0] == 'pwd': - print(f'current output directory is {outdir}') + print(f"current output directory is {outdir}") continue - if elements[0].startswith( - '!dream' - ): # in case a stored prompt still contains the !dream command + # in case a stored prompt still contains the !dream command + if elements[0].startswith('!dream'): elements.pop(0) # rearrange the arguments to mimic how it works in the Dream bot. @@ -196,9 +158,9 @@ def main_loop(t2i, outdir, parser, log, infile): parser.print_help() continue if len(opt.prompt) == 0: - print('Try again with a prompt!') + print("Try again with a prompt!") continue - if opt.seed is not None and opt.seed < 0: # retrieve previous value! + if opt.seed is not None and opt.seed < 0: # retrieve previous value! try: opt.seed = last_seeds[opt.seed] print(f'reusing previous seed {opt.seed}') @@ -214,9 +176,7 @@ def main_loop(t2i, outdir, parser, log, infile): callback = file_writer.write_image if individual_images else None image_list = t2i.prompt2image(image_callback=callback, **vars(opt)) - results = ( - file_writer.files_written if individual_images else image_list - ) + results = file_writer.files_written if individual_images else image_list if opt.grid and len(results) > 0: grid_img = file_writer.make_grid([r[0] for r in results]) @@ -225,8 +185,7 @@ def main_loop(t2i, outdir, parser, log, infile): results = [[filename, seeds]] metadata_prompt = f'{normalized_prompt} -S{results[0][1]}' file_writer.save_image_and_prompt_to_png( - grid_img, metadata_prompt, filename - ) + grid_img, metadata_prompt, filename) last_seeds = [r[1] for r in results] @@ -238,50 +197,10 @@ def main_loop(t2i, outdir, parser, log, infile): print(e) continue - print('Outputs:') + print("Outputs:") write_log_message(t2i, normalized_prompt, results, log) - print('goodbye!') - - -def load_gfpgan_bg_upsampler(bg_upsampler, bg_tile=400): - import torch - - if bg_upsampler == 'realesrgan': - if not torch.cuda.is_available(): # CPU - import warnings - - warnings.warn( - 'The unoptimized RealESRGAN is slow on CPU. We do not use it. ' - 'If you really want to use it, please modify the corresponding codes.' - ) - bg_upsampler = None - else: - from basicsr.archs.rrdbnet_arch import RRDBNet - from realesrgan import RealESRGANer - - model = RRDBNet( - num_in_ch=3, - num_out_ch=3, - num_feat=64, - num_block=23, - num_grow_ch=32, - scale=2, - ) - bg_upsampler = RealESRGANer( - scale=2, - model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth', - model=model, - tile=bg_tile, - tile_pad=10, - pre_pad=0, - half=True, - ) # need to set False in CPU mode - else: - bg_upsampler = None - - return bg_upsampler - + print("goodbye!") # variant generation is going to be superseded by a generalized # "prompt-morph" functionality @@ -310,7 +229,7 @@ def load_gfpgan_bg_upsampler(bg_upsampler, bg_tile=400): def write_log_message(t2i, prompt, results, logfile): - """logs the name of the output image, its prompt and seed to the terminal, log file, and a Dream text chunk in the PNG metadata""" + ''' logs the name of the output image, its prompt and seed to the terminal, log file, and a Dream text chunk in the PNG metadata''' last_seed = None img_num = 1 seenit = {} @@ -326,109 +245,61 @@ def write_log_message(t2i, prompt, results, logfile): def create_argv_parser(): parser = argparse.ArgumentParser( - description="Parse script's command line args" - ) - parser.add_argument( - '--laion400m', - '--latent_diffusion', - '-l', - dest='laion400m', - action='store_true', - help='fallback to the latent diffusion (laion400m) weights and config', - ) - parser.add_argument( - '--from_file', - dest='infile', - type=str, - help='if specified, load prompts from this file', - ) - parser.add_argument( - '-n', - '--iterations', - type=int, - default=1, - help='number of images to generate', - ) - parser.add_argument( - '-F', - '--full_precision', - dest='full_precision', - action='store_true', - help='use slower full precision math for calculations', - ) - parser.add_argument( - '--sampler', - '-m', - dest='sampler_name', - choices=[ - 'ddim', - 'k_dpm_2_a', - 'k_dpm_2', - 'k_euler_a', - 'k_euler', - 'k_heun', - 'k_lms', - 'plms', - ], - default='k_lms', - help='which sampler to use (k_lms) - can only be set on command line', - ) - parser.add_argument( - '--outdir', - '-o', - type=str, - default='outputs/img-samples', - help='directory in which to place generated images and a log of prompts and seeds (outputs/img-samples', - ) - parser.add_argument( - '--embedding_path', - type=str, - help='Path to a pre-trained embedding manager checkpoint - can only be set on command line', - ) - parser.add_argument( - '--device', - '-d', - type=str, - default='cuda', - help='device to run stable diffusion on. defaults to cuda `torch.cuda.current_device()` if avalible', - ) + description="Parse script's command line args") + parser.add_argument("--laion400m", + "--latent_diffusion", + "-l", + dest='laion400m', + action='store_true', + help="fallback to the latent diffusion (laion400m) weights and config") + parser.add_argument("--from_file", + dest='infile', + type=str, + help="if specified, load prompts from this file") + parser.add_argument('-n', '--iterations', + type=int, + default=1, + help="number of images to generate") + parser.add_argument('-F', '--full_precision', + dest='full_precision', + action='store_true', + help="use slower full precision math for calculations") + parser.add_argument('--sampler', '-m', + dest="sampler_name", + choices=['ddim', 'k_dpm_2_a', 'k_dpm_2', + 'k_euler_a', 'k_euler', 'k_heun', 'k_lms', 'plms'], + default='k_lms', + help="which sampler to use (k_lms) - can only be set on command line") + parser.add_argument('--outdir', + '-o', + type=str, + default="outputs/img-samples", + help="directory in which to place generated images and a log of prompts and seeds (outputs/img-samples") + parser.add_argument('--embedding_path', + type=str, + help="Path to a pre-trained embedding manager checkpoint - can only be set on command line") + parser.add_argument('--device', + '-d', + type=str, + default="cuda", + help="device to run stable diffusion on. defaults to cuda `torch.cuda.current_device()` if avalible") # GFPGAN related args - parser.add_argument( - '--gfpgan', - dest='use_gfpgan', - action='store_true', - help='load gfpgan for use in the dreambot. Note: Enabling GFPGAN will require more GPU memory', - ) - parser.add_argument( - '--gfpgan_upscale', - type=int, - default=2, - help='The final upsampling scale of the image. Default: 2. Only used if --gfpgan is specified', - ) - parser.add_argument( - '--gfpgan_bg_upsampler', - type=str, - default='realesrgan', - help='Background upsampler. Default: None. Options: realesrgan, none. Only used if --gfpgan is specified', - ) - parser.add_argument( - '--gfpgan_bg_tile', - type=int, - default=400, - help='Tile size for background sampler, 0 for no tile during testing. Default: 400. Only used if --gfpgan is specified', - ) - parser.add_argument( - '--gfpgan_model_path', - type=str, - default='experiments/pretrained_models/GFPGANv1.3.pth', - help='indicates the path to the GFPGAN model, relative to --gfpgan_dir. Only used if --gfpgan is specified', - ) - parser.add_argument( - '--gfpgan_dir', - type=str, - default='../GFPGAN', - help='indicates the directory containing the GFPGAN code. Only used if --gfpgan is specified', - ) + parser.add_argument("--gfpgan_bg_upsampler", + type=str, + default='realesrgan', + help="Background upsampler. Default: None. Options: realesrgan, none.") + parser.add_argument("--gfpgan_bg_tile", + type=int, + default=400, + help="Tile size for background sampler, 0 for no tile during testing. Default: 400.") + parser.add_argument("--gfpgan_dir", + type=str, + default='../GFPGAN', + help="indicates the directory containing the GFPGAN code.") + parser.add_argument("--gfpgan_model_path", + type=str, + default='experiments/pretrained_models/GFPGANv1.3.pth', + help="indicates the path to the GFPGAN model, relative to --gfpgan_dir.") return parser @@ -437,79 +308,40 @@ def create_cmd_parser(): description='Example: dream> a fantastic alien landscape -W1024 -H960 -s100 -n12' ) parser.add_argument('prompt') - parser.add_argument('-s', '--steps', type=int, help='number of steps') - parser.add_argument( - '-S', - '--seed', - type=int, - help='image seed; a +ve integer, or use -1 for the previous seed, -2 for the one before that, etc', - ) - parser.add_argument( - '-n', - '--iterations', - type=int, - default=1, - help='number of samplings to perform (slower, but will provide seeds for individual images)', - ) - parser.add_argument( - '-b', - '--batch_size', - type=int, - default=1, - help='number of images to produce per sampling (will not provide seeds for individual images!)', - ) - parser.add_argument( - '-W', '--width', type=int, help='image width, multiple of 64' - ) - parser.add_argument( - '-H', '--height', type=int, help='image height, multiple of 64' - ) - parser.add_argument( - '-C', - '--cfg_scale', - default=7.5, - type=float, - help='prompt configuration scale', - ) - parser.add_argument( - '-g', '--grid', action='store_true', help='generate a grid' - ) - parser.add_argument( - '-i', - '--individual', - action='store_true', - help='generate individual files (default)', - ) - parser.add_argument( - '-I', - '--init_img', - type=str, - help='path to input image for img2img mode (supersedes width and height)', - ) - parser.add_argument( - '-f', - '--strength', - default=0.75, - type=float, - help='strength for noising/unnoising. 0.0 preserves image exactly, 1.0 replaces it completely', - ) - parser.add_argument( - '-G', - '--gfpgan_strength', - default=None, - type=float, - help='The strength at which to apply the GFPGAN model to the result, in order to improve faces.', - ) - # variants is going to be superseded by a generalized "prompt-morph" function - # parser.add_argument('-v','--variants',type=int,help="in img2img mode, the first generated image will get passed back to img2img to generate the requested number of variants") - parser.add_argument( - '-x', - '--skip_normalize', - action='store_true', - help='skip subprompt weight normalization', - ) + parser.add_argument('-s', '--steps', type=int, + default=50, help="number of steps") + parser.add_argument('-S', '--seed', type=int, + help="image seed; a +ve integer, or use -1 for the previous seed, -2 for the one before that, etc") + parser.add_argument('-n', '--iterations', type=int, default=1, + help="number of samplings to perform (slower, but will provide seeds for individual images)") + parser.add_argument('-b', '--batch_size', type=int, default=1, + help="number of images to produce per sampling (will not provide seeds for individual images!)") + parser.add_argument('-W', '--width', type=int, default=512, + help="image width, multiple of 64") + parser.add_argument('-H', '--height', type=int, + default=512, help="image height, multiple of 64") + parser.add_argument('-C', '--cfg_scale', default=7.5, + type=float, help="prompt configuration scale") + parser.add_argument('-g', '--grid', action='store_true', + help="generate a grid") + parser.add_argument('-i', '--individual', action='store_true', + help="generate individual files (default)") + parser.add_argument('-I', '--init_img', type=str, + help="path to input image for img2img mode (supersedes width and height)") + parser.add_argument('-f', '--strength', default=0.75, type=float, + help="strength for noising/unnoising. 0.0 preserves image exactly, 1.0 replaces it completely") + parser.add_argument('-G', '--gfpgan_strength', default=0, type=float, + help="The strength at which to apply the GFPGAN model to the result, in order to improve faces.") + parser.add_argument('-U', '--upscale', nargs=2, default=None, type=float, + help="Scale factor for Real-ESRGAN. Either use 2 or 4.") + parser.add_argument('-save_orig', '--save_original', action='store_true', + help="Save original. Use it when upscaling to save both versions.") +# variants is going to be superseded by a generalized "prompt-morph" function +# parser.add_argument('-v','--variants',type=int,help="in img2img mode, the first generated image will get passed back to img2img to generate the requested number of variants") + parser.add_argument('-x', '--skip_normalize', action='store_true', + help="skip subprompt weight normalization") return parser -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/scripts/preload_models.py b/scripts/preload_models.py index 624b61e48ec..9c9df2cb4a4 100755 --- a/scripts/preload_models.py +++ b/scripts/preload_models.py @@ -3,6 +3,9 @@ # Before running stable-diffusion on an internet-isolated machine, # run this script from one with internet connectivity. The # two machines must share a common .cache directory. +from transformers import CLIPTokenizer, CLIPTextModel +import clip +from transformers import BertTokenizerFast import sys import transformers import os @@ -12,7 +15,6 @@ # this will preload the Bert tokenizer fles print('preloading bert tokenizer...') -from transformers import BertTokenizerFast tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased') print('...success') @@ -28,8 +30,6 @@ print('preloading CLIP model (Ignore the deprecation warnings)...') sys.stdout.flush() -import clip -from transformers import CLIPTokenizer, CLIPTextModel tokenizer = CLIPTokenizer.from_pretrained(version) transformer = CLIPTextModel.from_pretrained(version) @@ -63,6 +63,14 @@ scale=2, ), ) + + RealESRGANer( + scale=4, + model_path='https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth', + model=RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, + num_block=23, num_grow_ch=32, scale=4), + ) + FaceRestoreHelper(1, det_model='retinaface_resnet50') print('...success') except Exception: diff --git a/static/dream_web/index.html b/static/dream_web/index.html index 5dca10997c1..4dccd05fb3b 100644 --- a/static/dream_web/index.html +++ b/static/dream_web/index.html @@ -25,9 +25,27 @@ - + - +