CoolFace
Apppublic

CyStorm/instruct-pix2pix

sourceHugging Faceupdated 4y agoView on Hugging Face
1likes
README.md218 linesDownload Raw Back to root
1---2title: InstructPix2Pix3sdk: gradio4sdk_version: 3.16.25app_file: edit_app.py6pinned: true7duplicated_from: timbrooks/instruct-pix2pix8---9 10# InstructPix2Pix: Learning to Follow Image Editing Instructions11### [Project Page](https://www.timothybrooks.com/instruct-pix2pix/) | [Paper](https://arxiv.org/abs/2211.09800) | [Data](http://instruct-pix2pix.eecs.berkeley.edu/)12PyTorch implementation of InstructPix2Pix, an instruction-based image editing model, based on the original [CompVis/stable_diffusion](https://github.com/CompVis/stable-diffusion) repo. <br>13 14[InstructPix2Pix: Learning to Follow Image Editing Instructions](https://www.timothybrooks.com/instruct-pix2pix/)  15 [Tim Brooks](https://www.timothybrooks.com/)\*,16 [Aleksander Holynski](https://holynski.org/)\*,17 [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros/) <br>18 UC Berkeley <br>19  \*denotes equal contribution  20  21  <img src='https://instruct-pix2pix.timothybrooks.com/teaser.jpg'/>22 23## TL;DR: quickstart 24 25Set up a conda environment, and download a pretrained model:26```27conda env create -f environment.yaml28conda activate ip2p29bash scripts/download_checkpoints.sh30```31 32Edit a single image:33```34python edit_cli.py --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"35 36# Optionally, you can specify parameters to tune your result:37# python edit_cli.py --steps 100 --resolution 512 --seed 1371 --cfg-text 7.5 --cfg-image 1.2 --input imgs/example.jpg --output imgs/output.jpg --edit "turn him into a cyborg"38```39 40Or launch your own interactive editing Gradio app:41```42python edit_app.py 43```44![Edit app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/edit_app.jpg?raw=true)45 46_(For advice on how to get the best results by tuning parameters, see the [Tips](https://github.com/timothybrooks/instruct-pix2pix#tips) section)._47 48## Setup49 50Install all dependencies with:51```52conda env create -f environment.yaml53```54 55Download the pretrained models by running:56```57bash scripts/download_checkpoints.sh58```59 60## Generated Dataset61 62Our image editing model is trained on a generated dataset consisting of 454,445 examples. Each example contains (1) an input image, (2) an editing instruction, and (3) an output edited image. We provide two versions of the dataset, one in which each pair of edited images is generated 100 times, and the best examples are chosen based on CLIP metrics (Section 3.1.2 in the paper) (`clip-filtered-dataset`), and one in which examples are randomly chosen (`random-sample-dataset`).63 64For the released version of this dataset, we've additionally filtered prompts and images for NSFW content. After NSFW filtering, the GPT-3 generated dataset contains 451,990 examples. The final image-pair datasets contain:65 66|  | # of image editing examples | Dataset size |67|--|-----------------------|----------------------- |68| `random-sample-dataset` |451990|727GB|69|  `clip-filtered-dataset` |313010|436GB|70 71To download one of these datasets, along with the entire NSFW-filtered text data, run the following command with the appropriate dataset name:72 73```74bash scripts/download_data.sh clip-filtered-dataset75```76 77 78## Training InstructPix2Pix79 80InstructPix2Pix is trained by fine-tuning from an initial StableDiffusion checkpoint. The first step is to download a Stable Diffusion checkpoint. For our trained models, we used the v1.5 checkpoint as the starting point. To download the same ones we used, you can run the following script:81```82bash scripts/download_pretrained_sd.sh83```84If you'd like to use a different checkpoint, point to it in the config file `configs/train.yaml`, on line 8, after `ckpt_path:`. 85 86Next, we need to change the config to point to our downloaded (or generated) dataset. If you're using the `clip-filtered-dataset` from above, you can skip this. Otherwise, you may need to edit lines 85 and 94 of the config (`data.params.train.params.path`, `data.params.validation.params.path`). 87 88Finally, start a training job with the following command:89 90```91python main.py --name default --base configs/train.yaml --train --gpus 0,1,2,3,4,5,6,792```93 94 95## Creating your own dataset96 97Our generated dataset of paired images and editing instructions is made in two phases: First, we use GPT-3 to generate text triplets: (a) a caption describing an image, (b) an edit instruction, (c) a caption describing the image after the edit. Then, we turn pairs of captions (before/after the edit) into pairs of images using Stable Diffusion and Prompt-to-Prompt.98 99### (1) Generate a dataset of captions and instructions100 101We provide our generated dataset of captions and edit instructions [here](https://instruct-pix2pix.eecs.berkeley.edu/gpt-generated-prompts.jsonl). If you plan to use our captions+instructions, skip to step (2). Otherwise, if you would like to create your own text dataset, please follow steps (1.1-1.3) below. Note that generating very large datasets using GPT-3 can be expensive.102 103#### (1.1) Manually write a dataset of instructions and captions104 105The first step of the process is fine-tuning GPT-3. To do this, we made a dataset of 700 examples broadly covering of edits that we might want our model to be able to perform. Our examples are available [here](https://instruct-pix2pix.eecs.berkeley.edu/human-written-prompts.jsonl). These should be diverse and cover a wide range of possible captions and types of edits. Ideally, they should avoid duplication or significant overlap of captions and instructions. It is also important to be mindful of limitations of Stable Diffusion and Prompt-to-Prompt in writing these examples, such as inability to perform large spatial transformations (e.g., moving the camera, zooming in, swapping object locations). 106 107Input prompts should closely match the distribution of input prompts used to generate the larger dataset. We sampled the 700 input prompts from the _LAION Improved Aesthetics 6.5+_ dataset and also use this dataset for generating examples. We found this dataset is quite noisy (many of the captions are overly long and contain irrelevant text). For this reason, we also considered MSCOCO and LAION-COCO datasets, but ultimately chose _LAION Improved Aesthetics 6.5+_ due to its diversity of content, proper nouns, and artistic mediums. If you choose to use another dataset or combination of datasets as input to GPT-3 when generating examples, we recommend you sample the input prompts from the same distribution when manually writing training examples.108 109#### (1.2) Finetune GPT-3110 111The next step is to finetune a large language model on the manually written instructions/outputs to generate edit instructions and edited caption from a new input caption. For this, we finetune GPT-3's Davinci model via the OpenAI API, although other language models could be used.112 113To prepare training data for GPT-3, one must first create an OpenAI developer account to access the needed APIs, and [set up the API keys on your local device](https://beta.openai.com/docs/api-reference/introduction). Also, run the `prompts/prepare_for_gpt.py` script, which forms the prompts into the correct format by concatenating instructions and captions and adding delimiters and stop sequences.114 115```bash116python dataset_creation/prepare_for_gpt.py --input-path data/human-written-prompts.jsonl --output-path data/human-written-prompts-for-gpt.jsonl117```118 119Next, finetune GPT-3 via the OpenAI CLI. We provide an example below, although please refer to OpenAI's official documentation for this, as best practices may change. We trained the Davinci model for a single epoch. You can experiment with smaller less expensive GPT-3 variants or with open source language models, although this may negatively affect performance.120 121```bash122openai api fine_tunes.create -t data/human-written-prompts-for-gpt.jsonl -m davinci --n_epochs 1 --suffix "instruct-pix2pix"123```124 125You can test out the finetuned GPT-3 model by launching the provided Gradio app:126 127```bash128python prompt_app.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME129```130 131![Prompt app](https://github.com/timothybrooks/instruct-pix2pix/blob/main/imgs/prompt_app.jpg?raw=true)132 133#### (1.3) Generate a large dataset of captions and instructions134 135We now use the finetuned GPT-3 model to generate a large dataset. Our dataset cost thousands of dollars to create. See `prompts/gen_instructions_and_captions.py` for the script which generates these examples. We recommend first generating a small number of examples (by setting a low value of `--num-samples`) and gradually increasing the scale to ensure the results are working as desired before increasing scale.136 137```bash138python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME139```140 141If you are generating at a very large scale (e.g., 100K+), it will be noteably faster to generate the dataset with multiple processes running in parallel. This can be accomplished by setting `--partitions=N` to a higher number and running multiple processes, setting each `--partition` to the corresponding value.142 143```bash144python dataset_creation/generate_txt_dataset.py --openai-api-key OPENAI_KEY --openai-model OPENAI_MODEL_NAME --partitions=10 --partition=0145```146 147### (2) Turn paired captions into paired images148 149The next step is to turn pairs of text captions into pairs of images. For this, we need to copy some pre-trained Stable Diffusion checkpoints to `stable_diffusion/models/ldm/stable-diffusion-v1/`. You may have already done this if you followed the instructions above for training with our provided data, but if not, you can do this by running:150 151```bash152bash scripts/download_pretrained_sd.sh153```154 155For our model, we used [checkpoint v1.5](https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt), and the [new autoencoder](https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.ckpt), but other models may work as well. If you choose to use other models, make sure to change point to the corresponding checkpoints by passing in the `--ckpt` and `--vae-ckpt` arguments. Once all checkpoints have been downloaded, we can generate the dataset with the following command:156 157```158python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl159```160 161This command operates on a single GPU (typically a V100 or A100). To parallelize over many GPUs/machines, set `--n-partitions` to the total number of parallel jobs and `--partition` to the index of each job.162 163```164python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-partitions 100 --partition 0165```166 167The default parameters match that of our dataset, although in practice you can use a smaller number of steps (e.g., `--steps=25`) to generate high quality data faster. By default, we generate 100 samples per prompt and use CLIP filtering to keep a max of 4 per prompt. You can experiment with fewer samples by setting `--n-samples`. The command below turns off CLIP filtering entirely and is therefore faster:168 169```170python dataset_creation/generate_img_dataset.py --out_dir data/instruct-pix2pix-dataset-000 --prompts_file path/to/generated_prompts.jsonl --n-samples 4 --clip-threshold 0 --clip-dir-threshold 0 --clip-img-threshold 0 --n-partitions 100 --partition 0171```172 173After generating all of the dataset examples, run the following command below to create a list of the examples. This is needed for the dataset onject to efficiently be able to sample examples without needing to iterate over the entire dataset directory at the start of each training run.174 175```176python dataset_creation/prepare_dataset.py data/instruct-pix2pix-dataset-000177```178 179## Evaluation180 181To generate plots like the ones in Figures 8 and 10 in the paper, run the following command:182 183```184python metrics/compute_metrics.py --ckpt /path/to/your/model.ckpt185```186 187## Tips188 189If you're not getting the quality result you want, there may be a few reasons:1901. **Is the image not changing enough?** Your Image CFG weight may be too high. This value dictates how similar the output should be to the input. It's possible your edit requires larger changes from the original image, and your Image CFG weight isn't allowing that. Alternatively, your Text CFG weight may be too low. This value dictates how much to listen to the text instruction. The default Image CFG of 1.5 and Text CFG of 7.5 are a good starting point, but aren't necessarily optimal for each edit. Try:191    * Decreasing the Image CFG weight, or192    * Incerasing the Text CFG weight, or1932. Conversely, **is the image changing too much**, such that the details in the original image aren't preserved? Try:194    * Increasing the Image CFG weight, or195    * Decreasing the Text CFG weight1963. Try generating results with different random seeds by setting "Randomize Seed" and running generation multiple times. You can also try setting "Randomize CFG" to sample new Text CFG and Image CFG values each time.1974. Rephrasing the instruction sometimes improves results (e.g., "turn him into a dog" vs. "make him a dog" vs. "as a dog").1985. Increasing the number of steps sometimes improves results.1996. Do faces look weird? The Stable Diffusion autoencoder has a hard time with faces that are small in the image. Try cropping the image so the face takes up a larger portion of the frame.200 201## Comments202 203- Our codebase is based on the [Stable Diffusion codebase](https://github.com/CompVis/stable-diffusion).204 205## BibTeX206 207```208@article{brooks2022instructpix2pix,209  title={InstructPix2Pix: Learning to Follow Image Editing Instructions},210  author={Brooks, Tim and Holynski, Aleksander and Efros, Alexei A},211  journal={arXiv preprint arXiv:2211.09800},212  year={2022}213}214```215 216 217 218