├── src ├── __init__.py └── py_dreambooth │ ├── __init__.py │ ├── scripts │ ├── __init__.py │ ├── infer │ │ ├── __init__.py │ │ ├── sd_dreambooth │ │ │ ├── __init__.py │ │ │ ├── requirements.txt │ │ │ └── inference.py │ │ ├── sd_dreambooth_lora │ │ │ ├── __init__.py │ │ │ ├── requirements.txt │ │ │ └── inference.py │ │ ├── sdxl_dreambooth_lora │ │ │ ├── __init__.py │ │ │ ├── requirements.txt │ │ │ └── inference.py │ │ └── sdxl_dreambooth_lora_advanced │ │ │ ├── __init__.py │ │ │ ├── requirements.txt │ │ │ └── inference.py │ └── train │ │ ├── __init__.py │ │ └── requirements.txt │ ├── __version__.py │ ├── utils │ ├── __init__.py │ ├── misc.py │ ├── prompt_helpers.py │ ├── image_helpers.py │ └── aws_helpers.py │ ├── dataset.py │ ├── trainer.py │ ├── predictor.py │ └── model.py ├── docs └── CNAME ├── assets ├── asset-001.png └── asset-002.png ├── setup.cfg ├── requirements.txt ├── setup.py ├── README.md ├── .gitignore ├── ipynb ├── 01-local-tutorial.ipynb └── 02-aws-tutorial.ipynb └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/CNAME: -------------------------------------------------------------------------------- 1 | py-dreambooth.readthedocs.io -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/train/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth_lora/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora_advanced/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/asset-001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bits-bytes-nn/py-dreambooth/HEAD/assets/asset-001.png -------------------------------------------------------------------------------- /assets/asset-002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bits-bytes-nn/py-dreambooth/HEAD/assets/asset-002.png -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | addopts = 3 | -vv 4 | testpaths = tests 5 | 6 | [aliases] 7 | test = pytest 8 | 9 | [metadata] 10 | description-file = README.md 11 | license_file = LICENSE 12 | 13 | [wheel] 14 | universal = 1 -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/train/requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | bitsandbytes>=0.41.0 3 | deepspeed>=0.12.6 4 | diffusers==0.25.0 5 | peft==0.7.1 6 | safetensors>=0.4.1 7 | torch==2.0.0 8 | transformers==4.36.2 9 | wandb>=0.16.1 10 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth/requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | bitsandbytes>=0.41.0 3 | deepspeed>=0.12.6 4 | diffusers==0.25.0 5 | peft==0.7.1 6 | safetensors>=0.4.1 7 | torch==2.0.0 8 | transformers==4.36.2 9 | wandb>=0.16.1 10 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth_lora/requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | bitsandbytes>=0.41.0 3 | deepspeed>=0.12.6 4 | diffusers==0.25.0 5 | peft==0.7.1 6 | safetensors>=0.4.1 7 | torch==2.0.0 8 | transformers==4.36.2 9 | wandb>=0.16.1 10 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora/requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | bitsandbytes>=0.41.0 3 | deepspeed>=0.12.6 4 | diffusers==0.25.0 5 | peft==0.7.1 6 | safetensors>=0.4.1 7 | torch==2.0.0 8 | transformers==4.36.2 9 | wandb>=0.16.1 10 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora_advanced/requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | bitsandbytes>=0.41.0 3 | deepspeed>=0.12.6 4 | diffusers==0.25.0 5 | peft==0.7.1 6 | safetensors>=0.4.1 7 | torch==2.0.0 8 | transformers==4.36.2 9 | wandb>=0.16.1 10 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/__version__.py: -------------------------------------------------------------------------------- 1 | __title__ = "py-dreambooth" 2 | __description__ = "Easily create your own AI avatar images!" 3 | __version__ = "0.3.0" 4 | __author__ = "Youngmin Kim" 5 | __author_email__ = "aldente0630@gmail.com" 6 | __license__ = "creativeml-openrail-m" 7 | __url__ = "https://github.com/aldente0630/py-dreambooth" 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate>=0.25.0 2 | autocrop>=1.3.0 3 | awscli>=1.31.12 4 | boto3>=1.33.12 5 | bitsandbytes>=0.41.0 6 | deepspeed>=0.12.6 7 | diffusers==0.25.0 8 | matplotlib>=3.8.0 9 | peft==0.7.1 10 | pillow>=10.0.1 11 | prodigyopt>=1.0 12 | safetensors>=0.4.1 13 | sagemaker>=2.199.0 14 | tensorboard>=2.15.1 15 | torch==2.0.1 16 | torchvision>=0.15.2 17 | tqdm>=4.66.1 18 | transformers==4.36.2 19 | wandb>=0.16.1 20 | xformers>=0.0.19 -------------------------------------------------------------------------------- /src/py_dreambooth/utils/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import shutil 4 | from typing import Optional 5 | 6 | 7 | def delete_dir_with_name( 8 | root_dir: str, dir_name: str, logger: Optional[logging.Logger] = None 9 | ) -> None: 10 | for root, dirs, _ in os.walk(root_dir, topdown=False): 11 | for name in dirs: 12 | if name == dir_name: 13 | dir_path = os.path.join(root, name) 14 | shutil.rmtree(dir_path) 15 | msg = f"The deleted directory is '{dir_path}'." 16 | if logger is None: 17 | print(msg) 18 | else: 19 | logger.info(msg) 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import setuptools 4 | from typing import AnyStr, List 5 | 6 | 7 | def read_file(path_parts: List[str], encoding: str = "utf-8") -> AnyStr: 8 | """ 9 | Read a file from the project directory 10 | Args: 11 | path_parts: List of parts of the path to the file 12 | encoding: Encoding of the file 13 | Returns: 14 | Content of the file as a string 15 | """ 16 | with open( 17 | os.path.join(os.path.dirname(__file__), *path_parts), "r", encoding=encoding 18 | ) as file: 19 | return file.read() 20 | 21 | 22 | version_contents = read_file(["src", "py_dreambooth", "__version__.py"]) 23 | about = {} 24 | 25 | for key in [ 26 | "__author__", 27 | "__author_email__", 28 | "__description__", 29 | "__license__", 30 | "__title__", 31 | "__url__", 32 | "__version__", 33 | ]: 34 | key_match = re.search(f"{key} = ['\"]([^'\"]+)['\"]", version_contents) 35 | if key_match: 36 | about[key] = key_match.group(1) 37 | 38 | readme = read_file(["README.md"]) 39 | 40 | required_packages = [ 41 | "accelerate>=0.25.0", 42 | "autocrop>=1.3.0", 43 | "awscli>=1.31.12", 44 | "bitsandbytes>=0.41.0", 45 | "deepspeed>=0.12.6", 46 | "diffusers==0.25.0", 47 | "matplotlib>=3.8.0", 48 | "peft==0.7.1", 49 | "pillow>=10.0.1", 50 | "prodigyopt>=1.0", 51 | "safetensors>=0.4.1", 52 | "sagemaker>=2.199.0", 53 | "tensorboard>=2.15.1", 54 | "torch==2.0.1", 55 | "torchvision>=0.15.2", 56 | "tqdm>=4.66.1", 57 | "transformers==4.36.2", 58 | "wandb>=0.16.1", 59 | "xformers>=0.0.19", 60 | ] 61 | extras = { 62 | "test": [ 63 | "black", 64 | "coverage", 65 | "flake8", 66 | "mock", 67 | "pydocstyle", 68 | "pytest", 69 | "pytest-cov", 70 | "tox", 71 | ] 72 | } 73 | 74 | setuptools.setup( 75 | name=about.get("__title__", "unknown"), 76 | version=about.get("__version__", "0.0.0"), 77 | description=about.get("__description__", "unknown"), 78 | long_description=readme, 79 | author=about.get("__author__", "unknown"), 80 | author_email=about.get("__author_email__", "unknown"), 81 | url=about.get("__url__", "unknown"), 82 | packages=setuptools.find_packages("src"), 83 | classifiers=[ 84 | "Development Status :: 3 - Alpha", 85 | "Intended Audience :: Developers", 86 | "Natural Language :: English", 87 | "Programming Language :: Python", 88 | "Programming Language :: Python :: 3", 89 | "Programming Language :: Python :: 3.7", 90 | "Programming Language :: Python :: 3.8", 91 | "Programming Language :: Python :: 3.9", 92 | "Programming Language :: Python :: 3.10", 93 | ], 94 | license=about.get("__license__", "unknown"), 95 | package_dir={"": "src"}, 96 | package_data={"": ["*.txt"]}, 97 | extras_require=extras, 98 | install_requires=required_packages, 99 | long_description_content_type="text/markdown", 100 | python_requires=">=3.7.0", 101 | ) 102 | -------------------------------------------------------------------------------- /src/py_dreambooth/utils/misc.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import shutil 4 | import tarfile 5 | import zipfile 6 | from typing import Optional 7 | 8 | 9 | def compress_dir_to_model_tar_gz( 10 | src_dir: str, 11 | tgt_dir: Optional[str] = None, 12 | tgt_filename: Optional[str] = None, 13 | logger: Optional[logging.Logger] = None, 14 | ) -> None: 15 | """ 16 | Compresses a directory to a tar.gz file. 17 | Args: 18 | src_dir: source directory to compress. 19 | tgt_dir: target directory to compress. 20 | tgt_filename: target filename to compress. 21 | logger: logger to log messages. 22 | """ 23 | if tgt_dir is None: 24 | tgt_dir = src_dir 25 | 26 | if tgt_filename is None: 27 | tgt_filename = "model.tar.gz" 28 | 29 | src_dir = os.path.abspath(src_dir) 30 | tgt_dir = os.path.abspath(tgt_dir) 31 | tgt_file_path = os.path.join(tgt_dir, tgt_filename) 32 | 33 | msg = "The following directories and files will be compressed:" 34 | log_or_print(msg, logger) 35 | 36 | os.chdir(src_dir) 37 | with tarfile.open(tgt_file_path, "w:gz") as file: 38 | for item in os.listdir("."): 39 | log_or_print(f"Adding {item}", logger) 40 | file.add(item, arcname=item) 41 | 42 | os.chdir(tgt_dir) 43 | 44 | 45 | def decompress_file( 46 | src_file_path: str, tgt_dir: Optional[str] = None, compression: Optional[str] = None 47 | ) -> None: 48 | """ 49 | Decompresses a file. 50 | Args: 51 | src_file_path: source file to decompress. 52 | tgt_dir: target directory to decompress. 53 | compression: compression type (zip or tar.gz). 54 | """ 55 | if tgt_dir is None: 56 | tgt_dir = os.path.dirname(src_file_path) 57 | if compression is None: 58 | compression = "zip" 59 | 60 | if compression == "zip": 61 | with zipfile.ZipFile(src_file_path) as file: 62 | file.extractall(tgt_dir) 63 | elif compression == "tar": 64 | with tarfile.open(src_file_path) as file: 65 | file.extractall(tgt_dir) 66 | else: 67 | raise ValueError("The argument, 'compression' should be 'zip or 'tar'.") 68 | 69 | 70 | def delete_dir_with_name( 71 | root_dir: str, dir_name: str, logger: Optional[logging.Logger] = None 72 | ) -> None: 73 | """ 74 | Deletes a directory with a given name. 75 | Args: 76 | root_dir: root directory to delete from. 77 | dir_name: directory name to delete. 78 | logger: logger to log messages. 79 | """ 80 | for root, dirs, _ in os.walk(root_dir, topdown=False): 81 | for name in dirs: 82 | if name == dir_name: 83 | dir_path = os.path.join(root, name) 84 | shutil.rmtree(dir_path) 85 | msg = f"The deleted directory is '{dir_path}'." 86 | log_or_print(msg, logger) 87 | 88 | 89 | def log_or_print(msg: str, logger: Optional[logging.Logger] = None) -> None: 90 | """ 91 | Logs a message or prints it depending on the logger. 92 | Args: 93 | msg: message to log or print. 94 | logger: logger to log messages. 95 | """ 96 | if logger: 97 | logger.info(msg) 98 | else: 99 | print(msg) 100 | -------------------------------------------------------------------------------- /src/py_dreambooth/utils/prompt_helpers.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def make_prompt(subject_name: str, class_name: str) -> str: 5 | """ 6 | Make a prompt sample. 7 | Args: 8 | subject_name: The subject name used for training. 9 | class_name: The class name used for training. 10 | Returns: 11 | The prompt string. 12 | """ 13 | prompt_list = [ 14 | "A hyper-realistic and stunning depiction of {subject_name} {class_name}, capturing the {class_name}'s charisma and charm, trending on Behance, intricate textures, vivid color palette, reminiscent of Alex Ross and Norman Rockwell", 15 | "A drawing of {subject_name} {class_name}, in the style of Mark Lague, hyper-realistic portraits, Sam Spratt, Brent Heighton, captivating gaze, Cyclorama, crisp and clean --ar 69:128 --s 750 --v 5. 2", 16 | "A digital painting of {subject_name} {class_name}, a digital painting, magenta and gray, high contrast illustration, Ryan Hewett, Otto Schmidt", 17 | "Closeup of {subject_name} {class_name} posing in front of a solid dark wall, side profile, uhd, Kodak Ektochrome, lifelike and stunning, cinematic light, volumetric light, Rembrandt lighting", 18 | "A professional photograph of {subject_name} {class_name}, portrait photography, with detailed skin textures, shallow depth of field, Otus 85mm f/1. 4 ZF. 2 Lens, ISO 200, f/4, 1/250s, 8k --ar 2:3 --no blur, distortion, mutation, 3d, 2d, illustration", 19 | "Masterpiece, (beautiful and aesthetic:1. 5), surrealism, highly detailed, a portrait painting of {subject_name} {class_name}, hard brush, minimalist low poly collage illustration, splatter oil paintings effect, city portraits, heavy inking", 20 | "A drawing of {subject_name} {class_name}, black and white, hints of oil painting style, hints of watercolor style, brush strokes, negative white space, crisp, sharp, textured collage, layered fibers, post-impressionist, hyper-realism", 21 | "Portrait of {subject_name} {class_name}, dramatic lighting, illustration by Greg Rutkowski, Yoji Shinkawa, 4k, digital art, concept art, trending on Artstation", 22 | "Portrait of {subject_name} {class_name}, pen and ink, intricate line drawings, by Craig Mullins, Ruan Jia, Kentaro Miura, Greg Rutkowski, Loundraw ", 23 | "A ultra-detailed panting of {subject_name} {class_name}, by Conrad Roset, Greg Rutkowski and Makoto Shinkai, trending on Artstation", 24 | ] 25 | random.shuffle(prompt_list) 26 | for prompt in list( 27 | map( 28 | lambda x: x.format(subject_name=subject_name, class_name=class_name), 29 | prompt_list, 30 | ) 31 | ): 32 | yield prompt 33 | 34 | 35 | def make_negative_prompt() -> str: 36 | """ 37 | Make a negative prompt sample. 38 | Returns: 39 | The negative prompt string. 40 | """ 41 | negative_prompt = """ 42 | (deformed iris, deformed pupils), text, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, 43 | duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, 44 | deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, 45 | gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, 46 | too many fingers, long neck 47 | """ 48 | return ", ".join(map(lambda x: x.strip(), negative_prompt.split(","))) 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Py-Dreambooth 2 | - - - 3 | ![Samples](assets/asset-002.png) 4 | **Py-Dreambooth** is a Python package that makes it easy to create AI avatar images from photos of you, your family, friends, or pets! 5 | 1. Tasks are pre-configured with the most efficient defaults, which greatly streamlines the workload. A number of helper functions are also provided. 6 | 2. This is designed to be modular and extensible to many different models. Currently supported models are the *Stable Diffusion Dreambooth*, *Stable Diffusion Dreambooth LoRA*, and *Stable Diffusion XL Dreambooth LoRA*. 7 | 3. This is designed to give you the flexibility to choose local or cloud resources to train your model and generate images. 8 | 9 | ## ⚙️ How to Install 10 | - - - 11 | ```shell 12 | pip install py-dreambooth 13 | ``` 14 | 15 | ## 🚀 Quick Start 16 | - - - 17 | * Prepare about 10-20 high-quality solo selfie photos (jpg or png) and put them in a specific directory. 18 | * Please run on a machine with a GPU of 16GB or more. (If you're fine-tuning *SDXL*, you'll need 24GB of VRAM.) 19 | ```python 20 | from py_dreambooth.dataset import LocalDataset 21 | from py_dreambooth.model import SdDreamboothModel 22 | from py_dreambooth.trainer import LocalTrainer 23 | from py_dreambooth.utils.image_helpers import display_images 24 | from py_dreambooth.utils.prompt_helpers import make_prompt 25 | 26 | DATA_DIR = "data" # The directory where you put your prepared photos 27 | OUTPUT_DIR = "models" 28 | 29 | dataset = LocalDataset(DATA_DIR) 30 | dataset = dataset.preprocess_images(detect_face=True) 31 | 32 | SUBJECT_NAME = "" 33 | CLASS_NAME = "person" 34 | 35 | model = SdDreamboothModel(subject_name=SUBJECT_NAME, class_name=CLASS_NAME) 36 | trainer = LocalTrainer(output_dir=OUTPUT_DIR) 37 | 38 | predictor = trainer.fit(model, dataset) 39 | 40 | # Use the prompt helper to create an awesome AI avatar! 41 | prompt = next(make_prompt(SUBJECT_NAME, CLASS_NAME)) 42 | 43 | images = predictor.predict( 44 | prompt, height=768, width=512, num_images_per_prompt=2, 45 | ) 46 | 47 | display_images(images, fig_size=10) 48 | ``` 49 | 50 | ## 🏃‍♀️ Tutorials 51 | - - - 52 | * Take a look at the [01-local-tutorial.ipynb](ipynb/01-local-tutorial.ipynb) file to learn how to get it running on your local *Jupyter Notebook*. 53 | * If you're interested in running it with AWS cloud resources, take a look at the [02-aws-tutorial.ipynb](ipynb/02-aws-tutorial.ipynb) file. 54 | * Or, get started right away with the [*Google Colab Notebook*](https://colab.research.google.com/drive/1jIv8210dOFLWXAL8gP3SpMQcLHmSHlVS?usp=sharing) here! 55 | 56 | ## 📚 Documentation 57 | - - - 58 | * Full documentation can be found here: https://py-dreambooth.readthedocs.io. 59 | 60 | ### References 61 | - - - 62 | * [*DreamBooth*: Fine-Tuning Text-to-Image Diffusion Models for Subject-Driven Generation (Paper)](https://arxiv.org/abs/2208.12242) 63 | * [*LoRA*: Low-Rank Adaptation of Large Language Models (Paper)](https://arxiv.org/abs/2106.09685) 64 | * [Fine-Tune Text-to-Image *Stable Diffusion* Models with *Amazon SageMaker JumpStart* (Blog)](https://aws.amazon.com/blogs/machine-learning/fine-tune-text-to-image-stable-diffusion-models-with-amazon-sagemaker-jumpstart/) 65 | * [Training *Stable Diffusion* with *Dreambooth* Using 🧨 *Diffusers* (Blog)](https://huggingface.co/blog/dreambooth) 66 | * [*Diffusers*: *DreamBooth* Training Example](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README.md#dreambooth-training-example) 67 | * [*Diffusers*: *DreamBooth* Training Example for *Stable Diffusion XL* (*SDXL*)](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_sdxl.md) -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth/inference.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import base64 3 | import os 4 | from enum import Enum 5 | from io import BytesIO 6 | from typing import Any, Dict, List, Union 7 | import torch 8 | from diffusers import DDIMScheduler, EulerDiscreteScheduler, StableDiffusionPipeline 9 | from diffusers.models import AutoencoderKL 10 | 11 | 12 | class HfModel(str, Enum): 13 | """ 14 | A class that holds the HuggingFace Hub model IDs. 15 | """ 16 | 17 | SD_VAE = "stabilityai/sd-vae-ft-mse" 18 | 19 | 20 | class SchedulerConfig(Enum): 21 | """ 22 | A class that holds scheduler configuration values for inference. 23 | """ 24 | 25 | DDIM = { 26 | "beta_start": 0.00085, 27 | "beta_end": 0.012, 28 | "beta_schedule": "scaled_linear", 29 | "clip_sample": False, 30 | "set_alpha_to_one": True, 31 | "steps_offset": 1, 32 | } 33 | EULER_DISCRETE = { 34 | "beta_start": 0.00085, 35 | "beta_end": 0.012, 36 | "beta_schedule": "scaled_linear", 37 | "use_karras_sigmas": True, 38 | "steps_offset": 1, 39 | } 40 | 41 | 42 | def model_fn(model_dir: str) -> Any: 43 | """ 44 | A function for SageMaker endpoint that loads the model from the model directory. 45 | Args: 46 | model_dir: The directory where the model is stored. 47 | Returns: 48 | The dictionary of model component names and their instances. 49 | """ 50 | scheduler_type = os.getenv("SCHEDULER_TYPE", "DDIM") 51 | 52 | if scheduler_type.upper() == "DDIM": 53 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 54 | elif scheduler_type.upper() == "EULERDISCRETE": 55 | scheduler = EulerDiscreteScheduler( 56 | **SchedulerConfig.EULER_DISCRETE.value, 57 | ) 58 | else: 59 | scheduler = None 60 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 61 | 62 | pipeline = StableDiffusionPipeline.from_pretrained( 63 | model_dir, 64 | scheduler=scheduler, 65 | revision="fp16", 66 | torch_dtype=torch.float16, 67 | ).to("cuda") 68 | 69 | if ast.literal_eval(os.environ.get("USE_FT_VAE", "False")): 70 | pipeline.vae = AutoencoderKL.from_pretrained( 71 | HfModel.SD_VAE.value, torch_dtype=torch.float16 72 | ).to("cuda") 73 | 74 | return {"pipeline": pipeline} 75 | 76 | 77 | def predict_fn( 78 | data: Dict[str, Union[int, float, str]], model_components: Dict[str, Any] 79 | ) -> Dict[str, List[str]]: 80 | """ 81 | A function for SageMaker endpoint to generate images. 82 | Args: 83 | data: The input data. 84 | model_components: The model components. 85 | Returns: 86 | The dictionary of generated images in base64 encoding format. 87 | """ 88 | prompt = data.pop("prompt", data) 89 | height = data.pop("height", 512) 90 | width = data.pop("width", 512) 91 | num_inference_steps = data.pop("num_inference_steps", 50) 92 | guidance_scale = data.pop("guidance_scale", 7.5) 93 | negative_prompt = data.pop("negative_prompt", None) 94 | num_images_per_prompt = data.pop("num_images_per_prompt", 4) 95 | seed = data.pop("seed", None) 96 | 97 | pipeline = model_components["pipeline"] 98 | 99 | negative_prompt = ( 100 | None 101 | if negative_prompt is None or len(negative_prompt) == 0 102 | else negative_prompt 103 | ) 104 | generator = ( 105 | None if seed is None else torch.Generator(device="cuda").manual_seed(seed) 106 | ) 107 | 108 | generated_images = pipeline( 109 | prompt, 110 | height=height, 111 | width=width, 112 | num_inference_steps=num_inference_steps, 113 | guidance_scale=guidance_scale, 114 | negative_prompt=negative_prompt, 115 | num_images_per_prompt=num_images_per_prompt, 116 | generator=generator, 117 | )["images"] 118 | 119 | encoded_images = [] 120 | for image in generated_images: 121 | buffered = BytesIO() 122 | image.save(buffered, format="JPEG") 123 | encoded_images.append(base64.b64encode(buffered.getvalue()).decode()) 124 | 125 | return {"images": encoded_images} 126 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sd_dreambooth_lora/inference.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import base64 3 | import os 4 | from enum import Enum 5 | from io import BytesIO 6 | from typing import Any, Dict, List, Union 7 | import torch 8 | from diffusers import DDIMScheduler, EulerDiscreteScheduler, StableDiffusionPipeline 9 | from diffusers.models import AutoencoderKL 10 | 11 | 12 | class HfModel(str, Enum): 13 | """ 14 | A class that holds the HuggingFace Hub model IDs. 15 | """ 16 | 17 | SD_V2_1 = "stabilityai/stable-diffusion-2-1-base" 18 | SD_VAE = "stabilityai/sd-vae-ft-mse" 19 | 20 | 21 | class SchedulerConfig(Enum): 22 | """ 23 | A class that holds scheduler configuration values for inference. 24 | """ 25 | 26 | DDIM = { 27 | "beta_start": 0.00085, 28 | "beta_end": 0.012, 29 | "beta_schedule": "scaled_linear", 30 | "clip_sample": False, 31 | "set_alpha_to_one": True, 32 | "steps_offset": 1, 33 | } 34 | EULER_DISCRETE = { 35 | "beta_start": 0.00085, 36 | "beta_end": 0.012, 37 | "beta_schedule": "scaled_linear", 38 | "use_karras_sigmas": True, 39 | "steps_offset": 1, 40 | } 41 | 42 | 43 | def model_fn(model_dir: str) -> Any: 44 | """ 45 | A function for SageMaker endpoint that loads the model from the model directory. 46 | Args: 47 | model_dir: The directory where the model is stored. 48 | Returns: 49 | The dictionary of model component names and their instances. 50 | """ 51 | scheduler_type = os.getenv("SCHEDULER_TYPE", "DDIM") 52 | 53 | if scheduler_type.upper() == "DDIM": 54 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 55 | elif scheduler_type.upper() == "EULERDISCRETE": 56 | scheduler = EulerDiscreteScheduler( 57 | **SchedulerConfig.EULER_DISCRETE.value, 58 | ) 59 | else: 60 | scheduler = None 61 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 62 | 63 | pretrained_model_name_or_path = os.environ.get( 64 | "PRETRAINED_MODEL_NAME_OR_PATH", HfModel.SD_V2_1.value 65 | ) 66 | pipeline = StableDiffusionPipeline.from_pretrained( 67 | pretrained_model_name_or_path, 68 | scheduler=scheduler, 69 | revision="fp16", 70 | torch_dtype=torch.float16, 71 | ).to("cuda") 72 | pipeline.load_lora_weights(model_dir) 73 | 74 | if ast.literal_eval(os.environ.get("USE_FT_VAE", "False")): 75 | pipeline.vae = AutoencoderKL.from_pretrained( 76 | HfModel.SD_VAE.value, torch_dtype=torch.float16 77 | ).to("cuda") 78 | 79 | return {"pipeline": pipeline} 80 | 81 | 82 | def predict_fn( 83 | data: Dict[str, Union[int, float, str]], model_components: Dict[str, Any] 84 | ) -> Dict[str, List[str]]: 85 | """ 86 | A function for SageMaker endpoint to generate images. 87 | Args: 88 | data: The input data. 89 | model_components: The model components. 90 | Returns: 91 | The dictionary of generated images in base64 encoding format. 92 | """ 93 | prompt = data.pop("prompt", data) 94 | height = data.pop("height", 512) 95 | width = data.pop("width", 512) 96 | num_inference_steps = data.pop("num_inference_steps", 50) 97 | guidance_scale = data.pop("guidance_scale", 7.5) 98 | negative_prompt = data.pop("negative_prompt", None) 99 | num_images_per_prompt = data.pop("num_images_per_prompt", 4) 100 | seed = data.pop("seed", None) 101 | cross_attention_scale = data.pop("cross_attention_scale", 1.0) 102 | 103 | pipeline = model_components["pipeline"] 104 | 105 | negative_prompt = ( 106 | None 107 | if negative_prompt is None or len(negative_prompt) == 0 108 | else negative_prompt 109 | ) 110 | generator = ( 111 | None if seed is None else torch.Generator(device="cuda").manual_seed(seed) 112 | ) 113 | 114 | generated_images = pipeline( 115 | prompt, 116 | height=height, 117 | width=width, 118 | num_inference_steps=num_inference_steps, 119 | guidance_scale=guidance_scale, 120 | negative_prompt=negative_prompt, 121 | num_images_per_prompt=num_images_per_prompt, 122 | generator=generator, 123 | cross_attention_kwargs={"scale": cross_attention_scale}, 124 | )["images"] 125 | 126 | encoded_images = [] 127 | for image in generated_images: 128 | buffered = BytesIO() 129 | image.save(buffered, format="JPEG") 130 | encoded_images.append(base64.b64encode(buffered.getvalue()).decode()) 131 | 132 | return {"images": encoded_images} 133 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### JupyterNotebooks template 2 | # gitignore template for Jupyter Notebooks 3 | # website: http://jupyter.org/ 4 | 5 | .ipynb_checkpoints 6 | */.ipynb_checkpoints/* 7 | 8 | # IPython 9 | profile_default/ 10 | ipython_config.py 11 | 12 | # Remove previous ipynb_checkpoints 13 | # git rm -r .ipynb_checkpoints/ 14 | 15 | ### macOS template 16 | # General 17 | .DS_Store 18 | .AppleDouble 19 | .LSOverride 20 | 21 | # Icon must end with two \r 22 | Icon 23 | 24 | # Thumbnails 25 | ._* 26 | 27 | # Files that might appear in the root of a volume 28 | .DocumentRevisions-V100 29 | .fseventsd 30 | .Spotlight-V100 31 | .TemporaryItems 32 | .Trashes 33 | .VolumeIcon.icns 34 | .com.apple.timemachine.donotpresent 35 | 36 | # Directories potentially created on remote AFP share 37 | .AppleDB 38 | .AppleDesktop 39 | Network Trash Folder 40 | Temporary Items 41 | .apdisk 42 | 43 | ### Python template 44 | # Byte-compiled / optimized / DLL files 45 | __pycache__/ 46 | *.py[cod] 47 | *$py.class 48 | 49 | # C extensions 50 | *.so 51 | 52 | # Distribution / packaging 53 | .Python 54 | build/ 55 | develop-eggs/ 56 | dist/ 57 | downloads/ 58 | eggs/ 59 | .eggs/ 60 | lib/ 61 | lib64/ 62 | parts/ 63 | sdist/ 64 | var/ 65 | wheels/ 66 | share/python-wheels/ 67 | *.egg-info/ 68 | .installed.cfg 69 | *.egg 70 | MANIFEST 71 | 72 | # PyInstaller 73 | # Usually these files are written by a python script from a template 74 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 75 | *.manifest 76 | *.spec 77 | 78 | # Installer logs 79 | pip-log.txt 80 | pip-delete-this-directory.txt 81 | 82 | # Unit test / coverage reports 83 | htmlcov/ 84 | .tox/ 85 | .nox/ 86 | .coverage 87 | .coverage.* 88 | .cache 89 | nosetests.xml 90 | coverage.xml 91 | *.cover 92 | *.py,cover 93 | .hypothesis/ 94 | .pytest_cache/ 95 | cover/ 96 | 97 | # Translations 98 | *.mo 99 | *.pot 100 | 101 | # Django stuff: 102 | *.log 103 | local_settings.py 104 | db.sqlite3 105 | db.sqlite3-journal 106 | 107 | # Flask stuff: 108 | instance/ 109 | .webassets-cache 110 | 111 | # Scrapy stuff: 112 | .scrapy 113 | 114 | # Sphinx documentation 115 | docs/_build/ 116 | 117 | # PyBuilder 118 | .pybuilder/ 119 | target/ 120 | 121 | # Jupyter Notebook 122 | .ipynb_checkpoints 123 | 124 | # IPython 125 | profile_default/ 126 | ipython_config.py 127 | 128 | # pyenv 129 | # For a library or package, you might want to ignore these files since the code is 130 | # intended to run in multiple environments; otherwise, check them in: 131 | # .python-version 132 | 133 | # pipenv 134 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 135 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 136 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 137 | # install all needed dependencies. 138 | #Pipfile.lock 139 | 140 | # poetry 141 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 142 | # This is especially recommended for binary packages to ensure reproducibility, and is more 143 | # commonly ignored for libraries. 144 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 145 | #poetry.lock 146 | 147 | # pdm 148 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 149 | #pdm.lock 150 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 151 | # in version control. 152 | # https://pdm.fming.dev/#use-with-ide 153 | .pdm.toml 154 | 155 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 156 | __pypackages__/ 157 | 158 | # Celery stuff 159 | celerybeat-schedule 160 | celerybeat.pid 161 | 162 | # SageMath parsed files 163 | *.sage.py 164 | 165 | # Environments 166 | .env 167 | .venv 168 | env/ 169 | venv/ 170 | ENV/ 171 | env.bak/ 172 | venv.bak/ 173 | 174 | # Spyder project settings 175 | .spyderproject 176 | .spyproject 177 | 178 | # Rope project settings 179 | .ropeproject 180 | 181 | # mkdocs documentation 182 | /site 183 | 184 | # mypy 185 | .mypy_cache/ 186 | .dmypy.json 187 | dmypy.json 188 | 189 | # Pyre type checker 190 | .pyre/ 191 | 192 | # pytype static type analyzer 193 | .pytype/ 194 | 195 | # Cython debug symbols 196 | cython_debug/ 197 | 198 | # PyCharm 199 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 200 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 201 | # and can be added to the global gitignore or merged into this file. For a more nuclear 202 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 203 | .empty/ 204 | .idea/ 205 | 206 | data/ 207 | data_preproc/ 208 | models/ 209 | excl_files/ 210 | -------------------------------------------------------------------------------- /src/py_dreambooth/utils/image_helpers.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import os 3 | from glob import glob 4 | from io import BytesIO 5 | from itertools import chain 6 | from typing import List 7 | import matplotlib.pyplot as plt 8 | from PIL import Image 9 | from autocrop import Cropper 10 | 11 | 12 | def decode_base64_image(image_string: str) -> Image.Image: 13 | """ 14 | Decodes a base64 encoded image string and returns an Image object. 15 | Args: 16 | image_string: The base64 encoded image string. 17 | Returns: 18 | The Image object. 19 | """ 20 | base64_image = base64.b64decode(image_string) 21 | buffer = BytesIO(base64_image) 22 | return Image.open(buffer) 23 | 24 | 25 | def encode_base64_image(file_name: str) -> str: 26 | """ 27 | Encodes an image file to a base64 encoded string. 28 | Args: 29 | file_name: The name of the image file. 30 | Returns: 31 | The base64 encoded string. 32 | """ 33 | with open(file_name, "rb") as image: 34 | image_string = base64.b64encode(bytearray(image.read())).decode() 35 | return image_string 36 | 37 | 38 | def detect_face_and_resize_image( 39 | image_path: str, tgt_width: int, tgt_height: int 40 | ) -> Image: 41 | """ 42 | Detects faces in an image and resizes it to the specified resolution. 43 | Args: 44 | image_path: The path to the image. 45 | tgt_width: The target width of the image. 46 | tgt_height: The target height of the image. 47 | Returns: 48 | The resized Image object. 49 | """ 50 | cropper = Cropper(width=tgt_width, height=tgt_height) 51 | cropped_array = cropper.crop(image_path) 52 | 53 | if cropped_array is None: 54 | msg = f"No faces detected in the image '{image_path.split(os.path.sep)[-1]}'." 55 | raise RuntimeError(msg) 56 | 57 | return Image.fromarray(cropped_array) 58 | 59 | 60 | def display_images( 61 | images: List[Image.Image], 62 | n_columns: int = 3, 63 | fig_size: int = 20, 64 | ) -> None: 65 | """ 66 | Displays a grid of images. 67 | Args: 68 | images: The list of images to display. 69 | n_columns: The number of columns in the grid. 70 | fig_size: The size of the figure (width). 71 | """ 72 | n_columns = min(len(images), n_columns) 73 | quotient, remainder = divmod(len(images), n_columns) 74 | if remainder > 0: 75 | quotient += 1 76 | width, height = images[0].size 77 | plt.figure(figsize=(fig_size, fig_size / n_columns * quotient * height / width)) 78 | 79 | for i, image in enumerate(images): 80 | plt.subplot(quotient, n_columns, i + 1) 81 | plt.axis("off") 82 | plt.imshow(image, aspect="auto") 83 | 84 | plt.subplots_adjust(hspace=0, wspace=0) 85 | plt.show() 86 | 87 | 88 | def get_image_grid(images: List[Image.Image], n_columns: int = 3) -> Image.Image: 89 | """ 90 | Get a grid of images. 91 | Args: 92 | images: The list of images to display. 93 | n_columns: The number of columns in the grid. 94 | Returns: 95 | The grid of images as an Image object. 96 | """ 97 | n_columns = min(len(images), n_columns) 98 | quotient, remainder = divmod(len(images), n_columns) 99 | if remainder > 0: 100 | quotient += 1 101 | width, height = images[0].size 102 | grid = Image.new( 103 | "RGB", 104 | size=( 105 | n_columns * width, 106 | quotient * height, 107 | ), 108 | ) 109 | 110 | for i, image in enumerate(images): 111 | grid.paste(image, box=(i % n_columns * width, i // n_columns * height)) 112 | 113 | return grid 114 | 115 | 116 | def get_image_paths(images_dir: str) -> List[str]: 117 | """ 118 | Get a list of image paths from a directory. 119 | Args: 120 | images_dir: The directory containing the images. 121 | Returns: 122 | A list of image paths. 123 | """ 124 | return list( 125 | chain( 126 | glob(os.path.join(images_dir, "*.[jJ][pP]*[Gg]")), 127 | glob(os.path.join(images_dir, "*.[Pp][Nn][Gg]")), 128 | ) 129 | ) 130 | 131 | 132 | def resize_and_center_crop_image( 133 | image_path: str, tgt_width: int, tgt_height: int 134 | ) -> Image: 135 | """ 136 | Resize and center crop an image. 137 | Args: 138 | image_path: The path to the image. 139 | tgt_width: The target width of the image. 140 | tgt_height: The target height of the image. 141 | Returns: 142 | The resized and centered cropped Image object. 143 | """ 144 | image = Image.open(image_path).convert("RGB") 145 | src_width, src_height = image.size 146 | 147 | if src_width > src_height: 148 | left = (src_width - src_height) / 2 149 | top = 0 150 | right = (src_width + src_height) / 2 151 | bottom = src_height 152 | else: 153 | top = (src_height - src_width) / 2 154 | left = 0 155 | bottom = (src_height + src_width) / 2 156 | right = src_width 157 | 158 | image = image.crop((left, top, right, bottom)) 159 | image = image.resize((tgt_width, tgt_height)) 160 | 161 | return image 162 | 163 | 164 | def validate_dir(tgt_dir: str) -> None: 165 | """ 166 | Validates that a directory exists and is not empty. 167 | Args: 168 | tgt_dir: The directory to validate. 169 | """ 170 | if not os.path.exists(tgt_dir) and len(get_image_paths(tgt_dir)) == 0: 171 | raise ValueError(f"The directory '{tgt_dir}' does not exist or is empty.") 172 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora/inference.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import base64 3 | import os 4 | from enum import Enum 5 | from io import BytesIO 6 | from typing import Any, Dict, List 7 | import torch 8 | from diffusers import DDIMScheduler, DiffusionPipeline, EulerDiscreteScheduler 9 | 10 | 11 | class HfModel(str, Enum): 12 | """ 13 | A class that holds the HuggingFace Hub model IDs. 14 | """ 15 | 16 | SDXL_V1_0 = "stabilityai/stable-diffusion-xl-base-1.0" 17 | SDXL_REFINER_V1_0 = "stabilityai/stable-diffusion-xl-refiner-1.0" 18 | 19 | 20 | class SchedulerConfig(Enum): 21 | """ 22 | A class that holds scheduler configuration values for inference. 23 | """ 24 | 25 | DDIM = { 26 | "beta_start": 0.00085, 27 | "beta_end": 0.012, 28 | "beta_schedule": "scaled_linear", 29 | "clip_sample": False, 30 | "set_alpha_to_one": True, 31 | "steps_offset": 1, 32 | } 33 | EULER_DISCRETE = { 34 | "beta_start": 0.00085, 35 | "beta_end": 0.012, 36 | "beta_schedule": "scaled_linear", 37 | "use_karras_sigmas": True, 38 | "steps_offset": 1, 39 | } 40 | 41 | 42 | def model_fn(model_dir: str) -> Dict[str, Any]: 43 | """ 44 | A function for SageMaker endpoint that loads the model from the model directory. 45 | Args: 46 | model_dir: The directory where the model is stored. 47 | Returns: 48 | The dictionary of model component names and their instances. 49 | """ 50 | 51 | scheduler_type = os.getenv("SCHEDULER_TYPE", "DDIM") 52 | 53 | if scheduler_type.upper() == "DDIM": 54 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 55 | elif scheduler_type.upper() == "EULERDISCRETE": 56 | scheduler = EulerDiscreteScheduler( 57 | **SchedulerConfig.EULER_DISCRETE.value, 58 | ) 59 | else: 60 | scheduler = None 61 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 62 | 63 | pretrained_model_name_or_path = os.environ.get( 64 | "PRETRAINED_MODEL_NAME_OR_PATH", HfModel.SDXL_V1_0.value 65 | ) 66 | pipeline = DiffusionPipeline.from_pretrained( 67 | pretrained_model_name_or_path, 68 | scheduler=scheduler, 69 | revision="fp16", 70 | torch_dtype=torch.float16, 71 | ).to("cuda") 72 | pipeline.load_lora_weights(model_dir) 73 | 74 | if ast.literal_eval(os.environ.get("USE_REFINER", "False")): 75 | refiner = DiffusionPipeline.from_pretrained( 76 | HfModel.SDXL_REFINER_V1_0.value, 77 | text_encoder_2=pipeline.text_encoder_2, 78 | vae=pipeline.vae, 79 | torch_dtype=torch.float16, 80 | variant="fp16", 81 | ).to("cuda") 82 | else: 83 | refiner = None 84 | 85 | return {"pipeline": pipeline, "refiner": refiner} 86 | 87 | 88 | def predict_fn( 89 | data: Dict[str, Any], model_components: Dict[str, Any] 90 | ) -> Dict[str, List[str]]: 91 | """ 92 | A function for SageMaker endpoint to generate images. 93 | Args: 94 | data: The input data. 95 | model_components: The model components. 96 | Returns: 97 | The dictionary of generated images in base64 encoding format. 98 | """ 99 | prompt = data.pop("prompt", "") 100 | height = data.pop("height", 512) 101 | width = data.pop("width", 512) 102 | num_inference_steps = data.pop("num_inference_steps", 50) 103 | guidance_scale = data.pop("guidance_scale", 7.5) 104 | negative_prompt = data.pop("negative_prompt", None) 105 | num_images_per_prompt = data.pop("num_images_per_prompt", 4) 106 | seed = data.pop("seed", 42) 107 | high_noise_frac = data.pop("high_noise_frac", 0.7) 108 | cross_attention_scale = data.pop("cross_attention_scale", 1.0) 109 | 110 | pipeline, refiner = model_components["model"], model_components["refiner"] 111 | 112 | negative_prompt = ( 113 | None 114 | if negative_prompt is None or len(negative_prompt) == 0 115 | else negative_prompt 116 | ) 117 | generator = ( 118 | None if seed is None else torch.Generator(device="cuda").manual_seed(seed) 119 | ) 120 | 121 | if refiner: 122 | image = pipeline( 123 | prompt=prompt, 124 | height=height, 125 | width=width, 126 | num_inference_steps=num_inference_steps, 127 | guidance_scale=guidance_scale, 128 | negative_prompt=negative_prompt, 129 | num_images_per_prompt=num_images_per_prompt, 130 | denoising_end=high_noise_frac, 131 | generator=generator, 132 | output_type="latent", 133 | cross_attention_kwargs={"scale": cross_attention_scale}, 134 | )["images"] 135 | generated_images = refiner( 136 | prompt=prompt, 137 | image=image, 138 | num_inference_steps=num_inference_steps, 139 | denoising_start=high_noise_frac, 140 | )["images"] 141 | 142 | else: 143 | generated_images = pipeline( 144 | prompt=prompt, 145 | height=height, 146 | width=width, 147 | num_inference_steps=num_inference_steps, 148 | guidance_scale=guidance_scale, 149 | negative_prompt=negative_prompt, 150 | num_images_per_prompt=num_images_per_prompt, 151 | generator=generator, 152 | cross_attention_kwargs={"scale": cross_attention_scale}, 153 | )["images"] 154 | 155 | encoded_images = [] 156 | for image in generated_images: 157 | buffered = BytesIO() 158 | image.save(buffered, format="JPEG") 159 | encoded_images.append(base64.b64encode(buffered.getvalue()).decode()) 160 | 161 | return {"images": encoded_images} 162 | -------------------------------------------------------------------------------- /src/py_dreambooth/utils/aws_helpers.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | from typing import Optional, List 5 | import boto3 6 | from .misc import log_or_print 7 | 8 | 9 | def create_bucket_if_not_exists( 10 | boto_session: boto3.Session, 11 | region_name: str, 12 | logger: Optional[logging.Logger] = None, 13 | ) -> str: 14 | """ 15 | Create a S3 bucket if it does not exist. 16 | Args: 17 | boto_session: The boto session to use for AWS interactions. 18 | region_name: AWS region name. 19 | logger: The logger to use for logging messages. 20 | Returns: 21 | The name of the S3 bucket created. 22 | """ 23 | s3_client = boto_session.client("s3") 24 | sts_client = boto_session.client("sts") 25 | account_id = sts_client.get_caller_identity()["Account"] 26 | 27 | bucket_name = f"sagemaker-{region_name}-{account_id}" 28 | if ( 29 | s3_client.head_bucket(Bucket=bucket_name)["ResponseMetadata"]["HTTPStatusCode"] 30 | == 404 31 | ): 32 | s3_client.create_bucket(Bucket=bucket_name) 33 | msg = f"The following S3 bucket was created: {bucket_name}" 34 | log_or_print(msg, logger) 35 | 36 | else: 37 | msg = f"The following S3 bucket was found: {bucket_name}" 38 | log_or_print(msg, logger) 39 | 40 | return bucket_name 41 | 42 | 43 | def create_role_if_not_exists( 44 | boto_session: boto3.Session, 45 | region_name: str, 46 | logger: Optional[logging.Logger] = None, 47 | ) -> str: 48 | """ 49 | Create an IAM role if it does not exist. 50 | Args: 51 | boto_session: The boto session to use for AWS interactions. 52 | region_name: AWS region name. 53 | logger: The logger to use for logging messages. 54 | Returns: 55 | The name of the IAM role created. 56 | """ 57 | iam_client = boto_session.client("iam") 58 | 59 | role_name = f"AmazonSageMaker-ExecutionRole-{region_name}" 60 | try: 61 | role = iam_client.get_role(RoleName=role_name) 62 | msg = f"The following IAM role was found: {role['Role']['Arn']}" 63 | 64 | except iam_client.exceptions.NoSuchEntityException: 65 | assume_role_policy_document = { 66 | "Version": "2012-10-17", 67 | "Statement": [ 68 | { 69 | "Effect": "Allow", 70 | "Principal": {"Service": "sagemaker.amazonaws.com"}, 71 | "Action": "sts:AssumeRole", 72 | } 73 | ], 74 | } 75 | role = iam_client.create_role( 76 | RoleName=role_name, 77 | AssumeRolePolicyDocument=json.dumps(assume_role_policy_document), 78 | Description="SageMaker Execution Role", 79 | ) 80 | policy_arn = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess" 81 | iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn) 82 | 83 | msg = f"The following IAM role was created: {role['Role']['Arn']}" 84 | 85 | log_or_print(msg, logger) 86 | return role_name 87 | 88 | 89 | def delete_files_in_s3( 90 | boto_session: boto3.Session, 91 | bucket_name: str, 92 | prefix: str, 93 | logger: Optional[logging.Logger] = None, 94 | ) -> None: 95 | """ 96 | Delete files in a S3 bucket. 97 | Args: 98 | boto_session: The boto session to use for AWS interactions. 99 | bucket_name: The name of the S3 bucket. 100 | prefix: The S3 prefix of the files to delete. 101 | logger: The logger to use for logging messages. 102 | """ 103 | s3_resource = boto_session.resource("s3") 104 | bucket = s3_resource.Bucket(bucket_name) 105 | 106 | for obj in bucket.objects.filter(Prefix=prefix): 107 | s3_resource.Object(bucket_name, obj.key).delete() 108 | msg = f"The 's3://{bucket_name}/{obj.key}' file has been deleted." 109 | log_or_print(msg, logger) 110 | 111 | 112 | def make_s3_uri(bucket: str, prefix: str, filename: Optional[str] = None) -> str: 113 | """ 114 | Make a S3 URI. 115 | Args: 116 | bucket: The S3 bucket name. 117 | prefix: The S3 prefix. 118 | filename: The filename. 119 | Returns: 120 | The S3 URI. 121 | """ 122 | prefix = prefix if filename is None else os.path.join(prefix, filename) 123 | return f"s3://{bucket}/{prefix}" 124 | 125 | 126 | def upload_dir_to_s3( 127 | boto_session: boto3.Session, 128 | local_dir: str, 129 | bucket_name: str, 130 | prefix: str, 131 | file_ext_to_excl: Optional[List[str]] = None, 132 | public_readable: bool = False, 133 | logger: Optional[logging.Logger] = None, 134 | ) -> None: 135 | """ 136 | Upload a directory to a S3 bucket. 137 | Args: 138 | boto_session: The boto session to use for AWS interactions. 139 | local_dir: The local directory to upload. 140 | bucket_name: The name of the S3 bucket. 141 | prefix: The S3 prefix. 142 | file_ext_to_excl: The file extensions to exclude from the upload. 143 | public_readable: Whether the files should be public readable. 144 | logger: The logger to use for logging messages. 145 | """ 146 | s3_client = boto_session.client("s3") 147 | file_ext_to_excl = [] if file_ext_to_excl is None else file_ext_to_excl 148 | extra_args = {"ACL": "public-read"} if public_readable else {} 149 | 150 | for root, _, files in os.walk(local_dir): 151 | for file in files: 152 | if file.split(".")[-1] not in file_ext_to_excl: 153 | s3_client.upload_file( 154 | os.path.join(root, file), 155 | bucket_name, 156 | f"{prefix}/{file}", 157 | ExtraArgs=extra_args, 158 | ) 159 | msg = f"The '{file}' file has been uploaded to 's3://{bucket_name}/{prefix}/{file}'." 160 | log_or_print(msg, logger) 161 | -------------------------------------------------------------------------------- /src/py_dreambooth/scripts/infer/sdxl_dreambooth_lora_advanced/inference.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import base64 3 | import os 4 | from enum import Enum 5 | from io import BytesIO 6 | from typing import Any, Dict, List 7 | import torch 8 | from diffusers import DDIMScheduler, DiffusionPipeline, EulerDiscreteScheduler 9 | from safetensors.torch import load_file 10 | 11 | 12 | class HfModel(str, Enum): 13 | """ 14 | A class that holds the HuggingFace Hub model IDs. 15 | """ 16 | 17 | SDXL_V1_0 = "stabilityai/stable-diffusion-xl-base-1.0" 18 | SDXL_REFINER_V1_0 = "stabilityai/stable-diffusion-xl-refiner-1.0" 19 | 20 | 21 | class SchedulerConfig(Enum): 22 | """ 23 | A class that holds scheduler configuration values for inference. 24 | """ 25 | 26 | DDIM = { 27 | "beta_start": 0.00085, 28 | "beta_end": 0.012, 29 | "beta_schedule": "scaled_linear", 30 | "clip_sample": False, 31 | "set_alpha_to_one": True, 32 | "steps_offset": 1, 33 | } 34 | EULER_DISCRETE = { 35 | "beta_start": 0.00085, 36 | "beta_end": 0.012, 37 | "beta_schedule": "scaled_linear", 38 | "use_karras_sigmas": True, 39 | "steps_offset": 1, 40 | } 41 | 42 | 43 | def model_fn(model_dir: str) -> Dict[str, Any]: 44 | """ 45 | A function for SageMaker endpoint that loads the model from the model directory. 46 | Args: 47 | model_dir: The directory where the model is stored. 48 | Returns: 49 | The dictionary of model component names and their instances. 50 | """ 51 | 52 | scheduler_type = os.getenv("SCHEDULER_TYPE", "DDIM") 53 | 54 | if scheduler_type.upper() == "DDIM": 55 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 56 | elif scheduler_type.upper() == "EULERDISCRETE": 57 | scheduler = EulerDiscreteScheduler( 58 | **SchedulerConfig.EULER_DISCRETE.value, 59 | ) 60 | else: 61 | scheduler = None 62 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 63 | 64 | pretrained_model_name_or_path = os.environ.get( 65 | "PRETRAINED_MODEL_NAME_OR_PATH", HfModel.SDXL_V1_0.value 66 | ) 67 | pipeline = DiffusionPipeline.from_pretrained( 68 | pretrained_model_name_or_path, 69 | scheduler=scheduler, 70 | revision="fp16", 71 | torch_dtype=torch.float16, 72 | ).to("cuda") 73 | 74 | if ast.literal_eval(os.environ.get("TRAIN_TEXT_ENCODER_TI", "True")): 75 | state_dict = load_file(os.path.join(model_dir, "models_emb.safetensors")) 76 | pipeline.load_textual_inversion( 77 | state_dict["clip_l"], 78 | token=["", ""], 79 | text_encoder=pipeline.text_encoder, 80 | tokenizer=pipeline.tokenizer, 81 | ) 82 | pipeline.load_textual_inversion( 83 | state_dict["clip_g"], 84 | token=["", ""], 85 | text_encoder=pipeline.text_encoder_2, 86 | tokenizer=pipeline.tokenizer_2, 87 | ) 88 | pipeline.load_lora_weights(model_dir) 89 | 90 | if ast.literal_eval(os.environ.get("USE_REFINER", "False")): 91 | refiner = DiffusionPipeline.from_pretrained( 92 | HfModel.SDXL_REFINER_V1_0.value, 93 | text_encoder_2=pipeline.text_encoder_2, 94 | vae=pipeline.vae, 95 | torch_dtype=torch.float16, 96 | variant="fp16", 97 | ).to("cuda") 98 | else: 99 | refiner = None 100 | 101 | return {"pipeline": pipeline, "refiner": refiner} 102 | 103 | 104 | def predict_fn( 105 | data: Dict[str, Any], model_components: Dict[str, Any] 106 | ) -> Dict[str, List[str]]: 107 | """ 108 | A function for SageMaker endpoint to generate images. 109 | Args: 110 | data: The input data. 111 | model_components: The model components. 112 | Returns: 113 | The dictionary of generated images in base64 encoding format. 114 | """ 115 | prompt = data.pop("prompt", "") 116 | height = data.pop("height", 512) 117 | width = data.pop("width", 512) 118 | num_inference_steps = data.pop("num_inference_steps", 50) 119 | guidance_scale = data.pop("guidance_scale", 7.5) 120 | negative_prompt = data.pop("negative_prompt", None) 121 | num_images_per_prompt = data.pop("num_images_per_prompt", 4) 122 | seed = data.pop("seed", 42) 123 | high_noise_frac = data.pop("high_noise_frac", 0.7) 124 | cross_attention_scale = data.pop("cross_attention_scale", 1.0) 125 | 126 | pipeline, refiner = model_components["model"], model_components["refiner"] 127 | 128 | negative_prompt = ( 129 | None 130 | if negative_prompt is None or len(negative_prompt) == 0 131 | else negative_prompt 132 | ) 133 | generator = ( 134 | None if seed is None else torch.Generator(device="cuda").manual_seed(seed) 135 | ) 136 | 137 | if refiner: 138 | image = pipeline( 139 | prompt=prompt, 140 | height=height, 141 | width=width, 142 | num_inference_steps=num_inference_steps, 143 | guidance_scale=guidance_scale, 144 | negative_prompt=negative_prompt, 145 | num_images_per_prompt=num_images_per_prompt, 146 | denoising_end=high_noise_frac, 147 | generator=generator, 148 | output_type="latent", 149 | cross_attention_kwargs={"scale": cross_attention_scale}, 150 | )["images"] 151 | generated_images = refiner( 152 | prompt=prompt, 153 | image=image, 154 | num_inference_steps=num_inference_steps, 155 | denoising_start=high_noise_frac, 156 | )["images"] 157 | 158 | else: 159 | generated_images = pipeline( 160 | prompt=prompt, 161 | height=height, 162 | width=width, 163 | num_inference_steps=num_inference_steps, 164 | guidance_scale=guidance_scale, 165 | negative_prompt=negative_prompt, 166 | num_images_per_prompt=num_images_per_prompt, 167 | generator=generator, 168 | cross_attention_kwargs={"scale": cross_attention_scale}, 169 | )["images"] 170 | 171 | encoded_images = [] 172 | for image in generated_images: 173 | buffered = BytesIO() 174 | image.save(buffered, format="JPEG") 175 | encoded_images.append(base64.b64encode(buffered.getvalue()).decode()) 176 | 177 | return {"images": encoded_images} 178 | -------------------------------------------------------------------------------- /src/py_dreambooth/dataset.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import shutil 4 | from enum import Enum 5 | from typing import Optional 6 | import boto3 7 | from huggingface_hub import snapshot_download 8 | from tqdm import tqdm 9 | from .utils.aws_helpers import ( 10 | create_bucket_if_not_exists, 11 | delete_files_in_s3, 12 | make_s3_uri, 13 | upload_dir_to_s3, 14 | ) 15 | from .utils.image_helpers import ( 16 | detect_face_and_resize_image, 17 | get_image_paths, 18 | resize_and_center_crop_image, 19 | validate_dir, 20 | ) 21 | from .utils.misc import log_or_print 22 | 23 | 24 | class HfRepoId(str, Enum): 25 | """ 26 | A class that holds the HuggingFace Hub repository ID. 27 | """ 28 | 29 | DOG_EXAMPLE = "diffusers/dog-example" 30 | FACE_EXAMPLE = "multimodalart/faces-prior-preservation" 31 | 32 | 33 | class LocalDataset: 34 | """ 35 | A class that represents a local dataset. 36 | Args: 37 | data_dir: The name of the local directory containing the images. 38 | you want the model to train on. 39 | logger: The logger to use for logging messages. 40 | """ 41 | 42 | def __init__(self, data_dir: str, logger: Optional[logging.Logger] = None) -> None: 43 | self.raw_data_dir = data_dir 44 | self.preproc_data_dir = data_dir 45 | self.resolution = None 46 | self.logger = logger 47 | 48 | os.makedirs(self.raw_data_dir, exist_ok=True) 49 | 50 | def __len__(self) -> int: 51 | return len(get_image_paths(self.preproc_data_dir)) 52 | 53 | def download_examples(self, repo_id: Optional[str] = None) -> "LocalDataset": 54 | """ 55 | Download a dataset from the HuggingFace Hub to the local directory. 56 | Args: 57 | repo_id: The ID of the HuggingFace Hub repository to download. 58 | Returns: 59 | The local dataset instance. 60 | """ 61 | shutil.rmtree(self.raw_data_dir) 62 | 63 | if repo_id is None: 64 | repo_id = HfRepoId.DOG_EXAMPLE.value 65 | 66 | snapshot_download( 67 | repo_id, 68 | local_dir=self.raw_data_dir, 69 | repo_type="dataset", 70 | ignore_patterns=".gitattributes", 71 | ) 72 | 73 | msg = f"The dataset '{repo_id}' has been downloaded from the HuggingFace Hub to '{self.raw_data_dir}'." 74 | log_or_print(msg, self.logger) 75 | 76 | return self 77 | 78 | def download_class_examples(self, repo_id: Optional[str] = None) -> "LocalDataset": 79 | """ 80 | Download a class dataset from the HuggingFace Hub to the local directory. 81 | Args: 82 | repo_id: The ID of the HuggingFace Hub repository to download. 83 | Returns: 84 | The local dataset instance. 85 | """ 86 | raw_class_data_dir = os.path.join(self.preproc_data_dir, "class") 87 | 88 | if os.path.exists(raw_class_data_dir): 89 | shutil.rmtree(raw_class_data_dir) 90 | 91 | os.makedirs(raw_class_data_dir) 92 | 93 | if repo_id is None: 94 | repo_id = HfRepoId.FACE_EXAMPLE.value 95 | 96 | snapshot_download( 97 | repo_id, 98 | local_dir=raw_class_data_dir, 99 | repo_type="dataset", 100 | ignore_patterns=".gitattributes", 101 | ) 102 | 103 | msg = f"The dataset '{repo_id}' has been downloaded from the HuggingFace Hub to '{raw_class_data_dir}'." 104 | log_or_print(msg, self.logger) 105 | 106 | return self 107 | 108 | def preprocess_images( 109 | self, resolution: int = 1024, detect_face: bool = False 110 | ) -> "LocalDataset": 111 | """ 112 | Preprocess (crop and resize) images in a local directory. 113 | Args: 114 | resolution: The resolution to resize the images to. 115 | detect_face: Whether to detect faces and crop around them. If not, crop by center. 116 | Returns: 117 | The local dataset instance. 118 | """ 119 | validate_dir(self.raw_data_dir) 120 | 121 | self.resolution = resolution 122 | self.preproc_data_dir = "_".join([self.raw_data_dir, "preproc"]) 123 | 124 | if os.path.exists(self.preproc_data_dir): 125 | shutil.rmtree(self.preproc_data_dir) 126 | 127 | os.makedirs(self.preproc_data_dir) 128 | 129 | preprocess_func = ( 130 | detect_face_and_resize_image 131 | if detect_face 132 | else resize_and_center_crop_image 133 | ) 134 | 135 | raw_image_paths = get_image_paths(self.raw_data_dir) 136 | msg = f"A total of {len(raw_image_paths)} images were found." 137 | log_or_print(msg, self.logger) 138 | 139 | for image_path in tqdm(raw_image_paths): 140 | try: 141 | preproc_image = preprocess_func( 142 | image_path, self.resolution, self.resolution 143 | ) 144 | preproc_image.save( 145 | os.path.join( 146 | self.preproc_data_dir, image_path.split(os.path.sep)[-1] 147 | ) 148 | ) 149 | 150 | except RuntimeError as error: 151 | log_or_print(str(error), self.logger) 152 | continue 153 | 154 | num_preproc_images = len(self) 155 | if num_preproc_images == 0: 156 | raise RuntimeError("There are no preprocessed images.") 157 | 158 | msg = f"A total of {num_preproc_images} images were preprocessed and stored in the path '{self.preproc_data_dir}'." 159 | log_or_print(msg, self.logger) 160 | 161 | return self 162 | 163 | 164 | class AWSDataset(LocalDataset): 165 | """ 166 | A class that represents an AWS dataset. 167 | Args: 168 | data_dir: The name of the local directory containing the images you want the model to train on. 169 | boto_session: The Boto session to use for AWS interactions. 170 | project_name: The name of the project, which will be used for task names, save locations, etc. 171 | s3_bucket_name: The name of the S3 bucket to use for the dataset. 172 | logger: The logger to use for logging messages. 173 | """ 174 | 175 | def __init__( 176 | self, 177 | data_dir: str, 178 | boto_session: boto3.Session, 179 | project_name: Optional[str] = None, 180 | s3_bucket_name: Optional[str] = None, 181 | logger: Optional[logging.Logger] = None, 182 | ) -> None: 183 | super().__init__(data_dir, logger) 184 | 185 | self.boto_session = boto_session 186 | self.project_name = "py-dreambooth" if project_name is None else project_name 187 | self.dataset_prefix = f"{self.project_name}/dataset" 188 | 189 | self.bucket_name = ( 190 | create_bucket_if_not_exists( 191 | self.boto_session, self.boto_session.region_name, logger=self.logger 192 | ) 193 | if s3_bucket_name is None 194 | else s3_bucket_name 195 | ) 196 | 197 | def get_s3_model_uri(self) -> str: 198 | """ 199 | Get the S3 URI for the model artifact. 200 | Returns: 201 | The S3 URI. 202 | """ 203 | return make_s3_uri( 204 | self.bucket_name, f"{self.project_name}/model", "model.tar.gz" 205 | ) 206 | 207 | def upload_images(self) -> "AWSDataset": 208 | """ 209 | Upload images to the S3 bucket. 210 | Returns: 211 | The AWS dataset instance. 212 | """ 213 | delete_files_in_s3( 214 | self.boto_session, 215 | self.bucket_name, 216 | self.dataset_prefix, 217 | logger=self.logger, 218 | ) 219 | 220 | validate_dir(self.preproc_data_dir) 221 | 222 | upload_dir_to_s3( 223 | self.boto_session, 224 | self.preproc_data_dir, 225 | self.bucket_name, 226 | self.dataset_prefix, 227 | logger=self.logger, 228 | ) 229 | 230 | return self 231 | -------------------------------------------------------------------------------- /ipynb/01-local-tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "021678ce-4224-4e3c-849f-14047092077e", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "%load_ext autoreload\n", 11 | "%autoreload 2" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "id": "64e87323-9b72-494c-bdd5-34491a0d77ea", 17 | "metadata": {}, 18 | "source": [ 19 | "# Using *Py-Dreambooth* on a Local Jupyter Notebook 🧑‍💻\n", 20 | "* Use *Py-Dreambooth* to easily create AI avatar images from photos of you, your family, friends, or pets!\n", 21 | "* Please run on a machine with a GPU of 16GB or more.\n", 22 | "\n", 23 | "## Install the package\n", 24 | "* Install the *Py-Dreambooth* python package as shown below." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "id": "77d79633-5a92-4655-9622-cdd8629e1f92", 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "!pip install -q py_dreambooth" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "id": "66e7a6fd-b927-4544-9410-3b8eeeecbf5b", 40 | "metadata": {}, 41 | "source": [ 42 | "## Import modules\n", 43 | "* There are several types of model classes, but you'll be using the most basic model, the Stable Diffusion Dreambooth model `SDDreamboothModel`, but you don't need to worry about that right now. 🤷‍♂️" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "id": "2b514aea-f747-453c-9b30-6c33d970a6f2", 50 | "metadata": { 51 | "tags": [] 52 | }, 53 | "outputs": [], 54 | "source": [ 55 | "from py_dreambooth.dataset import LocalDataset\n", 56 | "from py_dreambooth.model import SdDreamboothModel\n", 57 | "from py_dreambooth.predictor import LocalPredictor\n", 58 | "from py_dreambooth.trainer import LocalTrainer\n", 59 | "from py_dreambooth.utils.image_helpers import display_images\n", 60 | "from py_dreambooth.utils.prompt_helpers import make_prompt" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "55c7890e-071f-4c54-b7f5-6be1fe34a348", 66 | "metadata": {}, 67 | "source": [ 68 | "## Prepare your data 📸" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "id": "39413c84-4909-4d7e-bc6f-e4929889790c", 75 | "metadata": { 76 | "tags": [] 77 | }, 78 | "outputs": [], 79 | "source": [ 80 | "DATA_DIR = \"data\" # the directory with photos for the model to train on\n", 81 | "OUTPUT_DIR = \"models\" # The directory where the trained model files will be located\n", 82 | "\n", 83 | "dataset = LocalDataset(DATA_DIR)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "id": "2373c05b-1d47-4d0c-8318-0cf6a4721030", 89 | "metadata": {}, 90 | "source": [ 91 | "* Very important! In the `DATA_DIR` defined above, put the pictures (jpg or png) of the subject you want to train.\n", 92 | "* For this task, you'll need about 10 to 20 solo, high-quality selfies taken with different backgrounds, lighting, and facial expressions. I think a great example can be found in [Joe Penna's GitHub repository](https://github.com/JoePenna/Dreambooth-Stable-Diffusion).\n", 93 | "\n", 94 | "![Samples](../assets/asset-001.png)\n", 95 | "* Use the following image processing method to crop the images into a square centered on the face. If the subject the model is trying to learn is not a person (for example, a dog), set the `detect_face` argument to `False`. " 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "id": "5c5fc9e1c26241ff", 102 | "metadata": { 103 | "collapsed": false, 104 | "jupyter": { 105 | "outputs_hidden": false 106 | } 107 | }, 108 | "outputs": [], 109 | "source": [ 110 | "dataset = dataset.preprocess_images(detect_face=True)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "id": "9240698c-426f-44f4-89a4-c4e9cc8f6c22", 116 | "metadata": {}, 117 | "source": [ 118 | "## Train the model 🤖\n", 119 | "* Now it's time to train the model! Tell the model the name of the subject you want to train (e.g., Joe) and the class it belongs to. \n", 120 | "* When defining a model, one of the important arguments is how many iterations to train, or `max_train_steps`. It is generally accepted that 800 to 1200 steps are appropriate for a person, and 200 to 400 steps are appropriate for a non-human animal. The default value is 100 times the number of photos you have. You don't need to worry about that right now 🤷‍♂️, but if you don't like the results of the generated image below, this is the first parameter to adjust." 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "id": "151d05e7-5acb-4a53-9dff-b21e6f244b69", 127 | "metadata": { 128 | "tags": [] 129 | }, 130 | "outputs": [], 131 | "source": [ 132 | "SUBJECT_NAME = \"sks\" # The name of the subject you want to learn\n", 133 | "CLASS_NAME = \"person\" # The class to which the subject you want to learn belongs\n", 134 | "\n", 135 | "model = SdDreamboothModel(\n", 136 | " subject_name=SUBJECT_NAME,\n", 137 | " class_name=CLASS_NAME,\n", 138 | " # max_train_steps=1000,\n", 139 | ")\n", 140 | "\n", 141 | "trainer = LocalTrainer(output_dir=OUTPUT_DIR)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "markdown", 146 | "id": "a44f878e-762e-4eef-8f02-3a9708715245", 147 | "metadata": {}, 148 | "source": [ 149 | "* Model training time can be as short as a few tens of minutes or as long as several hours." 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "id": "85bacd28-e07e-4a05-bf5f-b60796568636", 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "%%time\n", 160 | "predictor = trainer.fit(model, dataset)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "markdown", 165 | "id": "d4113be1-b8ea-4319-b269-e180837e12fe", 166 | "metadata": {}, 167 | "source": [ 168 | "* If you restart the notebook kernel and then want to reload the models you've already trained, you can do so as follows." 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "id": "4b013e17-d669-46dd-abc2-043a22e9a5b9", 175 | "metadata": {}, 176 | "outputs": [], 177 | "source": [ 178 | "# predictor = LocalPredictor(model, OUTPUT_DIR)" 179 | ] 180 | }, 181 | { 182 | "cell_type": "markdown", 183 | "id": "7a508d27-a04b-4c38-8012-e41c68faac41", 184 | "metadata": {}, 185 | "source": [ 186 | "## Create images as you wish! 💃\n", 187 | "* Use the prompts to create any image you like. The prompt text should contain the subject name and class name defined above.\n", 188 | "* Having trouble coming up with a good prompt? Don't worry. You can use the `make_prompt` function to generate a curated prompt at random. Check this out. 🙆‍♀️\n", 189 | "* Creating great images takes patience. Play around with the prompts, but if the quality of the generation itself is problematic, you may need to retrain with better data and more appropriate training parameters." 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "id": "3b27d3a4-d608-4c64-8d9c-28dd4e5326d1", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "%%time\n", 200 | "prompt = f\"A photo of {SUBJECT_NAME} {CLASS_NAME} with Eiffel Tower in the background\"\n", 201 | "# prompt = next(make_prompt(SUBJECT_NAME, CLASS_NAME))\n", 202 | "\n", 203 | "print(f\"The prompt is as follows:\\n{prompt}\")\n", 204 | "\n", 205 | "images = predictor.predict(\n", 206 | " prompt,\n", 207 | " height=768,\n", 208 | " width=512,\n", 209 | " num_images_per_prompt=2,\n", 210 | ")\n", 211 | "\n", 212 | "display_images(images, fig_size=10)" 213 | ] 214 | } 215 | ], 216 | "metadata": { 217 | "kernelspec": { 218 | "display_name": "Python 3 (ipykernel)", 219 | "language": "python", 220 | "name": "python3" 221 | }, 222 | "language_info": { 223 | "codemirror_mode": { 224 | "name": "ipython", 225 | "version": 3 226 | }, 227 | "file_extension": ".py", 228 | "mimetype": "text/x-python", 229 | "name": "python", 230 | "nbconvert_exporter": "python", 231 | "pygments_lexer": "ipython3", 232 | "version": "3.10.13" 233 | } 234 | }, 235 | "nbformat": 4, 236 | "nbformat_minor": 5 237 | } 238 | -------------------------------------------------------------------------------- /ipynb/02-aws-tutorial.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "53811d2a-9013-4de2-8cd8-1ab80bccf133", 7 | "metadata": { 8 | "tags": [] 9 | }, 10 | "outputs": [], 11 | "source": [ 12 | "%load_ext autoreload\n", 13 | "%autoreload 2" 14 | ] 15 | }, 16 | { 17 | "cell_type": "markdown", 18 | "id": "da1b5bac-2d13-47cc-bcb5-f08ce8e531dd", 19 | "metadata": {}, 20 | "source": [ 21 | "# Using *Py-Dreambooth* with AWS Cloud Resources 🧑‍💻\n", 22 | "* Use *Py-Dreambooth* to easily create AI avatar images from photos of you, your family, friends, or pets!\n", 23 | "* First, you need to set up your AWS configuration and credentials files. Refer to [this document](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html).\n", 24 | "* Additionally, by default, the `ml.g4dn.xlarge` processing job and endpoint deployment will run. If you don't have enough quota, please increase it.\n", 25 | "\n", 26 | "## Install the package\n", 27 | "* Install the *Py-Dreambooth* python package as shown below." 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": null, 33 | "id": "65afcca8-f239-4057-836d-011a7784f93d", 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "!pip install -q py-dreambooth" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "id": "38934d41-8e95-4d96-9bfb-74cd1ab69e3a", 43 | "metadata": {}, 44 | "source": [ 45 | "## Import modules\n", 46 | "* There are several types of model classes, but you'll be using the most basic model, the Stable Diffusion Dreambooth LoRA model `SDDreamboothLoraModel`, but you don't need to worry about that right now. 🤷‍♂️" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "id": "4ceea878-1858-41ae-bbc2-d41be276ab40", 53 | "metadata": { 54 | "tags": [] 55 | }, 56 | "outputs": [], 57 | "source": [ 58 | "import boto3\n", 59 | "import sys\n", 60 | "from py_dreambooth.dataset import AWSDataset\n", 61 | "from py_dreambooth.model import SdDreamboothLoraModel\n", 62 | "from py_dreambooth.predictor import AWSPredictor\n", 63 | "from py_dreambooth.trainer import AWSTrainer\n", 64 | "from py_dreambooth.utils.image_helpers import display_images\n", 65 | "from py_dreambooth.utils.prompt_helpers import make_prompt" 66 | ] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "id": "299e0929-e89b-4b8e-835e-8d6666ad87f0", 71 | "metadata": {}, 72 | "source": [ 73 | "## Prepare your data 📸\n", 74 | "* The boto3 session should be created appropriately for the AWS profile or access key information you set up previously. You'll use the default profile here." 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "id": "7e2e17af-b416-4be1-a07f-7db6c4e24410", 81 | "metadata": { 82 | "tags": [] 83 | }, 84 | "outputs": [], 85 | "source": [ 86 | "DATA_DIR = \"data\" # the directory with photos for the model to train on\n", 87 | "\n", 88 | "boto_session = boto3.Session()\n", 89 | "dataset = AWSDataset(DATA_DIR, boto_session)" 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "id": "f8789bee-719b-4bf3-bcd7-a41d39ad19b3", 95 | "metadata": {}, 96 | "source": [ 97 | "* Very important! In the `DATA_DIR` defined above, put the pictures (jpg or png) of the subject you want to train.\n", 98 | "* For this task, you'll need about 10 to 20 solo, high-quality selfies taken with different backgrounds, lighting, and facial expressions. I think a great example can be found in [Joe Penna's GitHub repository](https://github.com/JoePenna/Dreambooth-Stable-Diffusion).\n", 99 | "\n", 100 | "![Samples](../assets/asset-001.png)\n", 101 | "* Use the following image processing method to crop the images into a square centered on the face. If the subject the model is trying to learn is not a person (for example, a dog), set the `detect_face` argument to `False`. " 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "id": "43780fef67ed87a8", 108 | "metadata": { 109 | "collapsed": false, 110 | "jupyter": { 111 | "outputs_hidden": false 112 | }, 113 | "tags": [] 114 | }, 115 | "outputs": [], 116 | "source": [ 117 | "dataset = dataset.preprocess_images(detect_face=True)\n", 118 | "dataset = dataset.upload_images()" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "id": "956d2937-93a4-4320-954d-b4c352f35723", 124 | "metadata": { 125 | "tags": [] 126 | }, 127 | "source": [ 128 | "## Train the model 🤖\n", 129 | "* Now it's time to train the model! Tell the model the name of the subject you want to train (e.g., Joe) and the class it belongs to. \n", 130 | "* When defining a model, one of the important arguments is how many iterations to train, or `max_train_steps`. It is generally accepted that 800 to 1200 steps are appropriate for a person, and 200 to 400 steps are appropriate for a non-human animal. The default value is 100 times the number of photos you have. You don't need to worry about that right now 🤷‍♂️, but if you don't like the results of the generated image below, this is the first parameter to adjust." 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "id": "52ed850d-1d56-4369-80f0-bebcab0e3adb", 137 | "metadata": { 138 | "tags": [] 139 | }, 140 | "outputs": [], 141 | "source": [ 142 | "SUBJECT_NAME = \"sks\" # The name of the subject you want to learn\n", 143 | "CLASS_NAME = \"person\" # The class to which the subject you want to learn belongs\n", 144 | "\n", 145 | "model = SdDreamboothLoraModel(\n", 146 | " subject_name=SUBJECT_NAME,\n", 147 | " class_name=CLASS_NAME,\n", 148 | " # max_train_steps=1000,\n", 149 | ")\n", 150 | "\n", 151 | "trainer = AWSTrainer()" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "id": "b5f2a9a3-7cf0-455d-9948-ce96b861025e", 157 | "metadata": {}, 158 | "source": [ 159 | "* Model training time can be as short as a few tens of minutes or as long as several hours." 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "id": "173ed0c9-00f6-4b48-9324-5deaedcfc47a", 166 | "metadata": { 167 | "tags": [] 168 | }, 169 | "outputs": [], 170 | "source": [ 171 | "%%time\n", 172 | "predictor = trainer.fit(model, dataset)" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "id": "d5d3e656-bdee-4762-8208-ea5fe80f6447", 178 | "metadata": {}, 179 | "source": [ 180 | "* If you restart the notebook kernel and then want to redeploy the models you've already trained to the endpoint, you can do so as follows." 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "id": "8f4ea2bc-e066-4037-8fd8-42ed4fac131a", 187 | "metadata": { 188 | "tags": [] 189 | }, 190 | "outputs": [], 191 | "source": [ 192 | "# predictor = AWSPredictor(model, dataset.get_s3_model_uri(), boto_session)" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "id": "ffeea02e-dab1-4237-b3dd-e79e3f2e6cfc", 198 | "metadata": {}, 199 | "source": [ 200 | "## Create images as you wish! 💃\n", 201 | "* Use the prompts to create any image you like. The prompt text should contain the subject name and class name defined above.\n", 202 | "* Having trouble coming up with a good prompt? Don't worry. You can use the `make_prompt` function to generate a curated prompt at random. Check this out. 🙆‍♀️\n", 203 | "* Creating great images takes patience. Play around with the prompts, but if the quality of the generation itself is problematic, you may need to retrain with better data and more appropriate training parameters." 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "id": "6c5ec891-6f71-4a26-8e90-5b0884ed4f8b", 210 | "metadata": { 211 | "tags": [] 212 | }, 213 | "outputs": [], 214 | "source": [ 215 | "%%time\n", 216 | "prompt = f\"A photo of {SUBJECT_NAME} {CLASS_NAME} with Eiffel Tower in the background\"\n", 217 | "# prompt = next(make_prompt(SUBJECT_NAME, CLASS_NAME))\n", 218 | "\n", 219 | "print(f\"The prompt is as follows:\\n{prompt}\")\n", 220 | "\n", 221 | "images = predictor.predict(\n", 222 | " prompt,\n", 223 | " height=768,\n", 224 | " width=512,\n", 225 | " num_images_per_prompt=2,\n", 226 | ")\n", 227 | "\n", 228 | "display_images(images, fig_size=10)" 229 | ] 230 | }, 231 | { 232 | "cell_type": "markdown", 233 | "id": "32398fab-f192-4c2b-8a50-fc4d74f89810", 234 | "metadata": {}, 235 | "source": [ 236 | "* Very important! Just having an AWS endpoint running to generate images is expensive. When you're done, be sure to delete the endpoint and check the console!" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": null, 242 | "id": "791984fc-4fa9-48b7-95c6-5b1c1264c4b0", 243 | "metadata": { 244 | "tags": [] 245 | }, 246 | "outputs": [], 247 | "source": [ 248 | "predictor.delete_endpoint()" 249 | ] 250 | } 251 | ], 252 | "metadata": { 253 | "kernelspec": { 254 | "display_name": "Python 3 (ipykernel)", 255 | "language": "python", 256 | "name": "python3" 257 | }, 258 | "language_info": { 259 | "codemirror_mode": { 260 | "name": "ipython", 261 | "version": 3 262 | }, 263 | "file_extension": ".py", 264 | "mimetype": "text/x-python", 265 | "name": "python", 266 | "nbconvert_exporter": "python", 267 | "pygments_lexer": "ipython3", 268 | "version": "3.10.13" 269 | } 270 | }, 271 | "nbformat": 4, 272 | "nbformat_minor": 5 273 | } 274 | -------------------------------------------------------------------------------- /src/py_dreambooth/trainer.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import shlex 4 | import subprocess 5 | from abc import ABCMeta, abstractmethod 6 | from typing import Final, Optional, Union 7 | import sagemaker 8 | from sagemaker.huggingface import HuggingFaceProcessor 9 | from sagemaker.processing import ProcessingInput, ProcessingOutput 10 | from sagemaker.utils import unique_name_from_base 11 | from .dataset import AWSDataset, LocalDataset 12 | from .model import BaseModel, SdDreamboothLoraModel, SdxlDreamboothLoraModel 13 | from .predictor import AWSPredictor, BasePredictor, LocalPredictor 14 | from .utils.aws_helpers import create_role_if_not_exists, make_s3_uri 15 | from .utils.misc import decompress_file, log_or_print 16 | 17 | DEFAULT_INSTANCE_TYPE: Final = "ml.g4dn.xlarge" 18 | 19 | PYTORCH_VERSION: Final = "2.0.0" 20 | TRANSFORMER_VERSION: Final = "4.28.1" 21 | PY_VERSION: Final = "py310" 22 | 23 | STEP_MULTIPLIER: Final = 100 24 | BASE_DIR: Final = "/opt/ml/processing" 25 | 26 | 27 | class BaseTrainer(metaclass=ABCMeta): 28 | """ 29 | An abstract class to represent the trainer. 30 | Args: 31 | config_path: The path to the Accelerate config file. 32 | report_to: The solution to report results and log. 33 | wandb_api_key: The API key to use for logging to WandB. 34 | logger: The logger to use for logging messages. 35 | """ 36 | 37 | def __init__( 38 | self, 39 | config_path: Optional[str], 40 | report_to: Optional[str], 41 | wandb_api_key: Optional[str], 42 | logger: Optional[logging.Logger], 43 | ) -> None: 44 | self.config_path = config_path 45 | self.report_to = "tensorboard" if report_to is None else report_to 46 | self.wandb_api_key = wandb_api_key 47 | self.logger = logger 48 | 49 | @abstractmethod 50 | def fit(self, model: BaseModel, dataset: LocalDataset) -> BasePredictor: 51 | """ 52 | Fit a model to a dataset. 53 | Args: 54 | model: The base model instance to be fitted. 55 | dataset: The local dataset instance to fit the model. 56 | Returns: 57 | The base predictor instance of the fitted model. 58 | """ 59 | 60 | 61 | class LocalTrainer(BaseTrainer): 62 | """ 63 | A class to represent the local trainer. 64 | Args: 65 | config_path: The path to the Accelerate config file. 66 | output_dir: The directory to store the model. 67 | report_to: The solution to report results and log. 68 | wandb_api_key: The API key to use for logging to WandB. 69 | logger: The logger to use for logging messages. 70 | """ 71 | 72 | def __init__( 73 | self, 74 | config_path: Optional[str] = None, 75 | output_dir: Optional[str] = None, 76 | report_to: Optional[str] = None, 77 | wandb_api_key: Optional[str] = None, 78 | logger: Optional[logging.Logger] = None, 79 | ) -> None: 80 | super().__init__(config_path, report_to, wandb_api_key, logger) 81 | 82 | self.output_dir = "output" if output_dir is None else output_dir 83 | os.makedirs(os.path.join(os.getcwd(), self.output_dir), exist_ok=True) 84 | 85 | def fit(self, model: BaseModel, dataset: LocalDataset) -> LocalPredictor: 86 | """ 87 | Fit a model to a dataset. 88 | Args: 89 | model: The base model instance to be fitted. 90 | dataset: The local dataset instance to fit the model. 91 | Returns: 92 | The local predictor instance of the fitted model. 93 | """ 94 | kwargs = { 95 | "data_dir": dataset.preproc_data_dir, 96 | "output_dir": self.output_dir, 97 | "report_to": self.report_to, 98 | "compress_output": "False", 99 | } 100 | 101 | if model.max_train_steps is None: 102 | max_train_steps = round(STEP_MULTIPLIER * len(dataset)) 103 | kwargs["max_train_steps"] = max_train_steps 104 | 105 | else: 106 | max_train_steps = model.max_train_steps 107 | 108 | model = model.set_members(**kwargs) 109 | 110 | if self.wandb_api_key: 111 | os.environ["WANDB_API_KEY"] = self.wandb_api_key 112 | 113 | command = model.make_command(self.config_path) 114 | 115 | log_or_print( 116 | f"The model training has begun.\n'max_train_steps' is set to {max_train_steps}.", 117 | self.logger, 118 | ) 119 | _ = subprocess.run(shlex.split(command), check=True) 120 | log_or_print("The model training has ended.", self.logger) 121 | 122 | predictor = LocalPredictor(model, self.output_dir, self.logger) 123 | 124 | return predictor 125 | 126 | 127 | class AWSTrainer(BaseTrainer): 128 | def __init__( 129 | self, 130 | config_path: Optional[str] = None, 131 | output_dir: Optional[str] = None, 132 | report_to: Optional[str] = None, 133 | wandb_api_key: Optional[str] = None, 134 | deploy_sm_endpoint: bool = True, 135 | iam_role_name: Optional[str] = None, 136 | sm_train_instance_type: Optional[str] = None, 137 | sm_infer_instance_type: Optional[str] = None, 138 | sm_endpoint_name: Optional[str] = None, 139 | logger: Optional[logging.Logger] = None, 140 | ) -> None: 141 | super().__init__(config_path, report_to, wandb_api_key, logger) 142 | 143 | self.output_dir = None 144 | self.deploy_sm_endpoint = deploy_sm_endpoint 145 | self.role_name = iam_role_name 146 | self.train_instance_type = ( 147 | DEFAULT_INSTANCE_TYPE 148 | if sm_train_instance_type is None 149 | else sm_train_instance_type 150 | ) 151 | self.infer_instance_type = None 152 | self.endpoint_name = None 153 | 154 | if self.deploy_sm_endpoint: 155 | self.infer_instance_type = ( 156 | DEFAULT_INSTANCE_TYPE 157 | if sm_infer_instance_type is None 158 | else sm_infer_instance_type 159 | ) 160 | self.endpoint_name = ( 161 | "py-dreambooth" if sm_endpoint_name is None else sm_endpoint_name 162 | ) 163 | 164 | else: 165 | self.output_dir = "output" if output_dir is None else output_dir 166 | os.makedirs(os.path.join(os.getcwd(), self.output_dir), exist_ok=True) 167 | 168 | self.sm_session = None 169 | 170 | def fit( 171 | self, model: BaseModel, dataset: AWSDataset 172 | ) -> Union[AWSPredictor, LocalPredictor]: 173 | """ 174 | Fit a model to a dataset. 175 | Args: 176 | model: The base model instance to be fitted. 177 | dataset: The AWS dataset instance to fit the model. 178 | Returns: 179 | The AWS or local predictor instance of the fitted model. 180 | """ 181 | self.sm_session = sagemaker.session.Session(boto_session=dataset.boto_session) 182 | 183 | self.role_name = ( 184 | create_role_if_not_exists( 185 | dataset.boto_session, 186 | dataset.boto_session.region_name, 187 | logger=self.logger, 188 | ) 189 | if self.role_name is None 190 | else self.role_name 191 | ) 192 | 193 | config_uri = self.sm_session.upload_data( 194 | os.path.join(os.path.dirname(model.train_code_path), "requirements.txt"), 195 | bucket=dataset.bucket_name, 196 | key_prefix=f"{dataset.project_name}/config", 197 | ) 198 | config_uri = "/".join(config_uri.split("/")[:-1]) 199 | 200 | log_or_print( 201 | f"The requirements file has been uploaded to '{config_uri}'.", 202 | self.logger, 203 | ) 204 | 205 | dataset_uri = make_s3_uri(dataset.bucket_name, dataset.dataset_prefix) 206 | 207 | kwargs = { 208 | "data_dir": f"{BASE_DIR}/dataset", 209 | "output_dir": f"{BASE_DIR}/model", 210 | "report_to": self.report_to, 211 | "compress_output": "True", 212 | } 213 | 214 | if model.max_train_steps is None: 215 | if isinstance(model, (SdDreamboothLoraModel, SdxlDreamboothLoraModel)): 216 | max_train_steps = round(len(dataset) * STEP_MULTIPLIER) 217 | else: 218 | max_train_steps = round(0.75 * len(dataset) * STEP_MULTIPLIER) 219 | 220 | kwargs["max_train_steps"] = max_train_steps 221 | 222 | else: 223 | max_train_steps = model.max_train_steps 224 | 225 | model = model.set_members(**kwargs) 226 | arguments = model.get_arguments() 227 | command = [ 228 | "accelerate", 229 | "launch", 230 | ] 231 | 232 | if self.config_path: 233 | _ = self.sm_session.upload_data( 234 | self.config_path, 235 | bucket=dataset.bucket_name, 236 | key_prefix=f"{dataset.project_name}/config", 237 | ) 238 | 239 | log_or_print( 240 | f"The Accelerate config file has been uploaded to '{config_uri}'.", 241 | self.logger, 242 | ) 243 | 244 | config_filename = os.path.basename(self.config_path) 245 | command += ["--config_file", f"{BASE_DIR}/config/{config_filename}"] 246 | 247 | model_prefix = f"{dataset.project_name}/model" 248 | model_uri = make_s3_uri(dataset.bucket_name, model_prefix) 249 | code_uri = make_s3_uri(dataset.bucket_name, f"{dataset.project_name}/code") 250 | 251 | processor = HuggingFaceProcessor( 252 | role=self.role_name, 253 | instance_count=1, 254 | instance_type=self.train_instance_type, 255 | transformers_version=TRANSFORMER_VERSION, 256 | pytorch_version=PYTORCH_VERSION, 257 | py_version=PY_VERSION, 258 | command=command, 259 | code_location=code_uri, 260 | base_job_name=dataset.project_name, 261 | sagemaker_session=self.sm_session, 262 | env={"WANDB_API_KEY": self.wandb_api_key} if self.wandb_api_key else None, 263 | ) 264 | 265 | log_or_print( 266 | f"The model training has begun.\n'max_train_steps' is set to {max_train_steps}.", 267 | self.logger, 268 | ) 269 | 270 | processor.run( 271 | inputs=[ 272 | ProcessingInput( 273 | source=config_uri, 274 | destination=f"{BASE_DIR}/config", 275 | input_name="config", 276 | ), 277 | ProcessingInput( 278 | source=dataset_uri, 279 | destination=f"{BASE_DIR}/dataset", 280 | input_name="dataset", 281 | ), 282 | ], 283 | outputs=[ 284 | ProcessingOutput( 285 | source=f"{BASE_DIR}/model", 286 | destination=model_uri, 287 | output_name="model", 288 | ) 289 | ], 290 | code=model.train_code_path, 291 | arguments=arguments, 292 | logs=True, 293 | job_name=unique_name_from_base(dataset.project_name), 294 | ) 295 | 296 | log_or_print("The model training has ended.", self.logger) 297 | 298 | if self.deploy_sm_endpoint: 299 | predictor = AWSPredictor( 300 | model, 301 | f"{model_uri}/model.tar.gz", 302 | dataset.boto_session, 303 | self.role_name, 304 | self.infer_instance_type, 305 | self.endpoint_name, 306 | self.logger, 307 | ) 308 | 309 | else: 310 | _ = self.sm_session.download_data( 311 | self.output_dir, 312 | bucket=dataset.bucket_name, 313 | key_prefix=model_prefix, 314 | ) 315 | 316 | decompress_file( 317 | os.path.join(self.output_dir, "model.tar.gz"), compression="tar" 318 | ) 319 | 320 | predictor = LocalPredictor(model, self.output_dir, self.logger) 321 | 322 | return predictor 323 | -------------------------------------------------------------------------------- /src/py_dreambooth/predictor.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from abc import ABCMeta, abstractmethod 3 | from typing import Final, List, Optional 4 | import boto3 5 | import sagemaker 6 | import torch 7 | from PIL import Image 8 | from sagemaker.huggingface.estimator import HuggingFaceModel 9 | from .model import ( 10 | BaseModel, 11 | SdDreamboothLoraModel, 12 | SdxlDreamboothLoraModel, 13 | SdxlDreamboothLoraAdvModel, 14 | ) 15 | from .utils.aws_helpers import create_role_if_not_exists 16 | from .utils.image_helpers import decode_base64_image 17 | from .utils.misc import log_or_print 18 | 19 | DEFAULT_INSTANCE_TYPE: Final = "ml.g4dn.xlarge" 20 | 21 | PYTORCH_VERSION: Final = "2.0.0" 22 | TRANSFORMER_VERSION: Final = "4.28.1" 23 | PY_VERSION: Final = "py310" 24 | 25 | 26 | class BasePredictor(metaclass=ABCMeta): 27 | """ 28 | An abstract class to represent the predictor. 29 | Args: 30 | model: The base model instance to use for prediction. 31 | logger: The logger to use for logging messages. 32 | """ 33 | 34 | def __init__(self, model: BaseModel, logger: Optional[logging.Logger]) -> None: 35 | self.model = model 36 | self.logger = logger 37 | 38 | @abstractmethod 39 | def predict( 40 | self, 41 | prompt: str, 42 | height: int, 43 | width: int, 44 | num_inference_steps: int, 45 | guidance_scale: float, 46 | negative_prompt: Optional[str], 47 | num_images_per_prompt: int, 48 | seed: Optional[int], 49 | high_noise_frac: Optional[float], 50 | cross_attention_scale: Optional[float], 51 | ) -> List[Image.Image]: 52 | """ 53 | Generate images given a prompt. 54 | Args: 55 | prompt: The prompt to use for generating images. 56 | height: The height of the generated images. 57 | width: The width of the generated images. 58 | num_inference_steps: The number of inference steps to use for generating images. 59 | guidance_scale: The guidance scale to use for generating images. 60 | negative_prompt: The negative prompt to use for generating images. 61 | num_images_per_prompt: The number of images to generate per prompt. 62 | seed: The seed to use for generating random numbers. 63 | high_noise_frac: The fraction of the noise to use for denoising. 64 | cross_attention_scale: The scale to use for cross-attention. 65 | Returns: 66 | A list of PIL images representing the generated images. 67 | """ 68 | 69 | def validate_prompt(self, prompt: str) -> bool: 70 | """ 71 | Validate the prompt. 72 | Args: 73 | prompt: The prompt to validate. 74 | Returns: 75 | Whether the prompt is valid or not. 76 | """ 77 | return not ( 78 | self.model.subject_name.lower() in prompt.lower() 79 | and self.model.class_name.lower() in prompt.lower() 80 | ) 81 | 82 | 83 | class LocalPredictor(BasePredictor): 84 | """ 85 | A class to represent the local predictor. 86 | Args: 87 | model: The base model instance to use for inference. 88 | output_dir: The output directory. 89 | logger: The logger to use for logging messages. 90 | """ 91 | 92 | def __init__( 93 | self, model: BaseModel, output_dir: str, logger: Optional[logging.Logger] = None 94 | ): 95 | super().__init__(model, logger) 96 | 97 | model_components = self.model.load_model(output_dir) 98 | self.pipeline = model_components["pipeline"] 99 | self.refiner = model_components.get("refiner") 100 | 101 | log_or_print( 102 | f"The model has loaded from the directory, '{output_dir}'.", self.logger 103 | ) 104 | 105 | def predict( 106 | self, 107 | prompt: str, 108 | height: int = 512, 109 | width: int = 512, 110 | num_inference_steps: int = 50, 111 | guidance_scale: float = 7.5, 112 | negative_prompt: Optional[str] = None, 113 | num_images_per_prompt: int = 4, 114 | seed: Optional[int] = None, 115 | high_noise_frac: float = 0.7, 116 | cross_attention_scale: float = 1.0, 117 | ) -> List[Image.Image]: 118 | """ 119 | Generate images given a prompt. 120 | Args: 121 | prompt: The prompt to use for generating images. 122 | height: The height of the generated images. 123 | width: The width of the generated images. 124 | num_inference_steps: The number of inference steps to use for generating images. 125 | guidance_scale: The guidance scale to use for generating images. 126 | negative_prompt: The negative prompt to use for generating images. 127 | num_images_per_prompt: The number of images to generate per prompt. 128 | seed: seed: The seed to use for generating random numbers. 129 | high_noise_frac: The fraction of the noise to use for denoising. 130 | cross_attention_scale: The scale to use for cross-attention. 131 | Returns: 132 | A list of PIL images representing the generated images. 133 | """ 134 | if self.validate_prompt(prompt): 135 | log_or_print( 136 | "Warning: the subject and class names are not included in the prompt.", 137 | self.logger, 138 | ) 139 | 140 | generator = ( 141 | None 142 | if seed is None 143 | else torch.Generator(device=self.model.device).manual_seed(seed) 144 | ) 145 | 146 | if isinstance( 147 | self.model, 148 | ( 149 | SdDreamboothLoraModel, 150 | SdxlDreamboothLoraModel, 151 | SdxlDreamboothLoraAdvModel, 152 | ), 153 | ): 154 | kwargs = {"cross_attention_kwargs": {"scale": cross_attention_scale}} 155 | else: 156 | kwargs = {} 157 | 158 | if self.refiner: 159 | image = self.pipeline( 160 | prompt=prompt, 161 | height=height, 162 | width=width, 163 | num_inference_steps=num_inference_steps, 164 | guidance_scale=guidance_scale, 165 | negative_prompt=negative_prompt, 166 | num_images_per_prompt=num_images_per_prompt, 167 | denoising_end=high_noise_frac, 168 | generator=generator, 169 | output_type="latent", 170 | **kwargs, 171 | )["images"] 172 | generated_images = self.refiner( 173 | prompt=prompt, 174 | image=image, 175 | num_inference_steps=num_inference_steps, 176 | denoising_start=high_noise_frac, 177 | )["images"] 178 | 179 | else: 180 | generated_images = self.pipeline( 181 | prompt, 182 | height=height, 183 | width=width, 184 | num_inference_steps=num_inference_steps, 185 | guidance_scale=guidance_scale, 186 | negative_prompt=negative_prompt, 187 | num_images_per_prompt=num_images_per_prompt, 188 | generator=generator, 189 | **kwargs, 190 | )["images"] 191 | 192 | return generated_images 193 | 194 | 195 | class AWSPredictor(BasePredictor): 196 | """ 197 | A class to represent the AWS predictor. 198 | Args: 199 | model: The base model instance to use for inference. 200 | s3_model_uri: The S3 URI of the model. 201 | boto_session: The boto session to use for AWS interactions. 202 | iam_role_name: The name of the IAM role to use. 203 | sm_infer_instance_type: The SageMaker instance type to use for inference. 204 | sm_endpoint_name: The name of the SageMaker endpoint to use for inference. 205 | logger: The logger to use for logging messages. 206 | """ 207 | 208 | def __init__( 209 | self, 210 | model: BaseModel, 211 | s3_model_uri: str, 212 | boto_session: boto3.Session, 213 | iam_role_name: Optional[str] = None, 214 | sm_infer_instance_type: Optional[str] = None, 215 | sm_endpoint_name: Optional[str] = None, 216 | logger: Optional[logging.Logger] = None, 217 | ): 218 | super().__init__(model, logger) 219 | 220 | role_name = ( 221 | create_role_if_not_exists( 222 | boto_session, 223 | boto_session.region_name, 224 | logger=self.logger, 225 | ) 226 | if iam_role_name is None 227 | else iam_role_name 228 | ) 229 | infer_instance_type = ( 230 | DEFAULT_INSTANCE_TYPE 231 | if sm_infer_instance_type is None 232 | else sm_infer_instance_type 233 | ) 234 | self.endpoint_name = ( 235 | "py-dreambooth" if sm_endpoint_name is None else sm_endpoint_name 236 | ) 237 | 238 | env = { 239 | "PRETRAINED_MODEL_NAME_OR_PATH": model.pretrained_model_name_or_path, 240 | "SCHEDULER_TYPE": model.scheduler_type, 241 | } 242 | if hasattr(model, "use_ft_vae") and model.use_ft_vae: 243 | env.update({"USE_FT_VAE": "True"}) 244 | if hasattr(model, "use_refiner") and model.use_refiner: 245 | env.update({"USE_REFINER": "True"}) 246 | if hasattr(model, "train_text_encoder_ti") and model.train_text_encoder_ti: 247 | env.update({"TRAIN_TEXT_ENCODER_TI": "True"}) 248 | 249 | sm_session = sagemaker.session.Session(boto_session=boto_session) 250 | 251 | hf_model = HuggingFaceModel( 252 | role=role_name, 253 | model_data=s3_model_uri, 254 | entry_point="inference.py", 255 | transformers_version=TRANSFORMER_VERSION, 256 | pytorch_version=PYTORCH_VERSION, 257 | py_version=PY_VERSION, 258 | source_dir=model.infer_source_dir, 259 | env=None if len(env) == 0 else env, 260 | sagemaker_session=sm_session, 261 | ) 262 | 263 | self.predictor = hf_model.deploy( 264 | initial_instance_count=1, 265 | instance_type=infer_instance_type, 266 | endpoint_name=self.endpoint_name, 267 | ) 268 | 269 | log_or_print( 270 | f"The model has deployed to the endpoint, '{self.endpoint_name}'.", 271 | self.logger, 272 | ) 273 | 274 | def delete_endpoint(self) -> None: 275 | self.predictor.delete_endpoint() 276 | log_or_print( 277 | f"The endpoint, '{self.endpoint_name}', has been deleted.", self.logger 278 | ) 279 | 280 | def predict( 281 | self, 282 | prompt: str, 283 | height: int = 512, 284 | width: int = 512, 285 | num_inference_steps: int = 50, 286 | guidance_scale: float = 7.5, 287 | negative_prompt: Optional[str] = None, 288 | num_images_per_prompt: int = 4, 289 | seed: Optional[int] = None, 290 | high_noise_frac: float = 0.7, 291 | cross_attention_scale: float = 1.0, 292 | ) -> List[Image.Image]: 293 | """ 294 | Generate images given a prompt. 295 | Args: 296 | prompt: The prompt to use for generating images. 297 | height: The height of the generated images. 298 | width: The width of the generated images. 299 | num_inference_steps: The number of inference steps to use for generating images. 300 | guidance_scale: The guidance scale to use for generating images. 301 | negative_prompt: The negative prompt to use for generating images. 302 | num_images_per_prompt: The number of images to generate per prompt. 303 | seed: seed: The seed to use for generating random numbers. 304 | high_noise_frac: The fraction of the noise to use for denoising. 305 | cross_attention_scale: The scale to use for cross-attention. 306 | Returns: 307 | A list of PIL images representing the generated images. 308 | """ 309 | if self.validate_prompt(prompt): 310 | log_or_print( 311 | "Warning: the subject and class names are not included in the prompt.", 312 | self.logger, 313 | ) 314 | 315 | data = { 316 | "prompt": prompt, 317 | "height": height, 318 | "width": width, 319 | "num_inference_steps": num_inference_steps, 320 | "guidance_scale": guidance_scale, 321 | "num_images_per_prompt": num_images_per_prompt, 322 | "high_noise_frac": high_noise_frac, 323 | "cross_attention_scale": cross_attention_scale, 324 | } 325 | 326 | if negative_prompt: 327 | data.update(**{"negative_prompt": negative_prompt}) 328 | 329 | if seed: 330 | data.update(**{"seed": seed}) 331 | 332 | generated_images = self.predictor.predict(data) 333 | generated_images = [ 334 | decode_base64_image(image) for image in generated_images["images"] 335 | ] 336 | 337 | return generated_images 338 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CreativeML Open RAIL++-M License 2 | dated November 24, 2022 3 | 4 | Section I: PREAMBLE 5 | 6 | Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation. 7 | 8 | Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations. 9 | 10 | In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation. 11 | 12 | Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI. 13 | 14 | This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model. 15 | 16 | NOW THEREFORE, You and Licensor agree as follows: 17 | 18 | 1. Definitions 19 | 20 | - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document. 21 | - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License. 22 | - "Output" means the results of operating a Model as embodied in informational content resulting therefrom. 23 | - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material. 24 | - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model. 25 | - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any. 26 | - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access. 27 | - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model. 28 | - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator. 29 | - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You. 30 | - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 31 | - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model. 32 | 33 | Section II: INTELLECTUAL PROPERTY RIGHTS 34 | 35 | Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III. 36 | 37 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model. 38 | 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed. 39 | 40 | Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION 41 | 42 | 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions: 43 | Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material. 44 | You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; 45 | You must cause any modified files to carry prominent notices stating that You changed the files; 46 | You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model. 47 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License. 48 | 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5). 49 | 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License. 50 | 51 | Section IV: OTHER PROVISIONS 52 | 53 | 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License. 54 | 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors. 55 | 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License. 56 | 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 57 | 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 58 | 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein. 59 | 60 | END OF TERMS AND CONDITIONS 61 | 62 | 63 | 64 | 65 | Attachment A 66 | 67 | Use Restrictions 68 | 69 | You agree not to use the Model or Derivatives of the Model: 70 | 71 | - In any way that violates any applicable national, federal, state, local or international law or regulation; 72 | - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; 73 | - To generate or disseminate verifiably false information and/or content with the purpose of harming others; 74 | - To generate or disseminate personal identifiable information that can be used to harm an individual; 75 | - To defame, disparage or otherwise harass others; 76 | - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation; 77 | - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics; 78 | - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm; 79 | - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories; 80 | - To provide medical advice and medical results interpretation; 81 | - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use). -------------------------------------------------------------------------------- /src/py_dreambooth/model.py: -------------------------------------------------------------------------------- 1 | import os 2 | from abc import ABCMeta, abstractmethod 3 | from enum import Enum 4 | from typing import Any, Dict, List, Optional, Union 5 | import torch 6 | from diffusers import ( 7 | DDIMScheduler, 8 | DiffusionPipeline, 9 | EulerDiscreteScheduler, 10 | StableDiffusionPipeline, 11 | ) 12 | from diffusers.models import AutoencoderKL 13 | from safetensors.torch import load_file 14 | 15 | 16 | class HfModel(str, Enum): 17 | """ 18 | A class that holds the HuggingFace Hub model IDs 19 | """ 20 | 21 | SD_V1_4 = "CompVis/stable-diffusion-v1-4" 22 | SD_V1_5 = "runwayml/stable-diffusion-v1-5" 23 | SD_V2_1 = "stabilityai/stable-diffusion-2-1-base" 24 | SD_VAE = "stabilityai/sd-vae-ft-mse" 25 | SDXL_V1_0 = "stabilityai/stable-diffusion-xl-base-1.0" 26 | SDXL_REFINER_V1_0 = "stabilityai/stable-diffusion-xl-refiner-1.0" 27 | SDXL_VAE = "madebyollin/sdxl-vae-fp16-fix" 28 | 29 | 30 | class CodeFilename(str, Enum): 31 | """ 32 | A class that holds script file names that will be used for training 33 | """ 34 | 35 | SD_DREAMBOOTH = "train_sd_dreambooth.py" 36 | SD_DREAMBOOTH_LORA = "train_sd_dreambooth_lora.py" 37 | SDXL_DREAMBOOTH_LORA = "train_sdxl_dreambooth_lora.py" 38 | SDXL_DREAMBOOTH_LORA_ADV = "train_sdxl_dreambooth_lora_advanced.py" 39 | 40 | 41 | class SourceDir(str, Enum): 42 | """ 43 | A class that holds source directory names that will be used to SageMaker Endpoint 44 | """ 45 | 46 | SD_DREAMBOOTH = "sd_dreambooth" 47 | SD_DREAMBOOTH_LORA = "sd_dreambooth_lora" 48 | SDXL_DREAMBOOTH_LORA = "sdxl_dreambooth_lora" 49 | SDXL_DREAMBOOTH_LORA_ADV = "sdxl_dreambooth_lora_advanced" 50 | 51 | 52 | class SchedulerConfig(Enum): 53 | """ 54 | A class that holds scheduler configuration values for inference 55 | """ 56 | 57 | DDIM = { 58 | "beta_start": 0.00085, 59 | "beta_end": 0.012, 60 | "beta_schedule": "scaled_linear", 61 | "clip_sample": False, 62 | "set_alpha_to_one": True, 63 | "steps_offset": 1, 64 | } 65 | EULER_DISCRETE = { 66 | "beta_start": 0.00085, 67 | "beta_end": 0.012, 68 | "beta_schedule": "scaled_linear", 69 | "use_karras_sigmas": True, 70 | "steps_offset": 1, 71 | } 72 | 73 | 74 | class BaseModel(metaclass=ABCMeta): 75 | """ 76 | An abstract class to represent the image generative model. 77 | Args: 78 | pretrained_model_name_or_path: 79 | Path to pretrained model or model identifier from huggingface.co/models. 80 | subject_name: The subject name to use for training. 81 | subject_supplement: The subject supplement to use for training. 82 | class_name: The class name to use for training. 83 | validation_prompt: A prompt that is used during validation to verify that the model is learning. 84 | with_prior_preservation: Whether to use prior preservation. 85 | seed: A seed for reproducible training. 86 | resolution: The resolution for input images, all the images in the train/validation dataset will be resized 87 | to this. 88 | center_crop: Whether to center crop the input images to the resolution. If not set, the images will be randomly 89 | cropped. The images will be resized to the resolution first before cropping. 90 | train_text_encoder: Whether to train the text encoder. If set, the text encoder should be float32 precision. 91 | train_batch_size: Batch size (per device) for the training dataloader. 92 | num_train_epochs: Total number of training epochs to perform. 93 | max_train_steps: Total number of training steps to perform. If provided, overrides num_train_epochs. 94 | learning_rate: Initial learning rate (after the potential warmup period) to use. 95 | reduce_gpu_memory_usage: Whether to reduce GPU memory usage (Instead, training speed is reduced). 96 | scheduler_type: The type of scheduler to use for training. 97 | compress_output: Whether to compress the output directory. 98 | """ 99 | 100 | def __init__( 101 | self, 102 | pretrained_model_name_or_path: str, 103 | subject_name: Optional[str], 104 | subject_supplement: Optional[str], 105 | class_name: Optional[str], 106 | validation_prompt: Optional[str], 107 | with_prior_preservation: bool, 108 | seed: Optional[int], 109 | resolution: int, 110 | center_crop: bool, 111 | train_text_encoder: bool, 112 | train_batch_size: int, 113 | num_train_epochs: int, 114 | max_train_steps: Optional[int], 115 | learning_rate: float, 116 | reduce_gpu_memory_usage: bool, 117 | scheduler_type: Optional[str], 118 | compress_output: bool, 119 | ): 120 | if subject_name is None: 121 | subject_name = "sks" 122 | subject_supplement = ( 123 | "" if subject_supplement is None else f" {subject_supplement}" 124 | ) 125 | if class_name is None: 126 | class_name = "person" 127 | 128 | if pretrained_model_name_or_path in ( 129 | HfModel.SD_V1_4.value, 130 | HfModel.SD_V1_5.value, 131 | ): 132 | resolution = min(resolution, 512) 133 | elif pretrained_model_name_or_path == HfModel.SD_V2_1.value: 134 | resolution = min(resolution, 768) 135 | else: 136 | resolution = min(resolution, 1024) 137 | 138 | self.pretrained_model_name_or_path = pretrained_model_name_or_path 139 | self.data_dir = None 140 | self.output_dir = None 141 | self.subject_name = subject_name 142 | self.subject_supplement = subject_supplement 143 | self.class_name = class_name 144 | self.with_prior_preservation = with_prior_preservation 145 | self.seed = seed 146 | self.resolution = resolution 147 | self.center_crop = center_crop 148 | self.train_text_encoder = train_text_encoder 149 | self.train_batch_size = train_batch_size 150 | self.num_train_epochs = num_train_epochs 151 | self.max_train_steps = max_train_steps 152 | self.learning_rate = learning_rate 153 | self.report_to = None 154 | self.validation_prompt = validation_prompt 155 | self.reduce_gpu_memory_usage = reduce_gpu_memory_usage 156 | self.scheduler_type = "DDIM" if scheduler_type is None else scheduler_type 157 | self.compress_output = compress_output 158 | 159 | self.train_code_path = None 160 | self.infer_source_dir = None 161 | self.device = "cuda" if torch.cuda.is_available() else "cpu" 162 | 163 | @staticmethod 164 | def get_abs_path(*args) -> Union[bytes, str]: 165 | """ 166 | Get an absolute path relative to the current script file. 167 | Returns: 168 | The absolute path string. 169 | """ 170 | return os.path.join(os.path.dirname(__file__), *args) 171 | 172 | @abstractmethod 173 | def get_arguments(self) -> List[str]: 174 | """ 175 | Get the arguments for executing the command. 176 | Returns: 177 | The list of arguments. 178 | """ 179 | 180 | @abstractmethod 181 | def load_model(self, output_dir: str) -> Dict[str, Any]: 182 | """ 183 | Load a model. 184 | Args: 185 | output_dir: The output directory. 186 | Returns: 187 | The dictionary of model component names and their instances. 188 | """ 189 | 190 | def make_command(self, config_path: Optional[str] = None) -> str: 191 | """ 192 | Make a command to execute the model training. 193 | Args: 194 | config_path: The path to the Accelerate config file. 195 | Returns: 196 | The command string. 197 | """ 198 | launch_arguments = ( 199 | "" if config_path is None else f"--config_file {config_path} " 200 | ) 201 | 202 | command = f"accelerate launch {launch_arguments}{self.train_code_path} " 203 | command += " ".join(self.get_arguments()) 204 | return command 205 | 206 | def set_members(self, **kwarg) -> "BaseModel": 207 | """ 208 | Update the members of the model. 209 | Returns: 210 | The BaseModel instance with the updated members. 211 | """ 212 | for key, value in kwarg.items(): 213 | if hasattr(self, key): 214 | setattr(self, key, value) 215 | else: 216 | raise ValueError(f"Invalid parameter: {key}") 217 | return self 218 | 219 | 220 | class SdDreamboothModel(BaseModel): 221 | """ 222 | A class to represent the Stable Diffusion Dreambooth model. 223 | Args: 224 | pretrained_model_name_or_path: 225 | Path to pretrained model or model identifier from huggingface.co/models. 226 | subject_name: The subject name to use for training. 227 | subject_supplement: The subject supplement to use for training. 228 | class_name: The class name to use for training. 229 | validation_prompt: A prompt that is used during validation to verify that the model is learning. 230 | with_prior_preservation: Whether to use prior preservation. 231 | seed: A seed for reproducible training. 232 | resolution: The resolution for input images, all the images in the train/validation dataset will be resized 233 | to this. 234 | center_crop: Whether to center crop the input images to the resolution. If not set, the images will be randomly 235 | cropped. The images will be resized to the resolution first before cropping. 236 | train_text_encoder: Whether to train the text encoder. If set, the text encoder should be float32 precision. 237 | train_batch_size: Batch size (per device) for the training dataloader. 238 | num_train_epochs: Total number of training epochs to perform. 239 | max_train_steps: Total number of training steps to perform. If provided, overrides num_train_epochs. 240 | learning_rate: Initial learning rate (after the potential warmup period) to use. 241 | reduce_gpu_memory_usage: Whether to reduce GPU memory usage (Instead, training speed is reduced). 242 | scheduler_type: The type of scheduler to use for training. 243 | compress_output: Whether to compress the output directory. 244 | """ 245 | 246 | def __init__( 247 | self, 248 | pretrained_model_name_or_path: Optional[str] = None, 249 | subject_name: Optional[str] = None, 250 | subject_supplement: Optional[str] = None, 251 | class_name: Optional[str] = None, 252 | validation_prompt: Optional[str] = None, 253 | with_prior_preservation: bool = True, 254 | seed: Optional[int] = None, 255 | resolution: int = 768, 256 | center_crop: bool = False, 257 | train_text_encoder: bool = True, 258 | train_batch_size: int = 1, 259 | num_train_epochs: int = 1, 260 | max_train_steps: Optional[int] = None, 261 | learning_rate: float = 2e-06, 262 | reduce_gpu_memory_usage: bool = True, 263 | scheduler_type: Optional[str] = None, 264 | use_ft_vae: bool = False, 265 | compress_output: bool = False, 266 | ): 267 | if pretrained_model_name_or_path is None: 268 | pretrained_model_name_or_path = HfModel.SD_V2_1.value 269 | 270 | super().__init__( 271 | pretrained_model_name_or_path, 272 | subject_name, 273 | subject_supplement, 274 | class_name, 275 | validation_prompt, 276 | with_prior_preservation, 277 | seed, 278 | resolution, 279 | center_crop, 280 | train_text_encoder, 281 | train_batch_size, 282 | num_train_epochs, 283 | max_train_steps, 284 | learning_rate, 285 | reduce_gpu_memory_usage, 286 | scheduler_type, 287 | compress_output, 288 | ) 289 | 290 | self.use_ft_vae = use_ft_vae 291 | self.train_code_path = self.get_abs_path( 292 | "scripts", 293 | "train", 294 | CodeFilename.SD_DREAMBOOTH.value, 295 | ) 296 | self.infer_source_dir = self.get_abs_path( 297 | "scripts", "infer", SourceDir.SD_DREAMBOOTH.value 298 | ) 299 | 300 | def load_model( 301 | self, 302 | output_dir: str, 303 | ) -> Dict[str, Any]: 304 | """ 305 | Load a model. 306 | Args: 307 | output_dir: The output directory. 308 | Returns: 309 | The dictionary of model component names and their instances. 310 | """ 311 | if self.scheduler_type.upper() == "DDIM": 312 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 313 | elif self.scheduler_type.upper() == "EULERDISCRETE": 314 | scheduler = EulerDiscreteScheduler( 315 | **SchedulerConfig.EULER_DISCRETE.value, 316 | ) 317 | else: 318 | scheduler = None 319 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 320 | 321 | pipeline = StableDiffusionPipeline.from_pretrained( 322 | output_dir, 323 | scheduler=scheduler, 324 | revision="fp16", 325 | torch_dtype=torch.float16, 326 | ).to(self.device) 327 | 328 | if self.use_ft_vae: 329 | pipeline.vae = AutoencoderKL.from_pretrained( 330 | HfModel.SD_VAE.value, torch_dtype=torch.float16 331 | ).to(self.device) 332 | 333 | return {"pipeline": pipeline} 334 | 335 | def get_arguments(self) -> List[str]: 336 | """ 337 | Get the arguments for executing the command. 338 | Returns: 339 | The list of arguments. 340 | """ 341 | assert ( 342 | self.data_dir or self.output_dir 343 | ), "'data_dir' or 'output_dir' is required." 344 | 345 | instance_prompt = ( 346 | f"a photo of {self.subject_name}{self.subject_supplement} {self.class_name}" 347 | ) 348 | class_prompt = f"a photo of {self.class_name}" 349 | 350 | if self.validation_prompt is None: 351 | self.validation_prompt = ( 352 | f"{instance_prompt} with Eiffel Tower in the background" 353 | ) 354 | 355 | arguments = [ 356 | "--pretrained_model_name_or_path", 357 | self.pretrained_model_name_or_path, 358 | "--instance_data_dir", 359 | self.data_dir, 360 | "--instance_prompt", 361 | f"'{instance_prompt}'", 362 | "--validation_prompt", 363 | f"'{self.validation_prompt}'", 364 | "--num_class_images", 365 | 150, 366 | "--output_dir", 367 | self.output_dir, 368 | "--resolution", 369 | self.resolution, 370 | "--train_batch_size", 371 | self.train_batch_size, 372 | "--learning_rate", 373 | self.learning_rate, 374 | "--lr_scheduler", 375 | "constant", 376 | "--lr_warmup_steps", 377 | 0, 378 | "--compress_output", 379 | self.compress_output, 380 | ] 381 | 382 | if self.with_prior_preservation: 383 | arguments += [ 384 | "--class_prompt", 385 | f"'{class_prompt}'", 386 | "--with_prior_preservation", 387 | "True", 388 | "--prior_loss_weight", 389 | "1.0", 390 | ] 391 | 392 | if self.seed: 393 | arguments += [ 394 | "--seed", 395 | self.seed, 396 | ] 397 | 398 | if self.center_crop: 399 | arguments += ["--center_crop"] 400 | 401 | if self.train_text_encoder: 402 | arguments += ["--train_text_encoder", "True"] 403 | 404 | if self.max_train_steps: 405 | arguments += [ 406 | "--max_train_steps", 407 | self.max_train_steps, 408 | ] 409 | 410 | if self.reduce_gpu_memory_usage: 411 | arguments += [ 412 | "--gradient_accumulation_steps", 413 | "1", 414 | "--gradient_checkpointing", 415 | "True", 416 | "--use_8bit_adam", 417 | "True", 418 | # "--enable_xformers_memory_efficient_attention", 419 | # "True", 420 | "--mixed_precision", 421 | "fp16", 422 | "--set_grads_to_none", 423 | "True", 424 | ] 425 | 426 | if self.report_to: 427 | arguments += [ 428 | "--report_to", 429 | self.report_to, 430 | ] 431 | 432 | return list(map(str, arguments)) 433 | 434 | 435 | class SdDreamboothLoraModel(BaseModel): 436 | """ 437 | A class to represent the Stable Diffusion Dreambooth LoRA model. 438 | Args: 439 | pretrained_model_name_or_path: 440 | Path to pretrained model or model identifier from huggingface.co/models. 441 | subject_name: The subject name to use for training. 442 | subject_supplement: The subject supplement to use for training. 443 | class_name: The class name to use for training. 444 | validation_prompt: A prompt that is used during validation to verify that the model is learning. 445 | with_prior_preservation: Whether to use prior preservation. 446 | seed: A seed for reproducible training. 447 | resolution: The resolution for input images, all the images in the train/validation dataset will be resized 448 | to this. 449 | center_crop: Whether to center crop the input images to the resolution. If not set, the images will be randomly 450 | cropped. The images will be resized to the resolution first before cropping. 451 | train_text_encoder: Whether to train the text encoder. If set, the text encoder should be float32 precision. 452 | train_batch_size: Batch size (per device) for the training dataloader. 453 | num_train_epochs: Total number of training epochs to perform. 454 | max_train_steps: Total number of training steps to perform. If provided, overrides num_train_epochs. 455 | learning_rate: Initial learning rate (after the potential warmup period) to use. 456 | rank: The dimension of the LoRA update matrices. 457 | reduce_gpu_memory_usage: Whether to reduce GPU memory usage (Instead, training speed is reduced). 458 | scheduler_type: The type of scheduler to use for training. 459 | compress_output: Whether to compress the output directory. 460 | """ 461 | 462 | def __init__( 463 | self, 464 | pretrained_model_name_or_path: Optional[str] = None, 465 | subject_name: Optional[str] = None, 466 | subject_supplement: Optional[str] = None, 467 | class_name: Optional[str] = None, 468 | validation_prompt: Optional[str] = None, 469 | with_prior_preservation: bool = True, 470 | seed: Optional[int] = None, 471 | resolution: int = 1024, 472 | center_crop: bool = False, 473 | train_text_encoder: bool = True, 474 | train_batch_size: int = 1, 475 | num_train_epochs: int = 1, 476 | max_train_steps: Optional[int] = None, 477 | learning_rate: float = 1e-4, 478 | rank: int = 4, 479 | reduce_gpu_memory_usage: bool = True, 480 | scheduler_type: Optional[str] = None, 481 | use_ft_vae: bool = False, 482 | compress_output: bool = False, 483 | ): 484 | if pretrained_model_name_or_path is None: 485 | pretrained_model_name_or_path = HfModel.SD_V2_1.value 486 | 487 | super().__init__( 488 | pretrained_model_name_or_path, 489 | subject_name, 490 | subject_supplement, 491 | class_name, 492 | validation_prompt, 493 | with_prior_preservation, 494 | seed, 495 | resolution, 496 | center_crop, 497 | train_text_encoder, 498 | train_batch_size, 499 | num_train_epochs, 500 | max_train_steps, 501 | learning_rate, 502 | reduce_gpu_memory_usage, 503 | scheduler_type, 504 | compress_output, 505 | ) 506 | 507 | self.rank = rank 508 | self.use_ft_vae = use_ft_vae 509 | self.train_code_path = self.get_abs_path( 510 | "scripts", 511 | "train", 512 | CodeFilename.SD_DREAMBOOTH_LORA.value, 513 | ) 514 | self.infer_source_dir = self.get_abs_path( 515 | "scripts", 516 | "infer", 517 | SourceDir.SD_DREAMBOOTH_LORA.value, 518 | ) 519 | 520 | def load_model( 521 | self, 522 | output_dir: str, 523 | ) -> Dict[str, Any]: 524 | """ 525 | Load a model. 526 | Args: 527 | output_dir: The output directory. 528 | Returns: 529 | The dictionary of model component names and their instances. 530 | """ 531 | if self.scheduler_type.upper() == "DDIM": 532 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 533 | elif self.scheduler_type.upper() == "EULERDISCRETE": 534 | scheduler = EulerDiscreteScheduler( 535 | **SchedulerConfig.EULER_DISCRETE.value, 536 | ) 537 | else: 538 | scheduler = None 539 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 540 | 541 | pipeline = DiffusionPipeline.from_pretrained( 542 | self.pretrained_model_name_or_path, 543 | scheduler=scheduler, 544 | variant="fp16", 545 | torch_dtype=torch.float16, 546 | ).to(self.device) 547 | pipeline.load_lora_weights(output_dir) 548 | 549 | if self.use_ft_vae: 550 | pipeline.vae = AutoencoderKL.from_pretrained( 551 | HfModel.SD_VAE.value, torch_dtype=torch.float16 552 | ).to(self.device) 553 | 554 | return {"pipeline": pipeline} 555 | 556 | def get_arguments(self) -> List[str]: 557 | """ 558 | Get the arguments for executing the command. 559 | Returns: 560 | The list of arguments. 561 | """ 562 | assert ( 563 | self.data_dir or self.output_dir 564 | ), "'data_dir' or 'output_dir' is required." 565 | 566 | instance_prompt = ( 567 | f"a photo of {self.subject_name}{self.subject_supplement} {self.class_name}" 568 | ) 569 | class_prompt = f"a photo of {self.class_name}" 570 | 571 | if self.validation_prompt is None: 572 | self.validation_prompt = ( 573 | f"{instance_prompt} with Eiffel Tower in the background" 574 | ) 575 | 576 | arguments = [ 577 | "--pretrained_model_name_or_path", 578 | self.pretrained_model_name_or_path, 579 | "--instance_data_dir", 580 | self.data_dir, 581 | "--instance_prompt", 582 | f"'{instance_prompt}'", 583 | "--validation_prompt", 584 | f"'{self.validation_prompt}'", 585 | "--num_class_images", 586 | 150, 587 | "--output_dir", 588 | self.output_dir, 589 | "--resolution", 590 | self.resolution, 591 | "--train_batch_size", 592 | self.train_batch_size, 593 | "--sample_batch_size", 594 | 2, 595 | "--learning_rate", 596 | self.learning_rate, 597 | "--lr_scheduler", 598 | "constant", 599 | "--lr_warmup_steps", 600 | 0, 601 | "--rank", 602 | self.rank, 603 | "--compress_output", 604 | self.compress_output, 605 | ] 606 | 607 | if self.with_prior_preservation: 608 | arguments += [ 609 | "--class_prompt", 610 | f"'{class_prompt}'", 611 | "--with_prior_preservation", 612 | "True", 613 | "--prior_loss_weight", 614 | "1.0", 615 | ] 616 | 617 | if self.seed: 618 | arguments += [ 619 | "--seed", 620 | self.seed, 621 | ] 622 | 623 | if self.center_crop: 624 | arguments += ["--center_crop"] 625 | 626 | if self.train_text_encoder: 627 | arguments += ["--train_text_encoder", "True"] 628 | 629 | if self.max_train_steps: 630 | arguments += [ 631 | "--max_train_steps", 632 | self.max_train_steps, 633 | ] 634 | 635 | if self.reduce_gpu_memory_usage: 636 | arguments += [ 637 | "--gradient_accumulation_steps", 638 | "4", 639 | "--gradient_checkpointing", 640 | "True", 641 | "--use_8bit_adam", 642 | "True", 643 | # "--enable_xformers_memory_efficient_attention", 644 | # "True", 645 | "--mixed_precision", 646 | "fp16", 647 | ] 648 | 649 | if self.report_to: 650 | arguments += [ 651 | "--report_to", 652 | self.report_to, 653 | ] 654 | 655 | return list(map(str, arguments)) 656 | 657 | 658 | class SdxlDreamboothLoraModel(BaseModel): 659 | """ 660 | A class to represent the Stable Diffusion XL Dreambooth LoRA model. 661 | Args: 662 | pretrained_model_name_or_path: 663 | Path to pretrained model or model identifier from huggingface.co/models. 664 | subject_name: The subject name to use for training. 665 | subject_supplement: The subject supplement to use for training. 666 | class_name: The class name to use for training. 667 | validation_prompt: A prompt that is used during validation to verify that the model is learning. 668 | with_prior_preservation: Whether to use prior preservation. 669 | seed: A seed for reproducible training. 670 | resolution: The resolution for input images, all the images in the train/validation dataset will be resized 671 | to this. 672 | center_crop: Whether to center crop the input images to the resolution. If not set, the images will be randomly 673 | cropped. The images will be resized to the resolution first before cropping. 674 | train_text_encoder: Whether to train the text encoder. If set, the text encoder should be float32 precision. 675 | train_batch_size: Batch size (per device) for the training dataloader. 676 | num_train_epochs: Total number of training epochs to perform. 677 | max_train_steps: Total number of training steps to perform. If provided, overrides num_train_epochs. 678 | learning_rate: Initial learning rate (after the potential warmup period) to use. 679 | rank: The dimension of the LoRA update matrices. 680 | reduce_gpu_memory_usage: Whether to reduce GPU memory usage (Instead, training speed is reduced). 681 | scheduler_type: The type of scheduler to use for training. 682 | use_refiner: Whether to use the refiner. 683 | compress_output: Whether to compress the output directory. 684 | """ 685 | 686 | def __init__( 687 | self, 688 | pretrained_model_name_or_path: Optional[str] = None, 689 | subject_name: Optional[str] = None, 690 | subject_supplement: Optional[str] = None, 691 | class_name: Optional[str] = None, 692 | validation_prompt: Optional[str] = None, 693 | with_prior_preservation: bool = True, 694 | seed: Optional[int] = None, 695 | resolution: int = 1024, 696 | center_crop: bool = False, 697 | train_text_encoder: bool = True, 698 | train_batch_size: int = 1, 699 | num_train_epochs: int = 1, 700 | max_train_steps: Optional[int] = None, 701 | learning_rate: float = 1e-4, 702 | rank: int = 4, 703 | reduce_gpu_memory_usage: bool = True, 704 | scheduler_type: Optional[str] = None, 705 | use_refiner: bool = False, 706 | compress_output: bool = False, 707 | ): 708 | if pretrained_model_name_or_path is None: 709 | pretrained_model_name_or_path = HfModel.SDXL_V1_0.value 710 | 711 | super().__init__( 712 | pretrained_model_name_or_path, 713 | subject_name, 714 | subject_supplement, 715 | class_name, 716 | validation_prompt, 717 | with_prior_preservation, 718 | seed, 719 | resolution, 720 | center_crop, 721 | train_text_encoder, 722 | train_batch_size, 723 | num_train_epochs, 724 | max_train_steps, 725 | learning_rate, 726 | reduce_gpu_memory_usage, 727 | scheduler_type, 728 | compress_output, 729 | ) 730 | 731 | self.pretrained_vae_model_name_or_path = HfModel.SDXL_VAE.value 732 | self.rank = rank 733 | self.use_refiner = use_refiner 734 | self.train_code_path = self.get_abs_path( 735 | "scripts", 736 | "train", 737 | CodeFilename.SDXL_DREAMBOOTH_LORA.value, 738 | ) 739 | self.infer_source_dir = self.get_abs_path( 740 | "scripts", 741 | "infer", 742 | SourceDir.SDXL_DREAMBOOTH_LORA.value, 743 | ) 744 | 745 | def load_model( 746 | self, 747 | output_dir: str, 748 | ) -> Dict[str, Any]: 749 | """ 750 | Load a model. 751 | Args: 752 | output_dir: The output directory. 753 | Returns: 754 | The dictionary of model component names and their instances. 755 | """ 756 | if self.scheduler_type.upper() == "DDIM": 757 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 758 | elif self.scheduler_type.upper() == "EULERDISCRETE": 759 | scheduler = EulerDiscreteScheduler( 760 | **SchedulerConfig.EULER_DISCRETE.value, 761 | ) 762 | else: 763 | scheduler = None 764 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 765 | 766 | vae = AutoencoderKL.from_pretrained( 767 | HfModel.SDXL_VAE.value, 768 | torch_dtype=torch.float16, 769 | ) 770 | pipeline = DiffusionPipeline.from_pretrained( 771 | self.pretrained_model_name_or_path, 772 | vae=vae, 773 | scheduler=scheduler, 774 | variant="fp16", 775 | torch_dtype=torch.float16, 776 | ).to(self.device) 777 | pipeline.load_lora_weights(output_dir) 778 | 779 | if self.use_refiner: 780 | refiner = DiffusionPipeline.from_pretrained( 781 | HfModel.SDXL_REFINER_V1_0.value, 782 | vae=pipeline.vae, 783 | text_encoder_2=pipeline.text_encoder_2, 784 | variant="fp16", 785 | torch_dtype=torch.float16, 786 | ).to(self.device) 787 | else: 788 | refiner = None 789 | 790 | return {"pipeline": pipeline, "refiner": refiner} 791 | 792 | def get_arguments(self) -> List[str]: 793 | """ 794 | Get the arguments for executing the command. 795 | Returns: 796 | The list of arguments. 797 | """ 798 | assert ( 799 | self.data_dir or self.output_dir 800 | ), "'data_dir' or 'output_dir' is required." 801 | 802 | instance_prompt = ( 803 | f"a photo of {self.subject_name}{self.subject_supplement} {self.class_name}" 804 | ) 805 | class_prompt = f"a photo of {self.class_name}" 806 | 807 | if self.validation_prompt is None: 808 | self.validation_prompt = ( 809 | f"{instance_prompt} with Eiffel Tower in the background" 810 | ) 811 | 812 | arguments = [ 813 | "--pretrained_model_name_or_path", 814 | self.pretrained_model_name_or_path, 815 | "--pretrained_vae_model_name_or_path", 816 | self.pretrained_vae_model_name_or_path, 817 | "--instance_data_dir", 818 | self.data_dir, 819 | "--instance_prompt", 820 | f"'{instance_prompt}'", 821 | "--validation_prompt", 822 | f"'{self.validation_prompt}'", 823 | "--num_validation_images", 824 | 4, 825 | "--num_class_images", 826 | 150, 827 | "--output_dir", 828 | self.output_dir, 829 | "--resolution", 830 | self.resolution, 831 | "--train_batch_size", 832 | self.train_batch_size, 833 | "--sample_batch_size", 834 | 2, 835 | "--learning_rate", 836 | self.learning_rate, 837 | "--snr_gamma", 838 | 5.0, 839 | "--lr_scheduler", 840 | "constant", 841 | "--lr_warmup_steps", 842 | 0, 843 | "--rank", 844 | self.rank, 845 | "--compress_output", 846 | self.compress_output, 847 | ] 848 | 849 | if self.with_prior_preservation: 850 | arguments += [ 851 | "--class_prompt", 852 | f"'{class_prompt}'", 853 | "--with_prior_preservation", 854 | "True", 855 | "--prior_loss_weight", 856 | "1.0", 857 | ] 858 | 859 | if self.seed: 860 | arguments += [ 861 | "--seed", 862 | self.seed, 863 | ] 864 | 865 | if self.center_crop: 866 | arguments += ["--center_crop"] 867 | 868 | if self.train_text_encoder: 869 | arguments += ["--train_text_encoder", "True"] 870 | 871 | if self.max_train_steps: 872 | arguments += [ 873 | "--max_train_steps", 874 | self.max_train_steps, 875 | ] 876 | 877 | if self.reduce_gpu_memory_usage: 878 | arguments += [ 879 | "--gradient_accumulation_steps", 880 | "4", 881 | "--gradient_checkpointing", 882 | "True", 883 | "--use_8bit_adam", 884 | "True", 885 | # "--enable_xformers_memory_efficient_attention", 886 | # "True", 887 | "--mixed_precision", 888 | "fp16", 889 | ] 890 | 891 | if self.report_to: 892 | arguments += [ 893 | "--report_to", 894 | self.report_to, 895 | ] 896 | 897 | return list(map(str, arguments)) 898 | 899 | 900 | class SdxlDreamboothLoraAdvModel(BaseModel): 901 | """ 902 | A class to represent the Stable Diffusion XL Dreambooth LoRA advanced model. 903 | Args: 904 | pretrained_model_name_or_path: 905 | Path to pretrained model or model identifier from huggingface.co/models. 906 | subject_name: The subject name to use for training. 907 | subject_supplement: The subject supplement to use for training. 908 | class_name: The class name to use for training. 909 | validation_prompt: A prompt that is used during validation to verify that the model is learning. 910 | with_prior_preservation: Whether to use prior preservation. 911 | seed: A seed for reproducible training. 912 | resolution: The resolution for input images, all the images in the train/validation dataset will be resized 913 | to this. 914 | center_crop: Whether to center crop the input images to the resolution. If not set, the images will be randomly 915 | cropped. The images will be resized to the resolution first before cropping. 916 | train_text_encoder: Whether to train the text encoder. If set, the text encoder should be float32 precision. 917 | train_batch_size: Batch size (per device) for the training dataloader. 918 | num_train_epochs: Total number of training epochs to perform. 919 | max_train_steps: Total number of training steps to perform. If provided, overrides num_train_epochs. 920 | learning_rate: Initial learning rate (after the potential warmup period) to use. 921 | text_encoder_lr: Text encoder learning rate to use. 922 | use_adamw: Whether to use AdamW optimizer (or Prodigy). 923 | rank: The dimension of the LoRA update matrices. 924 | reduce_gpu_memory_usage: Whether to reduce GPU memory usage (Instead, training speed is reduced). 925 | scheduler_type: The type of scheduler to use for training. 926 | use_refiner: Whether to use the refiner. 927 | compress_output: Whether to compress the output directory. 928 | """ 929 | 930 | def __init__( 931 | self, 932 | pretrained_model_name_or_path: Optional[str] = None, 933 | subject_name: Optional[str] = None, 934 | subject_supplement: Optional[str] = None, 935 | class_name: Optional[str] = None, 936 | validation_prompt: Optional[str] = None, 937 | with_prior_preservation: bool = True, 938 | seed: Optional[int] = None, 939 | resolution: int = 1024, 940 | center_crop: bool = False, 941 | train_text_encoder: bool = False, 942 | train_batch_size: int = 1, 943 | num_train_epochs: int = 1, 944 | max_train_steps: Optional[int] = None, 945 | learning_rate: Optional[float] = None, 946 | text_encoder_lr: Optional[float] = None, 947 | train_text_encoder_ti: bool = True, 948 | use_adamw: bool = False, 949 | rank: int = 32, 950 | reduce_gpu_memory_usage: bool = True, 951 | scheduler_type: Optional[str] = None, 952 | use_refiner: bool = False, 953 | compress_output: bool = False, 954 | ): 955 | if pretrained_model_name_or_path is None: 956 | pretrained_model_name_or_path = HfModel.SDXL_V1_0.value 957 | if subject_name is None and train_text_encoder_ti: 958 | subject_name = "TOK" 959 | if learning_rate is None: 960 | learning_rate = 1e-4 if use_adamw else 1.0 961 | if text_encoder_lr is None: 962 | text_encoder_lr = 5e-5 if use_adamw else learning_rate 963 | if train_text_encoder and train_text_encoder_ti: 964 | raise ValueError( 965 | "'train_text_encoder' and 'train_text_encoder_ti' cannot be True at the same time." 966 | ) 967 | 968 | super().__init__( 969 | pretrained_model_name_or_path, 970 | subject_name, 971 | subject_supplement, 972 | class_name, 973 | validation_prompt, 974 | with_prior_preservation, 975 | seed, 976 | resolution, 977 | center_crop, 978 | train_text_encoder, 979 | train_batch_size, 980 | num_train_epochs, 981 | max_train_steps, 982 | learning_rate, 983 | reduce_gpu_memory_usage, 984 | scheduler_type, 985 | compress_output, 986 | ) 987 | 988 | self.pretrained_vae_model_name_or_path = HfModel.SDXL_VAE.value 989 | self.text_encoder_lr = text_encoder_lr 990 | self.train_text_encoder_ti = train_text_encoder_ti 991 | self.use_adamw = use_adamw 992 | self.rank = rank 993 | self.use_refiner = use_refiner 994 | self.train_code_path = self.get_abs_path( 995 | "scripts", 996 | "train", 997 | CodeFilename.SDXL_DREAMBOOTH_LORA_ADV.value, 998 | ) 999 | self.infer_source_dir = self.get_abs_path( 1000 | "scripts", 1001 | "infer", 1002 | SourceDir.SDXL_DREAMBOOTH_LORA_ADV.value, 1003 | ) 1004 | 1005 | def load_model( 1006 | self, 1007 | output_dir: str, 1008 | ) -> Dict[str, Any]: 1009 | """ 1010 | Load a model. 1011 | Args: 1012 | output_dir: The output directory. 1013 | Returns: 1014 | The dictionary of model component names and their instances. 1015 | """ 1016 | if self.scheduler_type.upper() == "DDIM": 1017 | scheduler = DDIMScheduler(**SchedulerConfig.DDIM.value) 1018 | elif self.scheduler_type.upper() == "EULERDISCRETE": 1019 | scheduler = EulerDiscreteScheduler( 1020 | **SchedulerConfig.EULER_DISCRETE.value, 1021 | ) 1022 | else: 1023 | scheduler = None 1024 | ValueError("The 'scheduler_type' must be one of 'DDIM' or 'EulerDiscrete'.") 1025 | 1026 | vae = AutoencoderKL.from_pretrained( 1027 | HfModel.SDXL_VAE.value, 1028 | torch_dtype=torch.float16, 1029 | ) 1030 | pipeline = DiffusionPipeline.from_pretrained( 1031 | self.pretrained_model_name_or_path, 1032 | vae=vae, 1033 | scheduler=scheduler, 1034 | variant="fp16", 1035 | torch_dtype=torch.float16, 1036 | ).to(self.device) 1037 | 1038 | if self.train_text_encoder_ti: 1039 | state_dict = load_file(os.path.join(output_dir, "models_emb.safetensors")) 1040 | pipeline.load_textual_inversion( 1041 | state_dict["clip_l"], 1042 | token=["", ""], 1043 | text_encoder=pipeline.text_encoder, 1044 | tokenizer=pipeline.tokenizer, 1045 | ) 1046 | pipeline.load_textual_inversion( 1047 | state_dict["clip_g"], 1048 | token=["", ""], 1049 | text_encoder=pipeline.text_encoder_2, 1050 | tokenizer=pipeline.tokenizer_2, 1051 | ) 1052 | pipeline.load_lora_weights(output_dir) 1053 | 1054 | if self.use_refiner: 1055 | refiner = DiffusionPipeline.from_pretrained( 1056 | HfModel.SDXL_REFINER_V1_0.value, 1057 | vae=pipeline.vae, 1058 | text_encoder_2=pipeline.text_encoder_2, 1059 | variant="fp16", 1060 | torch_dtype=torch.float16, 1061 | ).to(self.device) 1062 | else: 1063 | refiner = None 1064 | 1065 | return {"pipeline": pipeline, "refiner": refiner} 1066 | 1067 | def get_arguments(self) -> List[str]: 1068 | """ 1069 | Get the arguments for executing the command. 1070 | Returns: 1071 | The list of arguments. 1072 | """ 1073 | assert ( 1074 | self.data_dir or self.output_dir 1075 | ), "'data_dir' or 'output_dir' is required." 1076 | 1077 | instance_prompt = ( 1078 | f"a photo of {self.subject_name}{self.subject_supplement} {self.class_name}" 1079 | ) 1080 | class_prompt = f"a photo of {self.class_name}" 1081 | 1082 | if self.validation_prompt is None: 1083 | self.validation_prompt = ( 1084 | f"{instance_prompt} with Eiffel Tower in the background" 1085 | ) 1086 | 1087 | arguments = [ 1088 | "--pretrained_model_name_or_path", 1089 | self.pretrained_model_name_or_path, 1090 | "--pretrained_vae_model_name_or_path", 1091 | self.pretrained_vae_model_name_or_path, 1092 | "--instance_data_dir", 1093 | self.data_dir, 1094 | "--repeats", 1095 | 1, 1096 | "--instance_prompt", 1097 | f"'{instance_prompt}'", 1098 | "--validation_prompt", 1099 | f"'{self.validation_prompt}'", 1100 | "--num_validation_images", 1101 | 4, 1102 | "--num_class_images", 1103 | 150, 1104 | "--output_dir", 1105 | self.output_dir, 1106 | "--resolution", 1107 | self.resolution, 1108 | "--train_batch_size", 1109 | self.train_batch_size, 1110 | "--sample_batch_size", 1111 | 2, 1112 | "--learning_rate", 1113 | self.learning_rate, 1114 | "--text_encoder_lr", 1115 | self.text_encoder_lr, 1116 | "--lr_scheduler", 1117 | "constant", 1118 | "--snr_gamma", 1119 | 5.0, 1120 | "--lr_warmup_steps", 1121 | 0, 1122 | "--rank", 1123 | self.rank, 1124 | "--compress_output", 1125 | self.compress_output, 1126 | ] 1127 | 1128 | if self.with_prior_preservation: 1129 | arguments += [ 1130 | "--class_prompt", 1131 | f"'{class_prompt}'", 1132 | "--with_prior_preservation", 1133 | "True", 1134 | "--prior_loss_weight", 1135 | "1.0", 1136 | ] 1137 | 1138 | if self.seed: 1139 | arguments += [ 1140 | "--seed", 1141 | self.seed, 1142 | ] 1143 | 1144 | if self.center_crop: 1145 | arguments += ["--center_crop"] 1146 | 1147 | if self.train_text_encoder: 1148 | arguments += ["--train_text_encoder", "True"] 1149 | 1150 | if self.max_train_steps: 1151 | arguments += [ 1152 | "--max_train_steps", 1153 | self.max_train_steps, 1154 | ] 1155 | 1156 | if self.train_text_encoder_ti: 1157 | arguments += [ 1158 | "--token_abstraction", 1159 | self.subject_name, 1160 | "--num_new_tokens_per_abstraction", 1161 | 2, 1162 | "--train_text_encoder_ti", 1163 | "True", 1164 | "--train_text_encoder_ti_frac", 1165 | 0.5, 1166 | "--adam_weight_decay_text_encoder", 1167 | 0.01, 1168 | ] 1169 | 1170 | if self.use_adamw: 1171 | arguments += [ 1172 | "--optimizer", 1173 | "adamw", 1174 | ] 1175 | else: 1176 | arguments += [ 1177 | "--optimizer", 1178 | "prodigy", 1179 | "--adam_beta1", 1180 | 0.9, 1181 | "--adam_beta2", 1182 | 0.99, 1183 | "--adam_weight_decay", 1184 | 0.01, 1185 | "--prodigy_use_bias_correction", 1186 | "True", 1187 | "--prodigy_safeguard_warmup", 1188 | "True", 1189 | ] 1190 | 1191 | if self.reduce_gpu_memory_usage: 1192 | arguments += [ 1193 | "--gradient_accumulation_steps", 1194 | "4", 1195 | "--gradient_checkpointing", 1196 | "True", 1197 | "--use_8bit_adam", 1198 | "True", 1199 | # "--enable_xformers_memory_efficient_attention", 1200 | # "True", 1201 | "--mixed_precision", 1202 | "bf16", 1203 | ] 1204 | 1205 | if self.report_to: 1206 | arguments += [ 1207 | "--report_to", 1208 | self.report_to, 1209 | ] 1210 | 1211 | return list(map(str, arguments)) 1212 | --------------------------------------------------------------------------------