File size: 11,232 Bytes
b386992 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "d874e23f-9631-48e0-b635-84e7280bf07b",
"metadata": {},
"source": [
"# SDXL Training / Inference Tutorial\n",
"\n",
"### Note:\n",
"Currently, this notebook must be run in a NeMo container (> 24.09) and open_clip_torch<=2.24.0. An example command to launch the container:\n",
"\n",
"```\n",
"docker run --gpus all -it --rm -v <your_nemo_dir>:/opt/NeMo -v <your_dataset_dir>:/datasets --shm-size=8g \\\n",
" -p 8888:8888 --ulimit memlock=-1 --ulimit \\\n",
" stack=67108864 <your_nemo_container>\n",
"```\n",
"\n",
"\n",
"## Introduction\n",
"\n",
"This notebook illustrates how to train and perform inference using Stable Diffusion XL with the NeMo Toolkit. Despite differences in model configs, the training and inference procedure is similar as Stable Diffusion.\n",
"\n",
"The implementation of Stable Diffusion XL is based on [SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis](https://arxiv.org/abs/2307.01952).\n",
"\n",
"This tutorial will guide you through the following topics:\n",
"\n",
"1. Training a Stable Diffusion XL model.\n",
"2. Performing inference with the trained model.\n",
"\n",
"## Datasets\n",
"\n",
"Please refer to [Dataset Tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Multimodal%20Data%20Preparation.ipynb) for how to prepare a training dataset for Stable diffusion XL.\n",
"\n",
"For a pre-cached Stable Diffusion dataset, each webdataset tar file should, at a minimum, include the pickle files that store the pre-cached image and text features:\n",
"\n",
"```\n",
"t0_r0_0.tar\n",
"|---- 0000.pickle\n",
"|---- 0001.pickle\n",
"...\n",
"```\n",
"\n",
"For non-precached Stable Diffusion dataset, each webdataset tar file should contain the raw texts and corresponding images:\n",
"\n",
"```\n",
"t0_r0_0.tar\n",
"|---- 0000.jpg\n",
"|---- 0000.txt\n",
"|---- 0001.jpg\n",
"|---- 0001.txt\n",
"...\n",
"```\n",
"\n",
"## Encoders Preparation\n",
"\n",
"Depending on whether you precache the dataset, you might also need to first download the image and/or text encoders.\n",
"\n",
"### Option 1: Training on Non-Precached Dataset (Use Encoders During Training)\n",
"\n",
"#### A. Prepare VAE\n",
"To download the default VAE for Stable Diffusion:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "730cd137-0fce-4bab-8ac7-219e5c55faf2",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"! wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/vae/diffusion_pytorch_model.safetensors\n",
"! mkdir -p /sdxl_ckpts\n",
"! mv diffusion_pytorch_model.safetensors /sdxl_ckpts/vae.safetensors"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "fef8b245-7cee-4048-a9ec-3ada90432a89",
"metadata": {},
"source": [
"The above command will download the default VAE weights from HuggingFace and save it to `/sdxl_ckpts/vae.safetensors`.\n",
"\n",
"**Note**: if you want to customize the saved location, make sure it is also reflected in your training config.\n",
"#### B. Prepare Text Encoder\n",
"For the text encoders used in Stable Diffusion XL, it will be automatically downloaded by the training script we provide.\n",
"\n",
"The type of text encoder used in the sdxl model conditioner can be found in `conditioner_config` in the predefined training configs:\n",
"\n",
"```\n",
" conditioner_config:\n",
" _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.GeneralConditioner\n",
" emb_models:\n",
" - is_trainable: false\n",
" input_key: captions\n",
" ucg_rate: 0.1\n",
" emb_model:\n",
" _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.FrozenCLIPEmbedder\n",
" layer: hidden\n",
" layer_idx: 11\n",
" - is_trainable: false\n",
" ucg_rate: 0.1\n",
" input_key: captions\n",
" emb_model:\n",
" _target_: nemo.collections.multimodal.modules.stable_diffusion.encoders.modules.FrozenOpenCLIPEmbedder2\n",
" arch: ViT-bigG-14\n",
" version: laion2b_s39b_b160k\n",
" freeze: true\n",
" layer: penultimate\n",
" always_return_pooled: true\n",
" legacy: false\n",
"```"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "8854eb7a-e822-43f6-a1d5-12357049485a",
"metadata": {},
"source": [
"\n",
"### Option 2: Training on Precached Dataset (Training UNet Only)\n",
"\n",
"When using precached dataset (please refer to the [Dataset Tutorial](https://github.com/NVIDIA/NeMo/blob/main/tutorials/multimodal/Multimodal%20Data%20Preparation.ipynb) for details), every text feature and image feature are stored as key-value pairs in `.pickle` file:\n",
"\n",
"```\n",
"{\n",
" image_key: torch.Tensor(),\n",
" text_key: torch.Tensor(),\n",
"}\n",
"```\n",
"\n",
"Make sure in the training config, `cond_stage_key` is associated with `text_key` and `first_stage_key` is associated with `image_key`.\n",
"\n",
"We offer an expample script to convert a dataset from `parquet` file to webdataset `tar` files at [parquet_conversion](https://github.com/NVIDIA/NeMo/blob/main/scripts/multimodal_dataset_conversion/parquet_conversion.py). Three different modes of prechaed training are provided, they are:\n",
"\n",
"1. No Caching: VAE and Text encoders are loaded during training\n",
"2. Text only: Only text features are loaded from dataset during training\n",
"3. Both: Both image and text features are loaded from dataset during training\n",
"\n",
"In each mode, the cached components should be saved in its raw format in tarfiles while cached components should be saved as torch.Tensor()."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "5762427b-f60c-4dfd-8318-e55771b25354",
"metadata": {},
"source": [
"## Model Config Setup\n",
"\n",
"Now we will begin setting up the config file needed for Stable Diffusion training. We will use [sd_train.yaml](https://github.com/NVIDIA/NeMo/blob/main/examples/multimodal/text_to_image/stable_diffusion/conf/sd_xl_base_train.yaml) as the template.\n",
"\n",
"1. Modify `model.data.train.dataset_path` so that it has all the webdataset info files you want to train on\n",
"2. Modify `model.data.webdataset.local_root_path` to point to your dataset path\n",
"3. Make sure VAE path `model.first_stage_config.from_pretrained` is adjusted if using non-precached dataset\n",
"4. Make sure the `model.precache mode` is set properly with the dataset you prepared, as detailed above.\n",
"5. Configure `exp_manager.exp_dir` for experiment save directory\n",
"6. Configure `exp_manager.wandb_logger_kwargs` and/or `exp_manager.create_tensorboard_logger` if needed"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "70f858b3-f7d5-4678-b380-80582337bc23",
"metadata": {},
"source": [
"**Note**: Please refer to NeMo Toolkit Developer Guide's Stable Diffusion page for more details on in-depth customizations, including all available optimizations.\n",
"\n",
"## Training\n",
"\n",
"Once everything is set up, training stable diffusion is as simple as running:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "589e3a14-c881-4a56-b2bd-370653059dfc",
"metadata": {},
"outputs": [],
"source": "! torchrun /opt/NeMo/examples/multimodal/text_to_image/stable_diffusion/sd_xl_train.py trainer.max_steps=100 model.data.train.dataset_path=/path/to/wdinfo.pkl model.data.webdataset.local_root_path=/path/to/dataset trainer.devices=1 trainer.num_nodes=1 model.micro_batch_size=1 model.global_batch_size=1 model.first_stage_config.from_pretrained=/sdxl_ckpts/vae.safetensors model.fsdp=False"
},
{
"attachments": {},
"cell_type": "markdown",
"id": "892d72dd-c4d7-4ca4-a948-168e187af65c",
"metadata": {},
"source": [
"Intermediate checkpoints (during training) and final checkpoint will be saved to `exp_manager.exp_dir` folder. Note that here we use synthetic data for demo purpose."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "087c8b9a-92c3-43d3-86a3-bf7e848dfbd2",
"metadata": {},
"source": [
"## Inference\n",
"\n",
"Stable Diffusion XL inference needs a trained NeMo Stable Diffusion checkpoint, along with both the image encoder (VAE) and text encoder (CLIP). The checkpoint can be either a fully trained `.nemo` checkpoint or an intermediate checkpoint from training (typically in `.ckpt` format). \n",
"\n",
"### Inference Config Setup\n",
"\n",
"Now we will begin setting up the config file needed for Stable Diffusion inference. We will use [sd_xl_infer_v2.yaml](https://github.com/NVIDIA/NeMo/blob/main/examples/multimodal/text_to_image/stable_diffusion/conf/sd_xl_infer_v2.yaml) as the template.\n",
"\n",
"We generally use [Classifier Free Guidance](https://arxiv.org/abs/2207.12598) for better visual quality, which can be set at `sampling.base.scale`.\n",
"\n",
"NeMo Stable Diffusion supports multiple samplers. Please refer to the developer guide for more details. Samplers can be set at `sampling.base.sampler`.\n",
"\n",
"Inference supports a batch of text prompts, which can be set at `infer.prompt`. One can also generate a configurable number of images per prompt by setting `infer.num_samples`. Generated images will be saved to `out_path`.\n",
"\n",
"You will also need to set the model checkpoint path at `model.restore_from_path` if you are loading from `.nemo` checkpoint, otherwise, mannually set `unet` checkpoints and `vae` checkpoint at `model.unet_config.from_pretrained` and `model.first_stage_config.from_pretrained`, respectively.\n",
"\n",
"### Running the Inference\n",
"\n",
"Once everything is set up, Stable Diffusion inference is as simple as running:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9e676c5d-d711-489e-8ab7-3ee20046d88d",
"metadata": {},
"outputs": [],
"source": "! torchrun /opt/NeMo/examples/multimodal/text_to_image/stable_diffusion/sd_xl_infer.py model.restore_from_path=/path/to/stable-diffusion-xl-train.nemo out_path=/sdxl_infer_out"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|