Stage Harbor release files 97501-98000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/control_lora/README.md +41 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/control_lora/control_lora.py +58 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/controlnet/train_controlnet_webdataset.py +1470 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/README.md +94 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/requirements.txt +8 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/train_diffusion_dpo.py +983 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/train_diffusion_dpo_sdxl.py +1141 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/README.md +1 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/requirements.txt +7 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/train_diffusion_orpo_sdxl_lora.py +1093 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/train_diffusion_orpo_sdxl_lora_wds.py +1096 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/README.md +118 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/requirements.txt +7 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/train_dreambooth_inpaint.py +812 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/train_dreambooth_inpaint_lora.py +831 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/README.md +167 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/accelerate.yaml +17 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/compute_embeddings.py +107 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/ds2.yaml +23 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/train_dreambooth_lora_flux_miniature.py +1201 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/geodiff/README.md +6 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/geodiff/geodiff_molecule_conformation.ipynb +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/README.md +156 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/dataset.py +110 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/demo.ipynb +196 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/generated-images-100000-00.png +3 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/make_datasets.py +119 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/requirements.txt +11 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/train_gligen_text.py +715 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/instructpix2pix_lora/README.md +106 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/instructpix2pix_lora/train_instruct_pix2pix_lora.py +1171 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/README.md +36 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/inference_bf16.py +56 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/README.md +68 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/requirements.txt +7 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py +646 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md +93 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt +7 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py +112 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py +996 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/README.md +226 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/requirements.txt +4 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py +415 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py +422 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_plus.py +445 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py +520 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/README.md +83 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/requirements.txt +8 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/train_text_to_image_lora.py +1026 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lpl/README.md +157 -0
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/control_lora/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Control-LoRA inference example
|
| 2 |
+
|
| 3 |
+
Control-LoRA is introduced by Stability AI in [stabilityai/control-lora](https://huggingface.co/stabilityai/control-lora) by adding low-rank parameter efficient fine tuning to ControlNet. This approach offers a more efficient and compact method to bring model control to a wider variety of consumer GPUs.
|
| 4 |
+
|
| 5 |
+
## Installing the dependencies
|
| 6 |
+
|
| 7 |
+
Before running the scripts, make sure to install the library's training dependencies:
|
| 8 |
+
|
| 9 |
+
**Important**
|
| 10 |
+
|
| 11 |
+
To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
|
| 12 |
+
```bash
|
| 13 |
+
git clone https://github.com/huggingface/diffusers
|
| 14 |
+
cd diffusers
|
| 15 |
+
pip install .
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
Then cd in the example folder and run
|
| 19 |
+
```bash
|
| 20 |
+
pip install -r requirements.txt
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
accelerate config
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Inference on SDXL
|
| 30 |
+
|
| 31 |
+
[stabilityai/control-lora](https://huggingface.co/stabilityai/control-lora) provides a set of Control-LoRA weights for SDXL. Here we use the `canny` condition to generate an image from a text prompt and a reference image.
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python control_lora.py
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
## Acknowledgements
|
| 38 |
+
|
| 39 |
+
- [stabilityai/control-lora](https://huggingface.co/stabilityai/control-lora)
|
| 40 |
+
- [comfyanonymous/ControlNet-v1-1_fp16_safetensors](https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors)
|
| 41 |
+
- [HighCWu/control-lora-v2](https://github.com/HighCWu/control-lora-v2)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/control_lora/control_lora.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
from diffusers import (
|
| 7 |
+
AutoencoderKL,
|
| 8 |
+
ControlNetModel,
|
| 9 |
+
StableDiffusionXLControlNetPipeline,
|
| 10 |
+
UNet2DConditionModel,
|
| 11 |
+
)
|
| 12 |
+
from diffusers.utils import load_image, make_image_grid
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
pipe_id = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 16 |
+
lora_id = "stabilityai/control-lora"
|
| 17 |
+
lora_filename = "control-LoRAs-rank128/control-lora-canny-rank128.safetensors"
|
| 18 |
+
|
| 19 |
+
unet = UNet2DConditionModel.from_pretrained(pipe_id, subfolder="unet", torch_dtype=torch.bfloat16).to("cuda")
|
| 20 |
+
controlnet = ControlNetModel.from_unet(unet).to(device="cuda", dtype=torch.bfloat16)
|
| 21 |
+
controlnet.load_lora_adapter(lora_id, weight_name=lora_filename, prefix=None, controlnet_config=controlnet.config)
|
| 22 |
+
|
| 23 |
+
prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
|
| 24 |
+
negative_prompt = "low quality, bad quality, sketches"
|
| 25 |
+
|
| 26 |
+
image = load_image(
|
| 27 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
controlnet_conditioning_scale = 1.0 # recommended for good generalization
|
| 31 |
+
|
| 32 |
+
vae = AutoencoderKL.from_pretrained("stabilityai/sdxl-vae", torch_dtype=torch.bfloat16)
|
| 33 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 34 |
+
pipe_id,
|
| 35 |
+
unet=unet,
|
| 36 |
+
controlnet=controlnet,
|
| 37 |
+
vae=vae,
|
| 38 |
+
torch_dtype=torch.bfloat16,
|
| 39 |
+
safety_checker=None,
|
| 40 |
+
).to("cuda")
|
| 41 |
+
|
| 42 |
+
image = np.array(image)
|
| 43 |
+
image = cv2.Canny(image, 100, 200)
|
| 44 |
+
image = image[:, :, None]
|
| 45 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 46 |
+
image = Image.fromarray(image)
|
| 47 |
+
|
| 48 |
+
images = pipe(
|
| 49 |
+
prompt,
|
| 50 |
+
negative_prompt=negative_prompt,
|
| 51 |
+
image=image,
|
| 52 |
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
| 53 |
+
num_images_per_prompt=4,
|
| 54 |
+
).images
|
| 55 |
+
|
| 56 |
+
final_image = [image] + images
|
| 57 |
+
grid = make_image_grid(final_image, 1, 5)
|
| 58 |
+
grid.save("hf-logo_canny.png")
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/controlnet/train_controlnet_webdataset.py
ADDED
|
@@ -0,0 +1,1470 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import functools
|
| 19 |
+
import gc
|
| 20 |
+
import itertools
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import random
|
| 26 |
+
import shutil
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
from typing import List, Optional, Union
|
| 29 |
+
|
| 30 |
+
import accelerate
|
| 31 |
+
import cv2
|
| 32 |
+
import numpy as np
|
| 33 |
+
import torch
|
| 34 |
+
import torch.utils.checkpoint
|
| 35 |
+
import transformers
|
| 36 |
+
import webdataset as wds
|
| 37 |
+
from accelerate import Accelerator
|
| 38 |
+
from accelerate.logging import get_logger
|
| 39 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 40 |
+
from braceexpand import braceexpand
|
| 41 |
+
from huggingface_hub import create_repo, upload_folder
|
| 42 |
+
from packaging import version
|
| 43 |
+
from PIL import Image
|
| 44 |
+
from torch.utils.data import default_collate
|
| 45 |
+
from torchvision import transforms
|
| 46 |
+
from tqdm.auto import tqdm
|
| 47 |
+
from transformers import AutoTokenizer, DPTForDepthEstimation, DPTImageProcessor, PretrainedConfig
|
| 48 |
+
from webdataset.tariterators import (
|
| 49 |
+
base_plus_ext,
|
| 50 |
+
tar_file_expander,
|
| 51 |
+
url_opener,
|
| 52 |
+
valid_sample,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
import diffusers
|
| 56 |
+
from diffusers import (
|
| 57 |
+
AutoencoderKL,
|
| 58 |
+
ControlNetModel,
|
| 59 |
+
EulerDiscreteScheduler,
|
| 60 |
+
StableDiffusionXLControlNetPipeline,
|
| 61 |
+
UNet2DConditionModel,
|
| 62 |
+
)
|
| 63 |
+
from diffusers.optimization import get_scheduler
|
| 64 |
+
from diffusers.utils import check_min_version, is_wandb_available
|
| 65 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
MAX_SEQ_LENGTH = 77
|
| 69 |
+
|
| 70 |
+
if is_wandb_available():
|
| 71 |
+
import wandb
|
| 72 |
+
|
| 73 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 74 |
+
check_min_version("0.18.0.dev0")
|
| 75 |
+
|
| 76 |
+
logger = get_logger(__name__)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def filter_keys(key_set):
|
| 80 |
+
def _f(dictionary):
|
| 81 |
+
return {k: v for k, v in dictionary.items() if k in key_set}
|
| 82 |
+
|
| 83 |
+
return _f
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def group_by_keys_nothrow(data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None):
|
| 87 |
+
"""Return function over iterator that groups key, value pairs into samples.
|
| 88 |
+
|
| 89 |
+
:param keys: function that splits the key into key and extension (base_plus_ext)
|
| 90 |
+
:param lcase: convert suffixes to lower case (Default value = True)
|
| 91 |
+
"""
|
| 92 |
+
current_sample = None
|
| 93 |
+
for filesample in data:
|
| 94 |
+
assert isinstance(filesample, dict)
|
| 95 |
+
fname, value = filesample["fname"], filesample["data"]
|
| 96 |
+
prefix, suffix = keys(fname)
|
| 97 |
+
if prefix is None:
|
| 98 |
+
continue
|
| 99 |
+
if lcase:
|
| 100 |
+
suffix = suffix.lower()
|
| 101 |
+
# FIXME webdataset version throws if suffix in current_sample, but we have a potential for
|
| 102 |
+
# this happening in the current LAION400m dataset if a tar ends with same prefix as the next
|
| 103 |
+
# begins, rare, but can happen since prefix aren't unique across tar files in that dataset
|
| 104 |
+
if current_sample is None or prefix != current_sample["__key__"] or suffix in current_sample:
|
| 105 |
+
if valid_sample(current_sample):
|
| 106 |
+
yield current_sample
|
| 107 |
+
current_sample = {"__key__": prefix, "__url__": filesample["__url__"]}
|
| 108 |
+
if suffixes is None or suffix in suffixes:
|
| 109 |
+
current_sample[suffix] = value
|
| 110 |
+
if valid_sample(current_sample):
|
| 111 |
+
yield current_sample
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def tarfile_to_samples_nothrow(src, handler=wds.warn_and_continue):
|
| 115 |
+
# NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw
|
| 116 |
+
streams = url_opener(src, handler=handler)
|
| 117 |
+
files = tar_file_expander(streams, handler=handler)
|
| 118 |
+
samples = group_by_keys_nothrow(files, handler=handler)
|
| 119 |
+
return samples
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def control_transform(image):
|
| 123 |
+
image = np.array(image)
|
| 124 |
+
|
| 125 |
+
low_threshold = 100
|
| 126 |
+
high_threshold = 200
|
| 127 |
+
|
| 128 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 129 |
+
image = image[:, :, None]
|
| 130 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 131 |
+
control_image = Image.fromarray(image)
|
| 132 |
+
return control_image
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def canny_image_transform(example, resolution=1024):
|
| 136 |
+
image = example["image"]
|
| 137 |
+
image = transforms.Resize(resolution, interpolation=transforms.InterpolationMode.BILINEAR)(image)
|
| 138 |
+
# get crop coordinates
|
| 139 |
+
c_top, c_left, _, _ = transforms.RandomCrop.get_params(image, output_size=(resolution, resolution))
|
| 140 |
+
image = transforms.functional.crop(image, c_top, c_left, resolution, resolution)
|
| 141 |
+
control_image = control_transform(image)
|
| 142 |
+
|
| 143 |
+
image = transforms.ToTensor()(image)
|
| 144 |
+
image = transforms.Normalize([0.5], [0.5])(image)
|
| 145 |
+
control_image = transforms.ToTensor()(control_image)
|
| 146 |
+
|
| 147 |
+
example["image"] = image
|
| 148 |
+
example["control_image"] = control_image
|
| 149 |
+
example["crop_coords"] = (c_top, c_left)
|
| 150 |
+
|
| 151 |
+
return example
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def depth_image_transform(example, feature_extractor, resolution=1024):
|
| 155 |
+
image = example["image"]
|
| 156 |
+
image = transforms.Resize(resolution, interpolation=transforms.InterpolationMode.BILINEAR)(image)
|
| 157 |
+
# get crop coordinates
|
| 158 |
+
c_top, c_left, _, _ = transforms.RandomCrop.get_params(image, output_size=(resolution, resolution))
|
| 159 |
+
image = transforms.functional.crop(image, c_top, c_left, resolution, resolution)
|
| 160 |
+
|
| 161 |
+
control_image = feature_extractor(images=image, return_tensors="pt").pixel_values.squeeze(0)
|
| 162 |
+
|
| 163 |
+
image = transforms.ToTensor()(image)
|
| 164 |
+
image = transforms.Normalize([0.5], [0.5])(image)
|
| 165 |
+
|
| 166 |
+
example["image"] = image
|
| 167 |
+
example["control_image"] = control_image
|
| 168 |
+
example["crop_coords"] = (c_top, c_left)
|
| 169 |
+
|
| 170 |
+
return example
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class WebdatasetFilter:
|
| 174 |
+
def __init__(self, min_size=1024, max_pwatermark=0.5):
|
| 175 |
+
self.min_size = min_size
|
| 176 |
+
self.max_pwatermark = max_pwatermark
|
| 177 |
+
|
| 178 |
+
def __call__(self, x):
|
| 179 |
+
try:
|
| 180 |
+
if "json" in x:
|
| 181 |
+
x_json = json.loads(x["json"])
|
| 182 |
+
filter_size = (x_json.get("original_width", 0.0) or 0.0) >= self.min_size and x_json.get(
|
| 183 |
+
"original_height", 0
|
| 184 |
+
) >= self.min_size
|
| 185 |
+
filter_watermark = (x_json.get("pwatermark", 1.0) or 1.0) <= self.max_pwatermark
|
| 186 |
+
return filter_size and filter_watermark
|
| 187 |
+
else:
|
| 188 |
+
return False
|
| 189 |
+
except Exception:
|
| 190 |
+
return False
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class Text2ImageDataset:
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
train_shards_path_or_url: Union[str, List[str]],
|
| 197 |
+
eval_shards_path_or_url: Union[str, List[str]],
|
| 198 |
+
num_train_examples: int,
|
| 199 |
+
per_gpu_batch_size: int,
|
| 200 |
+
global_batch_size: int,
|
| 201 |
+
num_workers: int,
|
| 202 |
+
resolution: int = 256,
|
| 203 |
+
center_crop: bool = True,
|
| 204 |
+
random_flip: bool = False,
|
| 205 |
+
shuffle_buffer_size: int = 1000,
|
| 206 |
+
pin_memory: bool = False,
|
| 207 |
+
persistent_workers: bool = False,
|
| 208 |
+
control_type: str = "canny",
|
| 209 |
+
feature_extractor: Optional[DPTImageProcessor] = None,
|
| 210 |
+
):
|
| 211 |
+
if not isinstance(train_shards_path_or_url, str):
|
| 212 |
+
train_shards_path_or_url = [list(braceexpand(urls)) for urls in train_shards_path_or_url]
|
| 213 |
+
# flatten list using itertools
|
| 214 |
+
train_shards_path_or_url = list(itertools.chain.from_iterable(train_shards_path_or_url))
|
| 215 |
+
|
| 216 |
+
if not isinstance(eval_shards_path_or_url, str):
|
| 217 |
+
eval_shards_path_or_url = [list(braceexpand(urls)) for urls in eval_shards_path_or_url]
|
| 218 |
+
# flatten list using itertools
|
| 219 |
+
eval_shards_path_or_url = list(itertools.chain.from_iterable(eval_shards_path_or_url))
|
| 220 |
+
|
| 221 |
+
def get_orig_size(json):
|
| 222 |
+
return (int(json.get("original_width", 0.0)), int(json.get("original_height", 0.0)))
|
| 223 |
+
|
| 224 |
+
if control_type == "canny":
|
| 225 |
+
image_transform = functools.partial(canny_image_transform, resolution=resolution)
|
| 226 |
+
elif control_type == "depth":
|
| 227 |
+
image_transform = functools.partial(
|
| 228 |
+
depth_image_transform, feature_extractor=feature_extractor, resolution=resolution
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
processing_pipeline = [
|
| 232 |
+
wds.decode("pil", handler=wds.ignore_and_continue),
|
| 233 |
+
wds.rename(
|
| 234 |
+
image="jpg;png;jpeg;webp",
|
| 235 |
+
control_image="jpg;png;jpeg;webp",
|
| 236 |
+
text="text;txt;caption",
|
| 237 |
+
orig_size="json",
|
| 238 |
+
handler=wds.warn_and_continue,
|
| 239 |
+
),
|
| 240 |
+
wds.map(filter_keys({"image", "control_image", "text", "orig_size"})),
|
| 241 |
+
wds.map_dict(orig_size=get_orig_size),
|
| 242 |
+
wds.map(image_transform),
|
| 243 |
+
wds.to_tuple("image", "control_image", "text", "orig_size", "crop_coords"),
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
# Create train dataset and loader
|
| 247 |
+
pipeline = [
|
| 248 |
+
wds.ResampledShards(train_shards_path_or_url),
|
| 249 |
+
tarfile_to_samples_nothrow,
|
| 250 |
+
wds.select(WebdatasetFilter(min_size=512)),
|
| 251 |
+
wds.shuffle(shuffle_buffer_size),
|
| 252 |
+
*processing_pipeline,
|
| 253 |
+
wds.batched(per_gpu_batch_size, partial=False, collation_fn=default_collate),
|
| 254 |
+
]
|
| 255 |
+
|
| 256 |
+
num_worker_batches = math.ceil(num_train_examples / (global_batch_size * num_workers)) # per dataloader worker
|
| 257 |
+
num_batches = num_worker_batches * num_workers
|
| 258 |
+
num_samples = num_batches * global_batch_size
|
| 259 |
+
|
| 260 |
+
# each worker is iterating over this
|
| 261 |
+
self._train_dataset = wds.DataPipeline(*pipeline).with_epoch(num_worker_batches)
|
| 262 |
+
self._train_dataloader = wds.WebLoader(
|
| 263 |
+
self._train_dataset,
|
| 264 |
+
batch_size=None,
|
| 265 |
+
shuffle=False,
|
| 266 |
+
num_workers=num_workers,
|
| 267 |
+
pin_memory=pin_memory,
|
| 268 |
+
persistent_workers=persistent_workers,
|
| 269 |
+
)
|
| 270 |
+
# add meta-data to dataloader instance for convenience
|
| 271 |
+
self._train_dataloader.num_batches = num_batches
|
| 272 |
+
self._train_dataloader.num_samples = num_samples
|
| 273 |
+
|
| 274 |
+
# Create eval dataset and loader
|
| 275 |
+
pipeline = [
|
| 276 |
+
wds.SimpleShardList(eval_shards_path_or_url),
|
| 277 |
+
wds.split_by_worker,
|
| 278 |
+
wds.tarfile_to_samples(handler=wds.ignore_and_continue),
|
| 279 |
+
*processing_pipeline,
|
| 280 |
+
wds.batched(per_gpu_batch_size, partial=False, collation_fn=default_collate),
|
| 281 |
+
]
|
| 282 |
+
self._eval_dataset = wds.DataPipeline(*pipeline)
|
| 283 |
+
self._eval_dataloader = wds.WebLoader(
|
| 284 |
+
self._eval_dataset,
|
| 285 |
+
batch_size=None,
|
| 286 |
+
shuffle=False,
|
| 287 |
+
num_workers=num_workers,
|
| 288 |
+
pin_memory=pin_memory,
|
| 289 |
+
persistent_workers=persistent_workers,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
@property
|
| 293 |
+
def train_dataset(self):
|
| 294 |
+
return self._train_dataset
|
| 295 |
+
|
| 296 |
+
@property
|
| 297 |
+
def train_dataloader(self):
|
| 298 |
+
return self._train_dataloader
|
| 299 |
+
|
| 300 |
+
@property
|
| 301 |
+
def eval_dataset(self):
|
| 302 |
+
return self._eval_dataset
|
| 303 |
+
|
| 304 |
+
@property
|
| 305 |
+
def eval_dataloader(self):
|
| 306 |
+
return self._eval_dataloader
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def image_grid(imgs, rows, cols):
|
| 310 |
+
assert len(imgs) == rows * cols
|
| 311 |
+
|
| 312 |
+
w, h = imgs[0].size
|
| 313 |
+
grid = Image.new("RGB", size=(cols * w, rows * h))
|
| 314 |
+
|
| 315 |
+
for i, img in enumerate(imgs):
|
| 316 |
+
grid.paste(img, box=(i % cols * w, i // cols * h))
|
| 317 |
+
return grid
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def log_validation(vae, unet, controlnet, args, accelerator, weight_dtype, step):
|
| 321 |
+
logger.info("Running validation... ")
|
| 322 |
+
|
| 323 |
+
controlnet = accelerator.unwrap_model(controlnet)
|
| 324 |
+
|
| 325 |
+
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 326 |
+
args.pretrained_model_name_or_path,
|
| 327 |
+
vae=vae,
|
| 328 |
+
unet=unet,
|
| 329 |
+
controlnet=controlnet,
|
| 330 |
+
revision=args.revision,
|
| 331 |
+
torch_dtype=weight_dtype,
|
| 332 |
+
)
|
| 333 |
+
# pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config)
|
| 334 |
+
pipeline = pipeline.to(accelerator.device)
|
| 335 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 336 |
+
|
| 337 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 338 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 339 |
+
|
| 340 |
+
if args.seed is None:
|
| 341 |
+
generator = None
|
| 342 |
+
else:
|
| 343 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 344 |
+
|
| 345 |
+
if len(args.validation_image) == len(args.validation_prompt):
|
| 346 |
+
validation_images = args.validation_image
|
| 347 |
+
validation_prompts = args.validation_prompt
|
| 348 |
+
elif len(args.validation_image) == 1:
|
| 349 |
+
validation_images = args.validation_image * len(args.validation_prompt)
|
| 350 |
+
validation_prompts = args.validation_prompt
|
| 351 |
+
elif len(args.validation_prompt) == 1:
|
| 352 |
+
validation_images = args.validation_image
|
| 353 |
+
validation_prompts = args.validation_prompt * len(args.validation_image)
|
| 354 |
+
else:
|
| 355 |
+
raise ValueError(
|
| 356 |
+
"number of `args.validation_image` and `args.validation_prompt` should be checked in `parse_args`"
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
image_logs = []
|
| 360 |
+
|
| 361 |
+
for validation_prompt, validation_image in zip(validation_prompts, validation_images):
|
| 362 |
+
validation_image = Image.open(validation_image).convert("RGB")
|
| 363 |
+
validation_image = validation_image.resize((args.resolution, args.resolution))
|
| 364 |
+
|
| 365 |
+
images = []
|
| 366 |
+
|
| 367 |
+
for _ in range(args.num_validation_images):
|
| 368 |
+
with torch.autocast("cuda"):
|
| 369 |
+
image = pipeline(
|
| 370 |
+
validation_prompt, image=validation_image, num_inference_steps=20, generator=generator
|
| 371 |
+
).images[0]
|
| 372 |
+
images.append(image)
|
| 373 |
+
|
| 374 |
+
image_logs.append(
|
| 375 |
+
{"validation_image": validation_image, "images": images, "validation_prompt": validation_prompt}
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
for tracker in accelerator.trackers:
|
| 379 |
+
if tracker.name == "tensorboard":
|
| 380 |
+
for log in image_logs:
|
| 381 |
+
images = log["images"]
|
| 382 |
+
validation_prompt = log["validation_prompt"]
|
| 383 |
+
validation_image = log["validation_image"]
|
| 384 |
+
|
| 385 |
+
formatted_images = [np.asarray(validation_image)]
|
| 386 |
+
|
| 387 |
+
for image in images:
|
| 388 |
+
formatted_images.append(np.asarray(image))
|
| 389 |
+
|
| 390 |
+
formatted_images = np.stack(formatted_images)
|
| 391 |
+
|
| 392 |
+
tracker.writer.add_images(validation_prompt, formatted_images, step, dataformats="NHWC")
|
| 393 |
+
elif tracker.name == "wandb":
|
| 394 |
+
formatted_images = []
|
| 395 |
+
|
| 396 |
+
for log in image_logs:
|
| 397 |
+
images = log["images"]
|
| 398 |
+
validation_prompt = log["validation_prompt"]
|
| 399 |
+
validation_image = log["validation_image"]
|
| 400 |
+
|
| 401 |
+
formatted_images.append(wandb.Image(validation_image, caption="Controlnet conditioning"))
|
| 402 |
+
|
| 403 |
+
for image in images:
|
| 404 |
+
image = wandb.Image(image, caption=validation_prompt)
|
| 405 |
+
formatted_images.append(image)
|
| 406 |
+
|
| 407 |
+
tracker.log({"validation": formatted_images})
|
| 408 |
+
else:
|
| 409 |
+
logger.warning(f"image logging not implemented for {tracker.name}")
|
| 410 |
+
|
| 411 |
+
del pipeline
|
| 412 |
+
gc.collect()
|
| 413 |
+
torch.cuda.empty_cache()
|
| 414 |
+
|
| 415 |
+
return image_logs
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def import_model_class_from_model_name_or_path(
|
| 419 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 420 |
+
):
|
| 421 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 422 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 423 |
+
)
|
| 424 |
+
model_class = text_encoder_config.architectures[0]
|
| 425 |
+
|
| 426 |
+
if model_class == "CLIPTextModel":
|
| 427 |
+
from transformers import CLIPTextModel
|
| 428 |
+
|
| 429 |
+
return CLIPTextModel
|
| 430 |
+
elif model_class == "CLIPTextModelWithProjection":
|
| 431 |
+
from transformers import CLIPTextModelWithProjection
|
| 432 |
+
|
| 433 |
+
return CLIPTextModelWithProjection
|
| 434 |
+
else:
|
| 435 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def save_model_card(repo_id: str, image_logs=None, base_model=str, repo_folder=None):
|
| 439 |
+
img_str = ""
|
| 440 |
+
if image_logs is not None:
|
| 441 |
+
img_str = "You can find some example images below.\n"
|
| 442 |
+
for i, log in enumerate(image_logs):
|
| 443 |
+
images = log["images"]
|
| 444 |
+
validation_prompt = log["validation_prompt"]
|
| 445 |
+
validation_image = log["validation_image"]
|
| 446 |
+
validation_image.save(os.path.join(repo_folder, "image_control.png"))
|
| 447 |
+
img_str += f"prompt: {validation_prompt}\n"
|
| 448 |
+
images = [validation_image] + images
|
| 449 |
+
image_grid(images, 1, len(images)).save(os.path.join(repo_folder, f"images_{i}.png"))
|
| 450 |
+
img_str += f"\n"
|
| 451 |
+
|
| 452 |
+
yaml = f"""
|
| 453 |
+
---
|
| 454 |
+
license: creativeml-openrail-m
|
| 455 |
+
base_model: {base_model}
|
| 456 |
+
tags:
|
| 457 |
+
- stable-diffusion-xl
|
| 458 |
+
- stable-diffusion-xl-diffusers
|
| 459 |
+
- text-to-image
|
| 460 |
+
- diffusers
|
| 461 |
+
- controlnet
|
| 462 |
+
- diffusers-training
|
| 463 |
+
- webdataset
|
| 464 |
+
inference: true
|
| 465 |
+
---
|
| 466 |
+
"""
|
| 467 |
+
model_card = f"""
|
| 468 |
+
# controlnet-{repo_id}
|
| 469 |
+
|
| 470 |
+
These are controlnet weights trained on {base_model} with new type of conditioning.
|
| 471 |
+
{img_str}
|
| 472 |
+
"""
|
| 473 |
+
with open(os.path.join(repo_folder, "README.md"), "w") as f:
|
| 474 |
+
f.write(yaml + model_card)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_args(input_args=None):
|
| 478 |
+
parser = argparse.ArgumentParser(description="Simple example of a ControlNet training script.")
|
| 479 |
+
parser.add_argument(
|
| 480 |
+
"--pretrained_model_name_or_path",
|
| 481 |
+
type=str,
|
| 482 |
+
default=None,
|
| 483 |
+
required=True,
|
| 484 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 485 |
+
)
|
| 486 |
+
parser.add_argument(
|
| 487 |
+
"--pretrained_vae_model_name_or_path",
|
| 488 |
+
type=str,
|
| 489 |
+
default=None,
|
| 490 |
+
help="Path to an improved VAE to stabilize training. For more details check out: https://github.com/huggingface/diffusers/pull/4038.",
|
| 491 |
+
)
|
| 492 |
+
parser.add_argument(
|
| 493 |
+
"--controlnet_model_name_or_path",
|
| 494 |
+
type=str,
|
| 495 |
+
default=None,
|
| 496 |
+
help="Path to pretrained controlnet model or model identifier from huggingface.co/models."
|
| 497 |
+
" If not specified controlnet weights are initialized from unet.",
|
| 498 |
+
)
|
| 499 |
+
parser.add_argument(
|
| 500 |
+
"--revision",
|
| 501 |
+
type=str,
|
| 502 |
+
default=None,
|
| 503 |
+
required=False,
|
| 504 |
+
help=(
|
| 505 |
+
"Revision of pretrained model identifier from huggingface.co/models. Trainable model components should be"
|
| 506 |
+
" float32 precision."
|
| 507 |
+
),
|
| 508 |
+
)
|
| 509 |
+
parser.add_argument(
|
| 510 |
+
"--tokenizer_name",
|
| 511 |
+
type=str,
|
| 512 |
+
default=None,
|
| 513 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 514 |
+
)
|
| 515 |
+
parser.add_argument(
|
| 516 |
+
"--output_dir",
|
| 517 |
+
type=str,
|
| 518 |
+
default="controlnet-model",
|
| 519 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 520 |
+
)
|
| 521 |
+
parser.add_argument(
|
| 522 |
+
"--cache_dir",
|
| 523 |
+
type=str,
|
| 524 |
+
default=None,
|
| 525 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 526 |
+
)
|
| 527 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 528 |
+
parser.add_argument(
|
| 529 |
+
"--resolution",
|
| 530 |
+
type=int,
|
| 531 |
+
default=512,
|
| 532 |
+
help=(
|
| 533 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 534 |
+
" resolution"
|
| 535 |
+
),
|
| 536 |
+
)
|
| 537 |
+
parser.add_argument(
|
| 538 |
+
"--crops_coords_top_left_h",
|
| 539 |
+
type=int,
|
| 540 |
+
default=0,
|
| 541 |
+
help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
|
| 542 |
+
)
|
| 543 |
+
parser.add_argument(
|
| 544 |
+
"--crops_coords_top_left_w",
|
| 545 |
+
type=int,
|
| 546 |
+
default=0,
|
| 547 |
+
help=("Coordinate for (the height) to be included in the crop coordinate embeddings needed by SDXL UNet."),
|
| 548 |
+
)
|
| 549 |
+
parser.add_argument(
|
| 550 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 551 |
+
)
|
| 552 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 553 |
+
parser.add_argument(
|
| 554 |
+
"--max_train_steps",
|
| 555 |
+
type=int,
|
| 556 |
+
default=None,
|
| 557 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 558 |
+
)
|
| 559 |
+
parser.add_argument(
|
| 560 |
+
"--checkpointing_steps",
|
| 561 |
+
type=int,
|
| 562 |
+
default=500,
|
| 563 |
+
help=(
|
| 564 |
+
"Save a checkpoint of the training state every X updates. Checkpoints can be used for resuming training via `--resume_from_checkpoint`. "
|
| 565 |
+
"In the case that the checkpoint is better than the final trained model, the checkpoint can also be used for inference."
|
| 566 |
+
"Using a checkpoint for inference requires separate loading of the original pipeline and the individual checkpointed model components."
|
| 567 |
+
"See https://huggingface.co/docs/diffusers/main/en/training/dreambooth#performing-inference-using-a-saved-checkpoint for step by step"
|
| 568 |
+
"instructions."
|
| 569 |
+
),
|
| 570 |
+
)
|
| 571 |
+
parser.add_argument(
|
| 572 |
+
"--checkpoints_total_limit",
|
| 573 |
+
type=int,
|
| 574 |
+
default=3,
|
| 575 |
+
help=("Max number of checkpoints to store."),
|
| 576 |
+
)
|
| 577 |
+
parser.add_argument(
|
| 578 |
+
"--resume_from_checkpoint",
|
| 579 |
+
type=str,
|
| 580 |
+
default=None,
|
| 581 |
+
help=(
|
| 582 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 583 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 584 |
+
),
|
| 585 |
+
)
|
| 586 |
+
parser.add_argument(
|
| 587 |
+
"--gradient_accumulation_steps",
|
| 588 |
+
type=int,
|
| 589 |
+
default=1,
|
| 590 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 591 |
+
)
|
| 592 |
+
parser.add_argument(
|
| 593 |
+
"--gradient_checkpointing",
|
| 594 |
+
action="store_true",
|
| 595 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 596 |
+
)
|
| 597 |
+
parser.add_argument(
|
| 598 |
+
"--learning_rate",
|
| 599 |
+
type=float,
|
| 600 |
+
default=5e-6,
|
| 601 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 602 |
+
)
|
| 603 |
+
parser.add_argument(
|
| 604 |
+
"--scale_lr",
|
| 605 |
+
action="store_true",
|
| 606 |
+
default=False,
|
| 607 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 608 |
+
)
|
| 609 |
+
parser.add_argument(
|
| 610 |
+
"--lr_scheduler",
|
| 611 |
+
type=str,
|
| 612 |
+
default="constant",
|
| 613 |
+
help=(
|
| 614 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 615 |
+
' "constant", "constant_with_warmup"]'
|
| 616 |
+
),
|
| 617 |
+
)
|
| 618 |
+
parser.add_argument(
|
| 619 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 620 |
+
)
|
| 621 |
+
parser.add_argument(
|
| 622 |
+
"--lr_num_cycles",
|
| 623 |
+
type=int,
|
| 624 |
+
default=1,
|
| 625 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 626 |
+
)
|
| 627 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 628 |
+
parser.add_argument(
|
| 629 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 630 |
+
)
|
| 631 |
+
parser.add_argument(
|
| 632 |
+
"--dataloader_num_workers",
|
| 633 |
+
type=int,
|
| 634 |
+
default=1,
|
| 635 |
+
help=("Number of subprocesses to use for data loading."),
|
| 636 |
+
)
|
| 637 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 638 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 639 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 640 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 641 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 642 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 643 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 644 |
+
parser.add_argument(
|
| 645 |
+
"--hub_model_id",
|
| 646 |
+
type=str,
|
| 647 |
+
default=None,
|
| 648 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 649 |
+
)
|
| 650 |
+
parser.add_argument(
|
| 651 |
+
"--logging_dir",
|
| 652 |
+
type=str,
|
| 653 |
+
default="logs",
|
| 654 |
+
help=(
|
| 655 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 656 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 657 |
+
),
|
| 658 |
+
)
|
| 659 |
+
parser.add_argument(
|
| 660 |
+
"--allow_tf32",
|
| 661 |
+
action="store_true",
|
| 662 |
+
help=(
|
| 663 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 664 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 665 |
+
),
|
| 666 |
+
)
|
| 667 |
+
parser.add_argument(
|
| 668 |
+
"--report_to",
|
| 669 |
+
type=str,
|
| 670 |
+
default="tensorboard",
|
| 671 |
+
help=(
|
| 672 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 673 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 674 |
+
),
|
| 675 |
+
)
|
| 676 |
+
parser.add_argument(
|
| 677 |
+
"--mixed_precision",
|
| 678 |
+
type=str,
|
| 679 |
+
default=None,
|
| 680 |
+
choices=["no", "fp16", "bf16"],
|
| 681 |
+
help=(
|
| 682 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 683 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 684 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 685 |
+
),
|
| 686 |
+
)
|
| 687 |
+
parser.add_argument(
|
| 688 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 689 |
+
)
|
| 690 |
+
parser.add_argument(
|
| 691 |
+
"--set_grads_to_none",
|
| 692 |
+
action="store_true",
|
| 693 |
+
help=(
|
| 694 |
+
"Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
|
| 695 |
+
" behaviors, so disable this argument if it causes any problems. More info:"
|
| 696 |
+
" https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
|
| 697 |
+
),
|
| 698 |
+
)
|
| 699 |
+
parser.add_argument(
|
| 700 |
+
"--train_shards_path_or_url",
|
| 701 |
+
type=str,
|
| 702 |
+
default=None,
|
| 703 |
+
help=(
|
| 704 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 705 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 706 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 707 |
+
),
|
| 708 |
+
)
|
| 709 |
+
parser.add_argument(
|
| 710 |
+
"--eval_shards_path_or_url",
|
| 711 |
+
type=str,
|
| 712 |
+
default=None,
|
| 713 |
+
help="The config of the Dataset, leave as None if there's only one config.",
|
| 714 |
+
)
|
| 715 |
+
parser.add_argument(
|
| 716 |
+
"--train_data_dir",
|
| 717 |
+
type=str,
|
| 718 |
+
default=None,
|
| 719 |
+
help=(
|
| 720 |
+
"A folder containing the training data. Folder contents must follow the structure described in"
|
| 721 |
+
" https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
|
| 722 |
+
" must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
|
| 723 |
+
),
|
| 724 |
+
)
|
| 725 |
+
parser.add_argument(
|
| 726 |
+
"--image_column", type=str, default="image", help="The column of the dataset containing the target image."
|
| 727 |
+
)
|
| 728 |
+
parser.add_argument(
|
| 729 |
+
"--conditioning_image_column",
|
| 730 |
+
type=str,
|
| 731 |
+
default="conditioning_image",
|
| 732 |
+
help="The column of the dataset containing the controlnet conditioning image.",
|
| 733 |
+
)
|
| 734 |
+
parser.add_argument(
|
| 735 |
+
"--caption_column",
|
| 736 |
+
type=str,
|
| 737 |
+
default="text",
|
| 738 |
+
help="The column of the dataset containing a caption or a list of captions.",
|
| 739 |
+
)
|
| 740 |
+
parser.add_argument(
|
| 741 |
+
"--max_train_samples",
|
| 742 |
+
type=int,
|
| 743 |
+
default=None,
|
| 744 |
+
help=(
|
| 745 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 746 |
+
"value if set."
|
| 747 |
+
),
|
| 748 |
+
)
|
| 749 |
+
parser.add_argument(
|
| 750 |
+
"--proportion_empty_prompts",
|
| 751 |
+
type=float,
|
| 752 |
+
default=0,
|
| 753 |
+
help="Proportion of image prompts to be replaced with empty strings. Defaults to 0 (no prompt replacement).",
|
| 754 |
+
)
|
| 755 |
+
parser.add_argument(
|
| 756 |
+
"--validation_prompt",
|
| 757 |
+
type=str,
|
| 758 |
+
default=None,
|
| 759 |
+
nargs="+",
|
| 760 |
+
help=(
|
| 761 |
+
"A set of prompts evaluated every `--validation_steps` and logged to `--report_to`."
|
| 762 |
+
" Provide either a matching number of `--validation_image`s, a single `--validation_image`"
|
| 763 |
+
" to be used with all prompts, or a single prompt that will be used with all `--validation_image`s."
|
| 764 |
+
),
|
| 765 |
+
)
|
| 766 |
+
parser.add_argument(
|
| 767 |
+
"--validation_image",
|
| 768 |
+
type=str,
|
| 769 |
+
default=None,
|
| 770 |
+
nargs="+",
|
| 771 |
+
help=(
|
| 772 |
+
"A set of paths to the controlnet conditioning image be evaluated every `--validation_steps`"
|
| 773 |
+
" and logged to `--report_to`. Provide either a matching number of `--validation_prompt`s, a"
|
| 774 |
+
" a single `--validation_prompt` to be used with all `--validation_image`s, or a single"
|
| 775 |
+
" `--validation_image` that will be used with all `--validation_prompt`s."
|
| 776 |
+
),
|
| 777 |
+
)
|
| 778 |
+
parser.add_argument(
|
| 779 |
+
"--num_validation_images",
|
| 780 |
+
type=int,
|
| 781 |
+
default=4,
|
| 782 |
+
help="Number of images to be generated for each `--validation_image`, `--validation_prompt` pair",
|
| 783 |
+
)
|
| 784 |
+
parser.add_argument(
|
| 785 |
+
"--validation_steps",
|
| 786 |
+
type=int,
|
| 787 |
+
default=100,
|
| 788 |
+
help=(
|
| 789 |
+
"Run validation every X steps. Validation consists of running the prompt"
|
| 790 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`"
|
| 791 |
+
" and logging the images."
|
| 792 |
+
),
|
| 793 |
+
)
|
| 794 |
+
parser.add_argument(
|
| 795 |
+
"--tracker_project_name",
|
| 796 |
+
type=str,
|
| 797 |
+
default="sd_xl_train_controlnet",
|
| 798 |
+
help=(
|
| 799 |
+
"The `project_name` argument passed to Accelerator.init_trackers for"
|
| 800 |
+
" more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
|
| 801 |
+
),
|
| 802 |
+
)
|
| 803 |
+
parser.add_argument(
|
| 804 |
+
"--control_type",
|
| 805 |
+
type=str,
|
| 806 |
+
default="canny",
|
| 807 |
+
help=("The type of controlnet conditioning image to use. One of `canny`, `depth` Defaults to `canny`."),
|
| 808 |
+
)
|
| 809 |
+
parser.add_argument(
|
| 810 |
+
"--transformer_layers_per_block",
|
| 811 |
+
type=str,
|
| 812 |
+
default=None,
|
| 813 |
+
help=("The number of layers per block in the transformer. If None, defaults to `args.transformer_layers`."),
|
| 814 |
+
)
|
| 815 |
+
parser.add_argument(
|
| 816 |
+
"--old_style_controlnet",
|
| 817 |
+
action="store_true",
|
| 818 |
+
default=False,
|
| 819 |
+
help=(
|
| 820 |
+
"Use the old style controlnet, which is a single transformer layer with a single head. Defaults to False."
|
| 821 |
+
),
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
if input_args is not None:
|
| 825 |
+
args = parser.parse_args(input_args)
|
| 826 |
+
else:
|
| 827 |
+
args = parser.parse_args()
|
| 828 |
+
|
| 829 |
+
if args.proportion_empty_prompts < 0 or args.proportion_empty_prompts > 1:
|
| 830 |
+
raise ValueError("`--proportion_empty_prompts` must be in the range [0, 1].")
|
| 831 |
+
|
| 832 |
+
if args.validation_prompt is not None and args.validation_image is None:
|
| 833 |
+
raise ValueError("`--validation_image` must be set if `--validation_prompt` is set")
|
| 834 |
+
|
| 835 |
+
if args.validation_prompt is None and args.validation_image is not None:
|
| 836 |
+
raise ValueError("`--validation_prompt` must be set if `--validation_image` is set")
|
| 837 |
+
|
| 838 |
+
if (
|
| 839 |
+
args.validation_image is not None
|
| 840 |
+
and args.validation_prompt is not None
|
| 841 |
+
and len(args.validation_image) != 1
|
| 842 |
+
and len(args.validation_prompt) != 1
|
| 843 |
+
and len(args.validation_image) != len(args.validation_prompt)
|
| 844 |
+
):
|
| 845 |
+
raise ValueError(
|
| 846 |
+
"Must provide either 1 `--validation_image`, 1 `--validation_prompt`,"
|
| 847 |
+
" or the same number of `--validation_prompt`s and `--validation_image`s"
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
if args.resolution % 8 != 0:
|
| 851 |
+
raise ValueError(
|
| 852 |
+
"`--resolution` must be divisible by 8 for consistently sized encoded images between the VAE and the controlnet encoder."
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
return args
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
# Adapted from pipelines.StableDiffusionXLPipeline.encode_prompt
|
| 859 |
+
def encode_prompt(prompt_batch, text_encoders, tokenizers, proportion_empty_prompts, is_train=True):
|
| 860 |
+
prompt_embeds_list = []
|
| 861 |
+
|
| 862 |
+
captions = []
|
| 863 |
+
for caption in prompt_batch:
|
| 864 |
+
if random.random() < proportion_empty_prompts:
|
| 865 |
+
captions.append("")
|
| 866 |
+
elif isinstance(caption, str):
|
| 867 |
+
captions.append(caption)
|
| 868 |
+
elif isinstance(caption, (list, np.ndarray)):
|
| 869 |
+
# take a random caption if there are multiple
|
| 870 |
+
captions.append(random.choice(caption) if is_train else caption[0])
|
| 871 |
+
|
| 872 |
+
with torch.no_grad():
|
| 873 |
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
| 874 |
+
text_inputs = tokenizer(
|
| 875 |
+
captions,
|
| 876 |
+
padding="max_length",
|
| 877 |
+
max_length=tokenizer.model_max_length,
|
| 878 |
+
truncation=True,
|
| 879 |
+
return_tensors="pt",
|
| 880 |
+
)
|
| 881 |
+
text_input_ids = text_inputs.input_ids
|
| 882 |
+
prompt_embeds = text_encoder(
|
| 883 |
+
text_input_ids.to(text_encoder.device),
|
| 884 |
+
output_hidden_states=True,
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 888 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
| 889 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 890 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 891 |
+
prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
|
| 892 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 893 |
+
|
| 894 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 895 |
+
pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
|
| 896 |
+
return prompt_embeds, pooled_prompt_embeds
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def main(args):
|
| 900 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 901 |
+
raise ValueError(
|
| 902 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 903 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 907 |
+
|
| 908 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 909 |
+
|
| 910 |
+
accelerator = Accelerator(
|
| 911 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 912 |
+
mixed_precision=args.mixed_precision,
|
| 913 |
+
log_with=args.report_to,
|
| 914 |
+
project_config=accelerator_project_config,
|
| 915 |
+
)
|
| 916 |
+
|
| 917 |
+
# Disable AMP for MPS.
|
| 918 |
+
if torch.backends.mps.is_available():
|
| 919 |
+
accelerator.native_amp = False
|
| 920 |
+
|
| 921 |
+
# Make one log on every process with the configuration for debugging.
|
| 922 |
+
logging.basicConfig(
|
| 923 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 924 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 925 |
+
level=logging.INFO,
|
| 926 |
+
)
|
| 927 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 928 |
+
if accelerator.is_local_main_process:
|
| 929 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 930 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 931 |
+
else:
|
| 932 |
+
transformers.utils.logging.set_verbosity_error()
|
| 933 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 934 |
+
|
| 935 |
+
# If passed along, set the training seed now.
|
| 936 |
+
if args.seed is not None:
|
| 937 |
+
set_seed(args.seed)
|
| 938 |
+
|
| 939 |
+
# Handle the repository creation
|
| 940 |
+
if accelerator.is_main_process:
|
| 941 |
+
if args.output_dir is not None:
|
| 942 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 943 |
+
|
| 944 |
+
if args.push_to_hub:
|
| 945 |
+
repo_id = create_repo(
|
| 946 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name,
|
| 947 |
+
exist_ok=True,
|
| 948 |
+
token=args.hub_token,
|
| 949 |
+
private=True,
|
| 950 |
+
).repo_id
|
| 951 |
+
|
| 952 |
+
# Load the tokenizers
|
| 953 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 954 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, use_fast=False
|
| 955 |
+
)
|
| 956 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 957 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer_2", revision=args.revision, use_fast=False
|
| 958 |
+
)
|
| 959 |
+
|
| 960 |
+
# import correct text encoder classes
|
| 961 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 962 |
+
args.pretrained_model_name_or_path, args.revision
|
| 963 |
+
)
|
| 964 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 965 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
# Load scheduler and models
|
| 969 |
+
# noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 970 |
+
noise_scheduler = EulerDiscreteScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 971 |
+
text_encoder_one = text_encoder_cls_one.from_pretrained(
|
| 972 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 973 |
+
)
|
| 974 |
+
text_encoder_two = text_encoder_cls_two.from_pretrained(
|
| 975 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision
|
| 976 |
+
)
|
| 977 |
+
vae_path = (
|
| 978 |
+
args.pretrained_model_name_or_path
|
| 979 |
+
if args.pretrained_vae_model_name_or_path is None
|
| 980 |
+
else args.pretrained_vae_model_name_or_path
|
| 981 |
+
)
|
| 982 |
+
vae = AutoencoderKL.from_pretrained(
|
| 983 |
+
vae_path,
|
| 984 |
+
subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
|
| 985 |
+
revision=args.revision,
|
| 986 |
+
)
|
| 987 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 988 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
if args.controlnet_model_name_or_path:
|
| 992 |
+
logger.info("Loading existing controlnet weights")
|
| 993 |
+
pre_controlnet = ControlNetModel.from_pretrained(args.controlnet_model_name_or_path)
|
| 994 |
+
else:
|
| 995 |
+
logger.info("Initializing controlnet weights from unet")
|
| 996 |
+
pre_controlnet = ControlNetModel.from_unet(unet)
|
| 997 |
+
|
| 998 |
+
if args.transformer_layers_per_block is not None:
|
| 999 |
+
transformer_layers_per_block = [int(x) for x in args.transformer_layers_per_block.split(",")]
|
| 1000 |
+
down_block_types = ["DownBlock2D" if l == 0 else "CrossAttnDownBlock2D" for l in transformer_layers_per_block]
|
| 1001 |
+
controlnet = ControlNetModel.from_config(
|
| 1002 |
+
pre_controlnet.config,
|
| 1003 |
+
down_block_types=down_block_types,
|
| 1004 |
+
transformer_layers_per_block=transformer_layers_per_block,
|
| 1005 |
+
)
|
| 1006 |
+
controlnet.load_state_dict(pre_controlnet.state_dict(), strict=False)
|
| 1007 |
+
del pre_controlnet
|
| 1008 |
+
else:
|
| 1009 |
+
controlnet = pre_controlnet
|
| 1010 |
+
|
| 1011 |
+
if args.control_type == "depth":
|
| 1012 |
+
feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
|
| 1013 |
+
depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas")
|
| 1014 |
+
depth_model.requires_grad_(False)
|
| 1015 |
+
else:
|
| 1016 |
+
feature_extractor = None
|
| 1017 |
+
depth_model = None
|
| 1018 |
+
|
| 1019 |
+
# `accelerate` 0.16.0 will have better support for customized saving
|
| 1020 |
+
if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
|
| 1021 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 1022 |
+
def save_model_hook(models, weights, output_dir):
|
| 1023 |
+
if accelerator.is_main_process:
|
| 1024 |
+
i = len(weights) - 1
|
| 1025 |
+
|
| 1026 |
+
while len(weights) > 0:
|
| 1027 |
+
weights.pop()
|
| 1028 |
+
model = models[i]
|
| 1029 |
+
|
| 1030 |
+
sub_dir = "controlnet"
|
| 1031 |
+
model.save_pretrained(os.path.join(output_dir, sub_dir))
|
| 1032 |
+
|
| 1033 |
+
i -= 1
|
| 1034 |
+
|
| 1035 |
+
def load_model_hook(models, input_dir):
|
| 1036 |
+
while len(models) > 0:
|
| 1037 |
+
# pop models so that they are not loaded again
|
| 1038 |
+
model = models.pop()
|
| 1039 |
+
|
| 1040 |
+
# load diffusers style into model
|
| 1041 |
+
load_model = ControlNetModel.from_pretrained(input_dir, subfolder="controlnet")
|
| 1042 |
+
model.register_to_config(**load_model.config)
|
| 1043 |
+
|
| 1044 |
+
model.load_state_dict(load_model.state_dict())
|
| 1045 |
+
del load_model
|
| 1046 |
+
|
| 1047 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 1048 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 1049 |
+
|
| 1050 |
+
vae.requires_grad_(False)
|
| 1051 |
+
unet.requires_grad_(False)
|
| 1052 |
+
text_encoder_one.requires_grad_(False)
|
| 1053 |
+
text_encoder_two.requires_grad_(False)
|
| 1054 |
+
controlnet.train()
|
| 1055 |
+
|
| 1056 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 1057 |
+
if is_xformers_available():
|
| 1058 |
+
import xformers
|
| 1059 |
+
|
| 1060 |
+
xformers_version = version.parse(xformers.__version__)
|
| 1061 |
+
if xformers_version == version.parse("0.0.16"):
|
| 1062 |
+
logger.warning(
|
| 1063 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 1064 |
+
)
|
| 1065 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 1066 |
+
controlnet.enable_xformers_memory_efficient_attention()
|
| 1067 |
+
else:
|
| 1068 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 1069 |
+
|
| 1070 |
+
if args.gradient_checkpointing:
|
| 1071 |
+
controlnet.enable_gradient_checkpointing()
|
| 1072 |
+
|
| 1073 |
+
# Check that all trainable models are in full precision
|
| 1074 |
+
low_precision_error_string = (
|
| 1075 |
+
" Please make sure to always have all model weights in full float32 precision when starting training - even if"
|
| 1076 |
+
" doing mixed precision training, copy of the weights should still be float32."
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
if accelerator.unwrap_model(controlnet).dtype != torch.float32:
|
| 1080 |
+
raise ValueError(
|
| 1081 |
+
f"Controlnet loaded as datatype {accelerator.unwrap_model(controlnet).dtype}. {low_precision_error_string}"
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 1085 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 1086 |
+
if args.allow_tf32:
|
| 1087 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 1088 |
+
|
| 1089 |
+
if args.scale_lr:
|
| 1090 |
+
args.learning_rate = (
|
| 1091 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 1095 |
+
if args.use_8bit_adam:
|
| 1096 |
+
try:
|
| 1097 |
+
import bitsandbytes as bnb
|
| 1098 |
+
except ImportError:
|
| 1099 |
+
raise ImportError(
|
| 1100 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 1101 |
+
)
|
| 1102 |
+
|
| 1103 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 1104 |
+
else:
|
| 1105 |
+
optimizer_class = torch.optim.AdamW
|
| 1106 |
+
|
| 1107 |
+
# Optimizer creation
|
| 1108 |
+
params_to_optimize = controlnet.parameters()
|
| 1109 |
+
optimizer = optimizer_class(
|
| 1110 |
+
params_to_optimize,
|
| 1111 |
+
lr=args.learning_rate,
|
| 1112 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 1113 |
+
weight_decay=args.adam_weight_decay,
|
| 1114 |
+
eps=args.adam_epsilon,
|
| 1115 |
+
)
|
| 1116 |
+
|
| 1117 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 1118 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 1119 |
+
weight_dtype = torch.float32
|
| 1120 |
+
if accelerator.mixed_precision == "fp16":
|
| 1121 |
+
weight_dtype = torch.float16
|
| 1122 |
+
elif accelerator.mixed_precision == "bf16":
|
| 1123 |
+
weight_dtype = torch.bfloat16
|
| 1124 |
+
|
| 1125 |
+
# Move vae, unet and text_encoder to device and cast to weight_dtype
|
| 1126 |
+
# The VAE is in float32 to avoid NaN losses.
|
| 1127 |
+
if args.pretrained_vae_model_name_or_path is not None:
|
| 1128 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 1129 |
+
else:
|
| 1130 |
+
vae.to(accelerator.device, dtype=torch.float32)
|
| 1131 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 1132 |
+
text_encoder_one.to(accelerator.device, dtype=weight_dtype)
|
| 1133 |
+
text_encoder_two.to(accelerator.device, dtype=weight_dtype)
|
| 1134 |
+
if args.control_type == "depth":
|
| 1135 |
+
depth_model.to(accelerator.device, dtype=weight_dtype)
|
| 1136 |
+
|
| 1137 |
+
# Here, we compute not just the text embeddings but also the additional embeddings
|
| 1138 |
+
# needed for the SD XL UNet to operate.
|
| 1139 |
+
def compute_embeddings(
|
| 1140 |
+
prompt_batch, original_sizes, crop_coords, proportion_empty_prompts, text_encoders, tokenizers, is_train=True
|
| 1141 |
+
):
|
| 1142 |
+
target_size = (args.resolution, args.resolution)
|
| 1143 |
+
original_sizes = list(map(list, zip(*original_sizes)))
|
| 1144 |
+
crops_coords_top_left = list(map(list, zip(*crop_coords)))
|
| 1145 |
+
|
| 1146 |
+
original_sizes = torch.tensor(original_sizes, dtype=torch.long)
|
| 1147 |
+
crops_coords_top_left = torch.tensor(crops_coords_top_left, dtype=torch.long)
|
| 1148 |
+
|
| 1149 |
+
# crops_coords_top_left = (args.crops_coords_top_left_h, args.crops_coords_top_left_w)
|
| 1150 |
+
prompt_embeds, pooled_prompt_embeds = encode_prompt(
|
| 1151 |
+
prompt_batch, text_encoders, tokenizers, proportion_empty_prompts, is_train
|
| 1152 |
+
)
|
| 1153 |
+
add_text_embeds = pooled_prompt_embeds
|
| 1154 |
+
|
| 1155 |
+
# Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
|
| 1156 |
+
# add_time_ids = list(crops_coords_top_left + target_size)
|
| 1157 |
+
add_time_ids = list(target_size)
|
| 1158 |
+
add_time_ids = torch.tensor([add_time_ids])
|
| 1159 |
+
add_time_ids = add_time_ids.repeat(len(prompt_batch), 1)
|
| 1160 |
+
# add_time_ids = torch.cat([torch.tensor(original_sizes, dtype=torch.long), add_time_ids], dim=-1)
|
| 1161 |
+
add_time_ids = torch.cat([original_sizes, crops_coords_top_left, add_time_ids], dim=-1)
|
| 1162 |
+
add_time_ids = add_time_ids.to(accelerator.device, dtype=prompt_embeds.dtype)
|
| 1163 |
+
|
| 1164 |
+
prompt_embeds = prompt_embeds.to(accelerator.device)
|
| 1165 |
+
add_text_embeds = add_text_embeds.to(accelerator.device)
|
| 1166 |
+
unet_added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 1167 |
+
|
| 1168 |
+
return {"prompt_embeds": prompt_embeds, **unet_added_cond_kwargs}
|
| 1169 |
+
|
| 1170 |
+
def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
|
| 1171 |
+
sigmas = noise_scheduler.sigmas.to(device=accelerator.device, dtype=dtype)
|
| 1172 |
+
schedule_timesteps = noise_scheduler.timesteps.to(accelerator.device)
|
| 1173 |
+
timesteps = timesteps.to(accelerator.device)
|
| 1174 |
+
|
| 1175 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 1176 |
+
|
| 1177 |
+
sigma = sigmas[step_indices].flatten()
|
| 1178 |
+
while len(sigma.shape) < n_dim:
|
| 1179 |
+
sigma = sigma.unsqueeze(-1)
|
| 1180 |
+
return sigma
|
| 1181 |
+
|
| 1182 |
+
dataset = Text2ImageDataset(
|
| 1183 |
+
train_shards_path_or_url=args.train_shards_path_or_url,
|
| 1184 |
+
eval_shards_path_or_url=args.eval_shards_path_or_url,
|
| 1185 |
+
num_train_examples=args.max_train_samples,
|
| 1186 |
+
per_gpu_batch_size=args.train_batch_size,
|
| 1187 |
+
global_batch_size=args.train_batch_size * accelerator.num_processes,
|
| 1188 |
+
num_workers=args.dataloader_num_workers,
|
| 1189 |
+
resolution=args.resolution,
|
| 1190 |
+
center_crop=False,
|
| 1191 |
+
random_flip=False,
|
| 1192 |
+
shuffle_buffer_size=1000,
|
| 1193 |
+
pin_memory=True,
|
| 1194 |
+
persistent_workers=True,
|
| 1195 |
+
control_type=args.control_type,
|
| 1196 |
+
feature_extractor=feature_extractor,
|
| 1197 |
+
)
|
| 1198 |
+
train_dataloader = dataset.train_dataloader
|
| 1199 |
+
|
| 1200 |
+
# Let's first compute all the embeddings so that we can free up the text encoders
|
| 1201 |
+
# from memory.
|
| 1202 |
+
text_encoders = [text_encoder_one, text_encoder_two]
|
| 1203 |
+
tokenizers = [tokenizer_one, tokenizer_two]
|
| 1204 |
+
|
| 1205 |
+
compute_embeddings_fn = functools.partial(
|
| 1206 |
+
compute_embeddings,
|
| 1207 |
+
proportion_empty_prompts=args.proportion_empty_prompts,
|
| 1208 |
+
text_encoders=text_encoders,
|
| 1209 |
+
tokenizers=tokenizers,
|
| 1210 |
+
)
|
| 1211 |
+
|
| 1212 |
+
# Scheduler and math around the number of training steps.
|
| 1213 |
+
overrode_max_train_steps = False
|
| 1214 |
+
num_update_steps_per_epoch = math.ceil(train_dataloader.num_batches / args.gradient_accumulation_steps)
|
| 1215 |
+
if args.max_train_steps is None:
|
| 1216 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 1217 |
+
overrode_max_train_steps = True
|
| 1218 |
+
|
| 1219 |
+
lr_scheduler = get_scheduler(
|
| 1220 |
+
args.lr_scheduler,
|
| 1221 |
+
optimizer=optimizer,
|
| 1222 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 1223 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 1224 |
+
num_cycles=args.lr_num_cycles,
|
| 1225 |
+
power=args.lr_power,
|
| 1226 |
+
)
|
| 1227 |
+
|
| 1228 |
+
# Prepare everything with our `accelerator`.
|
| 1229 |
+
controlnet, optimizer, lr_scheduler = accelerator.prepare(controlnet, optimizer, lr_scheduler)
|
| 1230 |
+
|
| 1231 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 1232 |
+
num_update_steps_per_epoch = math.ceil(train_dataloader.num_batches / args.gradient_accumulation_steps)
|
| 1233 |
+
if overrode_max_train_steps:
|
| 1234 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 1235 |
+
# Afterwards we recalculate our number of training epochs
|
| 1236 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 1237 |
+
|
| 1238 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 1239 |
+
# The trackers initializes automatically on the main process.
|
| 1240 |
+
if accelerator.is_main_process:
|
| 1241 |
+
tracker_config = dict(vars(args))
|
| 1242 |
+
|
| 1243 |
+
# tensorboard cannot handle list types for config
|
| 1244 |
+
tracker_config.pop("validation_prompt")
|
| 1245 |
+
tracker_config.pop("validation_image")
|
| 1246 |
+
|
| 1247 |
+
accelerator.init_trackers(args.tracker_project_name, config=tracker_config)
|
| 1248 |
+
|
| 1249 |
+
# Train!
|
| 1250 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 1251 |
+
|
| 1252 |
+
logger.info("***** Running training *****")
|
| 1253 |
+
logger.info(f" Num batches each epoch = {train_dataloader.num_batches}")
|
| 1254 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 1255 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 1256 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 1257 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 1258 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 1259 |
+
global_step = 0
|
| 1260 |
+
first_epoch = 0
|
| 1261 |
+
|
| 1262 |
+
# Potentially load in the weights and states from a previous save
|
| 1263 |
+
if args.resume_from_checkpoint:
|
| 1264 |
+
if args.resume_from_checkpoint != "latest":
|
| 1265 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 1266 |
+
else:
|
| 1267 |
+
# Get the most recent checkpoint
|
| 1268 |
+
dirs = os.listdir(args.output_dir)
|
| 1269 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 1270 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 1271 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 1272 |
+
|
| 1273 |
+
if path is None:
|
| 1274 |
+
accelerator.print(
|
| 1275 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 1276 |
+
)
|
| 1277 |
+
args.resume_from_checkpoint = None
|
| 1278 |
+
initial_global_step = 0
|
| 1279 |
+
else:
|
| 1280 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 1281 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 1282 |
+
global_step = int(path.split("-")[1])
|
| 1283 |
+
|
| 1284 |
+
initial_global_step = global_step
|
| 1285 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 1286 |
+
else:
|
| 1287 |
+
initial_global_step = 0
|
| 1288 |
+
|
| 1289 |
+
progress_bar = tqdm(
|
| 1290 |
+
range(0, args.max_train_steps),
|
| 1291 |
+
initial=initial_global_step,
|
| 1292 |
+
desc="Steps",
|
| 1293 |
+
# Only show the progress bar once on each machine.
|
| 1294 |
+
disable=not accelerator.is_local_main_process,
|
| 1295 |
+
)
|
| 1296 |
+
|
| 1297 |
+
image_logs = None
|
| 1298 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 1299 |
+
for step, batch in enumerate(train_dataloader):
|
| 1300 |
+
with accelerator.accumulate(controlnet):
|
| 1301 |
+
image, control_image, text, orig_size, crop_coords = batch
|
| 1302 |
+
|
| 1303 |
+
encoded_text = compute_embeddings_fn(text, orig_size, crop_coords)
|
| 1304 |
+
image = image.to(accelerator.device, non_blocking=True)
|
| 1305 |
+
control_image = control_image.to(accelerator.device, non_blocking=True)
|
| 1306 |
+
|
| 1307 |
+
if args.pretrained_vae_model_name_or_path is not None:
|
| 1308 |
+
pixel_values = image.to(dtype=weight_dtype)
|
| 1309 |
+
if vae.dtype != weight_dtype:
|
| 1310 |
+
vae.to(dtype=weight_dtype)
|
| 1311 |
+
else:
|
| 1312 |
+
pixel_values = image
|
| 1313 |
+
|
| 1314 |
+
# latents = vae.encode(pixel_values).latent_dist.sample()
|
| 1315 |
+
# encode pixel values with batch size of at most 8
|
| 1316 |
+
latents = []
|
| 1317 |
+
for i in range(0, pixel_values.shape[0], 8):
|
| 1318 |
+
latents.append(vae.encode(pixel_values[i : i + 8]).latent_dist.sample())
|
| 1319 |
+
latents = torch.cat(latents, dim=0)
|
| 1320 |
+
|
| 1321 |
+
latents = latents * vae.config.scaling_factor
|
| 1322 |
+
if args.pretrained_vae_model_name_or_path is None:
|
| 1323 |
+
latents = latents.to(weight_dtype)
|
| 1324 |
+
|
| 1325 |
+
if args.control_type == "depth":
|
| 1326 |
+
control_image = control_image.to(weight_dtype)
|
| 1327 |
+
with torch.autocast("cuda"):
|
| 1328 |
+
depth_map = depth_model(control_image).predicted_depth
|
| 1329 |
+
depth_map = torch.nn.functional.interpolate(
|
| 1330 |
+
depth_map.unsqueeze(1),
|
| 1331 |
+
size=image.shape[2:],
|
| 1332 |
+
mode="bicubic",
|
| 1333 |
+
align_corners=False,
|
| 1334 |
+
)
|
| 1335 |
+
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 1336 |
+
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 1337 |
+
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
| 1338 |
+
control_image = (depth_map * 255.0).to(torch.uint8).float() / 255.0 # hack to match inference
|
| 1339 |
+
control_image = torch.cat([control_image] * 3, dim=1)
|
| 1340 |
+
|
| 1341 |
+
# Sample noise that we'll add to the latents
|
| 1342 |
+
noise = torch.randn_like(latents)
|
| 1343 |
+
bsz = latents.shape[0]
|
| 1344 |
+
|
| 1345 |
+
# Sample a random timestep for each image
|
| 1346 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 1347 |
+
timesteps = timesteps.long()
|
| 1348 |
+
|
| 1349 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 1350 |
+
# (this is the forward diffusion process)
|
| 1351 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 1352 |
+
sigmas = get_sigmas(timesteps, len(noisy_latents.shape), noisy_latents.dtype)
|
| 1353 |
+
inp_noisy_latents = noisy_latents / ((sigmas**2 + 1) ** 0.5)
|
| 1354 |
+
|
| 1355 |
+
# ControlNet conditioning.
|
| 1356 |
+
controlnet_image = control_image.to(dtype=weight_dtype)
|
| 1357 |
+
prompt_embeds = encoded_text.pop("prompt_embeds")
|
| 1358 |
+
down_block_res_samples, mid_block_res_sample = controlnet(
|
| 1359 |
+
inp_noisy_latents,
|
| 1360 |
+
timesteps,
|
| 1361 |
+
encoder_hidden_states=prompt_embeds,
|
| 1362 |
+
added_cond_kwargs=encoded_text,
|
| 1363 |
+
controlnet_cond=controlnet_image,
|
| 1364 |
+
return_dict=False,
|
| 1365 |
+
)
|
| 1366 |
+
|
| 1367 |
+
# Predict the noise residual
|
| 1368 |
+
model_pred = unet(
|
| 1369 |
+
inp_noisy_latents,
|
| 1370 |
+
timesteps,
|
| 1371 |
+
encoder_hidden_states=prompt_embeds,
|
| 1372 |
+
added_cond_kwargs=encoded_text,
|
| 1373 |
+
down_block_additional_residuals=[
|
| 1374 |
+
sample.to(dtype=weight_dtype) for sample in down_block_res_samples
|
| 1375 |
+
],
|
| 1376 |
+
mid_block_additional_residual=mid_block_res_sample.to(dtype=weight_dtype),
|
| 1377 |
+
).sample
|
| 1378 |
+
|
| 1379 |
+
model_pred = model_pred * (-sigmas) + noisy_latents
|
| 1380 |
+
weighing = sigmas**-2.0
|
| 1381 |
+
|
| 1382 |
+
# Get the target for loss depending on the prediction type
|
| 1383 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 1384 |
+
target = latents # compute loss against the denoised latents
|
| 1385 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 1386 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 1387 |
+
else:
|
| 1388 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 1389 |
+
loss = torch.mean(
|
| 1390 |
+
(weighing.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1), 1
|
| 1391 |
+
)
|
| 1392 |
+
loss = loss.mean()
|
| 1393 |
+
|
| 1394 |
+
accelerator.backward(loss)
|
| 1395 |
+
if accelerator.sync_gradients:
|
| 1396 |
+
params_to_clip = controlnet.parameters()
|
| 1397 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 1398 |
+
optimizer.step()
|
| 1399 |
+
lr_scheduler.step()
|
| 1400 |
+
optimizer.zero_grad(set_to_none=args.set_grads_to_none)
|
| 1401 |
+
|
| 1402 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1403 |
+
if accelerator.sync_gradients:
|
| 1404 |
+
progress_bar.update(1)
|
| 1405 |
+
global_step += 1
|
| 1406 |
+
|
| 1407 |
+
if accelerator.is_main_process:
|
| 1408 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1409 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1410 |
+
if args.checkpoints_total_limit is not None:
|
| 1411 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1412 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1413 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1414 |
+
|
| 1415 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1416 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1417 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1418 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1419 |
+
|
| 1420 |
+
logger.info(
|
| 1421 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1422 |
+
)
|
| 1423 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1424 |
+
|
| 1425 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1426 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1427 |
+
shutil.rmtree(removing_checkpoint)
|
| 1428 |
+
|
| 1429 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1430 |
+
accelerator.save_state(save_path)
|
| 1431 |
+
logger.info(f"Saved state to {save_path}")
|
| 1432 |
+
|
| 1433 |
+
if args.validation_prompt is not None and global_step % args.validation_steps == 0:
|
| 1434 |
+
image_logs = log_validation(
|
| 1435 |
+
vae, unet, controlnet, args, accelerator, weight_dtype, global_step
|
| 1436 |
+
)
|
| 1437 |
+
|
| 1438 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1439 |
+
progress_bar.set_postfix(**logs)
|
| 1440 |
+
accelerator.log(logs, step=global_step)
|
| 1441 |
+
|
| 1442 |
+
if global_step >= args.max_train_steps:
|
| 1443 |
+
break
|
| 1444 |
+
|
| 1445 |
+
# Create the pipeline using using the trained modules and save it.
|
| 1446 |
+
accelerator.wait_for_everyone()
|
| 1447 |
+
if accelerator.is_main_process:
|
| 1448 |
+
controlnet = accelerator.unwrap_model(controlnet)
|
| 1449 |
+
controlnet.save_pretrained(args.output_dir)
|
| 1450 |
+
|
| 1451 |
+
if args.push_to_hub:
|
| 1452 |
+
save_model_card(
|
| 1453 |
+
repo_id,
|
| 1454 |
+
image_logs=image_logs,
|
| 1455 |
+
base_model=args.pretrained_model_name_or_path,
|
| 1456 |
+
repo_folder=args.output_dir,
|
| 1457 |
+
)
|
| 1458 |
+
upload_folder(
|
| 1459 |
+
repo_id=repo_id,
|
| 1460 |
+
folder_path=args.output_dir,
|
| 1461 |
+
commit_message="End of training",
|
| 1462 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1463 |
+
)
|
| 1464 |
+
|
| 1465 |
+
accelerator.end_training()
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
if __name__ == "__main__":
|
| 1469 |
+
args = parse_args()
|
| 1470 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Diffusion Model Alignment Using Direct Preference Optimization
|
| 2 |
+
|
| 3 |
+
This directory provides LoRA implementations of Diffusion DPO proposed in [DiffusionModel Alignment Using Direct Preference Optimization](https://huggingface.co/papers/2311.12908) by Bram Wallace, Meihua Dang, Rafael Rafailov, Linqi Zhou, Aaron Lou, Senthil Purushwalkam, Stefano Ermon, Caiming Xiong, Shafiq Joty, and Nikhil Naik.
|
| 4 |
+
|
| 5 |
+
We provide implementations for both Stable Diffusion (SD) and Stable Diffusion XL (SDXL). The original checkpoints are available at the URLs below:
|
| 6 |
+
|
| 7 |
+
* [mhdang/dpo-sd1.5-text2image-v1](https://huggingface.co/mhdang/dpo-sd1.5-text2image-v1)
|
| 8 |
+
* [mhdang/dpo-sdxl-text2image-v1](https://huggingface.co/mhdang/dpo-sdxl-text2image-v1)
|
| 9 |
+
|
| 10 |
+
> 💡 Note: The scripts are highly experimental and were only tested on low-data regimes. Proceed with caution. Feel free to let us know about your findings via GitHub issues.
|
| 11 |
+
|
| 12 |
+
## SD training command
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
accelerate launch train_diffusion_dpo.py \
|
| 16 |
+
--pretrained_model_name_or_path=stable-diffusion-v1-5/stable-diffusion-v1-5 \
|
| 17 |
+
--output_dir="diffusion-dpo" \
|
| 18 |
+
--mixed_precision="fp16" \
|
| 19 |
+
--dataset_name=kashif/pickascore \
|
| 20 |
+
--resolution=512 \
|
| 21 |
+
--train_batch_size=16 \
|
| 22 |
+
--gradient_accumulation_steps=2 \
|
| 23 |
+
--gradient_checkpointing \
|
| 24 |
+
--use_8bit_adam \
|
| 25 |
+
--rank=8 \
|
| 26 |
+
--learning_rate=1e-5 \
|
| 27 |
+
--report_to="wandb" \
|
| 28 |
+
--lr_scheduler="constant" \
|
| 29 |
+
--lr_warmup_steps=0 \
|
| 30 |
+
--max_train_steps=10000 \
|
| 31 |
+
--checkpointing_steps=2000 \
|
| 32 |
+
--run_validation --validation_steps=200 \
|
| 33 |
+
--seed="0" \
|
| 34 |
+
--report_to="wandb" \
|
| 35 |
+
--push_to_hub
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## SDXL training command
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
accelerate launch train_diffusion_dpo_sdxl.py \
|
| 42 |
+
--pretrained_model_name_or_path=stabilityai/stable-diffusion-xl-base-1.0 \
|
| 43 |
+
--pretrained_vae_model_name_or_path=madebyollin/sdxl-vae-fp16-fix \
|
| 44 |
+
--output_dir="diffusion-sdxl-dpo" \
|
| 45 |
+
--mixed_precision="fp16" \
|
| 46 |
+
--dataset_name=kashif/pickascore \
|
| 47 |
+
--train_batch_size=8 \
|
| 48 |
+
--gradient_accumulation_steps=2 \
|
| 49 |
+
--gradient_checkpointing \
|
| 50 |
+
--use_8bit_adam \
|
| 51 |
+
--rank=8 \
|
| 52 |
+
--learning_rate=1e-5 \
|
| 53 |
+
--report_to="wandb" \
|
| 54 |
+
--lr_scheduler="constant" \
|
| 55 |
+
--lr_warmup_steps=0 \
|
| 56 |
+
--max_train_steps=2000 \
|
| 57 |
+
--checkpointing_steps=500 \
|
| 58 |
+
--run_validation --validation_steps=50 \
|
| 59 |
+
--seed="0" \
|
| 60 |
+
--report_to="wandb" \
|
| 61 |
+
--push_to_hub
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
## SDXL Turbo training command
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
accelerate launch train_diffusion_dpo_sdxl.py \
|
| 68 |
+
--pretrained_model_name_or_path=stabilityai/sdxl-turbo \
|
| 69 |
+
--pretrained_vae_model_name_or_path=madebyollin/sdxl-vae-fp16-fix \
|
| 70 |
+
--output_dir="diffusion-sdxl-turbo-dpo" \
|
| 71 |
+
--mixed_precision="fp16" \
|
| 72 |
+
--dataset_name=kashif/pickascore \
|
| 73 |
+
--train_batch_size=8 \
|
| 74 |
+
--gradient_accumulation_steps=2 \
|
| 75 |
+
--gradient_checkpointing \
|
| 76 |
+
--use_8bit_adam \
|
| 77 |
+
--rank=8 \
|
| 78 |
+
--learning_rate=1e-5 \
|
| 79 |
+
--report_to="wandb" \
|
| 80 |
+
--lr_scheduler="constant" \
|
| 81 |
+
--lr_warmup_steps=0 \
|
| 82 |
+
--max_train_steps=2000 \
|
| 83 |
+
--checkpointing_steps=500 \
|
| 84 |
+
--run_validation --validation_steps=50 \
|
| 85 |
+
--seed="0" \
|
| 86 |
+
--report_to="wandb" \
|
| 87 |
+
--is_turbo --resolution 512 \
|
| 88 |
+
--push_to_hub
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
## Acknowledgements
|
| 93 |
+
|
| 94 |
+
This is based on the amazing work done by [Bram](https://github.com/bram-w) here for Diffusion DPO: https://github.com/bram-w/trl/blob/dpo/.
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.16.0
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.25.1
|
| 4 |
+
ftfy
|
| 5 |
+
tensorboard
|
| 6 |
+
Jinja2
|
| 7 |
+
peft
|
| 8 |
+
wandb
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/train_diffusion_dpo.py
ADDED
|
@@ -0,0 +1,983 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 bram-w, The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import contextlib
|
| 19 |
+
import io
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import shutil
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
import transformers
|
| 31 |
+
import wandb
|
| 32 |
+
from accelerate import Accelerator
|
| 33 |
+
from accelerate.logging import get_logger
|
| 34 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 35 |
+
from datasets import load_dataset
|
| 36 |
+
from huggingface_hub import create_repo, upload_folder
|
| 37 |
+
from packaging import version
|
| 38 |
+
from peft import LoraConfig
|
| 39 |
+
from peft.utils import get_peft_model_state_dict
|
| 40 |
+
from PIL import Image
|
| 41 |
+
from torchvision import transforms
|
| 42 |
+
from tqdm.auto import tqdm
|
| 43 |
+
from transformers import AutoTokenizer, PretrainedConfig
|
| 44 |
+
|
| 45 |
+
import diffusers
|
| 46 |
+
from diffusers import (
|
| 47 |
+
AutoencoderKL,
|
| 48 |
+
DDPMScheduler,
|
| 49 |
+
DiffusionPipeline,
|
| 50 |
+
DPMSolverMultistepScheduler,
|
| 51 |
+
UNet2DConditionModel,
|
| 52 |
+
)
|
| 53 |
+
from diffusers.loaders import StableDiffusionLoraLoaderMixin
|
| 54 |
+
from diffusers.optimization import get_scheduler
|
| 55 |
+
from diffusers.utils import check_min_version, convert_state_dict_to_diffusers
|
| 56 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 60 |
+
check_min_version("0.25.0.dev0")
|
| 61 |
+
|
| 62 |
+
logger = get_logger(__name__)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
VALIDATION_PROMPTS = [
|
| 66 |
+
"portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography",
|
| 67 |
+
"Self-portrait oil painting, a beautiful cyborg with golden hair, 8k",
|
| 68 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 69 |
+
"A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece",
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
|
| 74 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 75 |
+
pretrained_model_name_or_path,
|
| 76 |
+
subfolder="text_encoder",
|
| 77 |
+
revision=revision,
|
| 78 |
+
)
|
| 79 |
+
model_class = text_encoder_config.architectures[0]
|
| 80 |
+
|
| 81 |
+
if model_class == "CLIPTextModel":
|
| 82 |
+
from transformers import CLIPTextModel
|
| 83 |
+
|
| 84 |
+
return CLIPTextModel
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def log_validation(args, unet, accelerator, weight_dtype, epoch, is_final_validation=False):
|
| 90 |
+
logger.info(f"Running validation... \n Generating images with prompts:\n {VALIDATION_PROMPTS}.")
|
| 91 |
+
|
| 92 |
+
# create pipeline
|
| 93 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 94 |
+
args.pretrained_model_name_or_path,
|
| 95 |
+
revision=args.revision,
|
| 96 |
+
variant=args.variant,
|
| 97 |
+
torch_dtype=weight_dtype,
|
| 98 |
+
)
|
| 99 |
+
if not is_final_validation:
|
| 100 |
+
pipeline.unet = accelerator.unwrap_model(unet)
|
| 101 |
+
else:
|
| 102 |
+
pipeline.load_lora_weights(args.output_dir, weight_name="pytorch_lora_weights.safetensors")
|
| 103 |
+
|
| 104 |
+
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
|
| 105 |
+
pipeline = pipeline.to(accelerator.device)
|
| 106 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 107 |
+
|
| 108 |
+
# run inference
|
| 109 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 110 |
+
images = []
|
| 111 |
+
context = contextlib.nullcontext() if is_final_validation else torch.cuda.amp.autocast()
|
| 112 |
+
|
| 113 |
+
for prompt in VALIDATION_PROMPTS:
|
| 114 |
+
with context:
|
| 115 |
+
image = pipeline(prompt, num_inference_steps=25, generator=generator).images[0]
|
| 116 |
+
images.append(image)
|
| 117 |
+
|
| 118 |
+
tracker_key = "test" if is_final_validation else "validation"
|
| 119 |
+
for tracker in accelerator.trackers:
|
| 120 |
+
if tracker.name == "tensorboard":
|
| 121 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 122 |
+
tracker.writer.add_images(tracker_key, np_images, epoch, dataformats="NHWC")
|
| 123 |
+
if tracker.name == "wandb":
|
| 124 |
+
tracker.log(
|
| 125 |
+
{
|
| 126 |
+
tracker_key: [
|
| 127 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}") for i, image in enumerate(images)
|
| 128 |
+
]
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Also log images without the LoRA params for comparison.
|
| 133 |
+
if is_final_validation:
|
| 134 |
+
pipeline.disable_lora()
|
| 135 |
+
no_lora_images = [
|
| 136 |
+
pipeline(prompt, num_inference_steps=25, generator=generator).images[0] for prompt in VALIDATION_PROMPTS
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
for tracker in accelerator.trackers:
|
| 140 |
+
if tracker.name == "tensorboard":
|
| 141 |
+
np_images = np.stack([np.asarray(img) for img in no_lora_images])
|
| 142 |
+
tracker.writer.add_images("test_without_lora", np_images, epoch, dataformats="NHWC")
|
| 143 |
+
if tracker.name == "wandb":
|
| 144 |
+
tracker.log(
|
| 145 |
+
{
|
| 146 |
+
"test_without_lora": [
|
| 147 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}")
|
| 148 |
+
for i, image in enumerate(no_lora_images)
|
| 149 |
+
]
|
| 150 |
+
}
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def parse_args(input_args=None):
|
| 155 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--pretrained_model_name_or_path",
|
| 158 |
+
type=str,
|
| 159 |
+
default=None,
|
| 160 |
+
required=True,
|
| 161 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--revision",
|
| 165 |
+
type=str,
|
| 166 |
+
default=None,
|
| 167 |
+
required=False,
|
| 168 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--dataset_name",
|
| 172 |
+
type=str,
|
| 173 |
+
default=None,
|
| 174 |
+
help=(
|
| 175 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 176 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 177 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 178 |
+
),
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--dataset_split_name",
|
| 182 |
+
type=str,
|
| 183 |
+
default="validation",
|
| 184 |
+
help="Dataset split to be used during training. Helpful to specify for conducting experimental runs.",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--variant",
|
| 188 |
+
type=str,
|
| 189 |
+
default=None,
|
| 190 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 191 |
+
)
|
| 192 |
+
parser.add_argument(
|
| 193 |
+
"--run_validation",
|
| 194 |
+
default=False,
|
| 195 |
+
action="store_true",
|
| 196 |
+
help="Whether to run validation inference in between training and also after training. Helps to track progress.",
|
| 197 |
+
)
|
| 198 |
+
parser.add_argument(
|
| 199 |
+
"--validation_steps",
|
| 200 |
+
type=int,
|
| 201 |
+
default=200,
|
| 202 |
+
help="Run validation every X steps.",
|
| 203 |
+
)
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--max_train_samples",
|
| 206 |
+
type=int,
|
| 207 |
+
default=None,
|
| 208 |
+
help=(
|
| 209 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 210 |
+
"value if set."
|
| 211 |
+
),
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--output_dir",
|
| 215 |
+
type=str,
|
| 216 |
+
default="diffusion-dpo-lora",
|
| 217 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--cache_dir",
|
| 221 |
+
type=str,
|
| 222 |
+
default=None,
|
| 223 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
"--resolution",
|
| 228 |
+
type=int,
|
| 229 |
+
default=512,
|
| 230 |
+
help=(
|
| 231 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 232 |
+
" resolution"
|
| 233 |
+
),
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
"--vae_encode_batch_size",
|
| 237 |
+
type=int,
|
| 238 |
+
default=8,
|
| 239 |
+
help="Batch size to use for VAE encoding of the images for efficient processing.",
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--no_hflip",
|
| 243 |
+
action="store_true",
|
| 244 |
+
help="whether to randomly flip images horizontally",
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--random_crop",
|
| 248 |
+
default=False,
|
| 249 |
+
action="store_true",
|
| 250 |
+
help=(
|
| 251 |
+
"Whether to random crop the input images to the resolution. If not set, the images will be center-cropped."
|
| 252 |
+
),
|
| 253 |
+
)
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--max_train_steps",
|
| 260 |
+
type=int,
|
| 261 |
+
default=None,
|
| 262 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 263 |
+
)
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--checkpointing_steps",
|
| 266 |
+
type=int,
|
| 267 |
+
default=500,
|
| 268 |
+
help=(
|
| 269 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 270 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 271 |
+
" training using `--resume_from_checkpoint`."
|
| 272 |
+
),
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
"--checkpoints_total_limit",
|
| 276 |
+
type=int,
|
| 277 |
+
default=None,
|
| 278 |
+
help=("Max number of checkpoints to store."),
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--resume_from_checkpoint",
|
| 282 |
+
type=str,
|
| 283 |
+
default=None,
|
| 284 |
+
help=(
|
| 285 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 286 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 287 |
+
),
|
| 288 |
+
)
|
| 289 |
+
parser.add_argument(
|
| 290 |
+
"--gradient_accumulation_steps",
|
| 291 |
+
type=int,
|
| 292 |
+
default=1,
|
| 293 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 294 |
+
)
|
| 295 |
+
parser.add_argument(
|
| 296 |
+
"--gradient_checkpointing",
|
| 297 |
+
action="store_true",
|
| 298 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 299 |
+
)
|
| 300 |
+
parser.add_argument(
|
| 301 |
+
"--beta_dpo",
|
| 302 |
+
type=int,
|
| 303 |
+
default=2500,
|
| 304 |
+
help="DPO KL Divergence penalty.",
|
| 305 |
+
)
|
| 306 |
+
parser.add_argument(
|
| 307 |
+
"--loss_type",
|
| 308 |
+
type=str,
|
| 309 |
+
default="sigmoid",
|
| 310 |
+
help="DPO loss type. Can be one of 'sigmoid' (default), 'ipo', or 'cpo'",
|
| 311 |
+
)
|
| 312 |
+
parser.add_argument(
|
| 313 |
+
"--learning_rate",
|
| 314 |
+
type=float,
|
| 315 |
+
default=5e-4,
|
| 316 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 317 |
+
)
|
| 318 |
+
parser.add_argument(
|
| 319 |
+
"--scale_lr",
|
| 320 |
+
action="store_true",
|
| 321 |
+
default=False,
|
| 322 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 323 |
+
)
|
| 324 |
+
parser.add_argument(
|
| 325 |
+
"--lr_scheduler",
|
| 326 |
+
type=str,
|
| 327 |
+
default="constant",
|
| 328 |
+
help=(
|
| 329 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 330 |
+
' "constant", "constant_with_warmup"]'
|
| 331 |
+
),
|
| 332 |
+
)
|
| 333 |
+
parser.add_argument(
|
| 334 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 335 |
+
)
|
| 336 |
+
parser.add_argument(
|
| 337 |
+
"--lr_num_cycles",
|
| 338 |
+
type=int,
|
| 339 |
+
default=1,
|
| 340 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 341 |
+
)
|
| 342 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--dataloader_num_workers",
|
| 345 |
+
type=int,
|
| 346 |
+
default=0,
|
| 347 |
+
help=(
|
| 348 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 349 |
+
),
|
| 350 |
+
)
|
| 351 |
+
parser.add_argument(
|
| 352 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 353 |
+
)
|
| 354 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 355 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 356 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 357 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 358 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 359 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 360 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 361 |
+
parser.add_argument(
|
| 362 |
+
"--hub_model_id",
|
| 363 |
+
type=str,
|
| 364 |
+
default=None,
|
| 365 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 366 |
+
)
|
| 367 |
+
parser.add_argument(
|
| 368 |
+
"--logging_dir",
|
| 369 |
+
type=str,
|
| 370 |
+
default="logs",
|
| 371 |
+
help=(
|
| 372 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 373 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 374 |
+
),
|
| 375 |
+
)
|
| 376 |
+
parser.add_argument(
|
| 377 |
+
"--allow_tf32",
|
| 378 |
+
action="store_true",
|
| 379 |
+
help=(
|
| 380 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 381 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 382 |
+
),
|
| 383 |
+
)
|
| 384 |
+
parser.add_argument(
|
| 385 |
+
"--report_to",
|
| 386 |
+
type=str,
|
| 387 |
+
default="tensorboard",
|
| 388 |
+
help=(
|
| 389 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 390 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 391 |
+
),
|
| 392 |
+
)
|
| 393 |
+
parser.add_argument(
|
| 394 |
+
"--mixed_precision",
|
| 395 |
+
type=str,
|
| 396 |
+
default=None,
|
| 397 |
+
choices=["no", "fp16", "bf16"],
|
| 398 |
+
help=(
|
| 399 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 400 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 401 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 402 |
+
),
|
| 403 |
+
)
|
| 404 |
+
parser.add_argument(
|
| 405 |
+
"--prior_generation_precision",
|
| 406 |
+
type=str,
|
| 407 |
+
default=None,
|
| 408 |
+
choices=["no", "fp32", "fp16", "bf16"],
|
| 409 |
+
help=(
|
| 410 |
+
"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 411 |
+
" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
|
| 412 |
+
),
|
| 413 |
+
)
|
| 414 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 415 |
+
parser.add_argument(
|
| 416 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 417 |
+
)
|
| 418 |
+
parser.add_argument(
|
| 419 |
+
"--rank",
|
| 420 |
+
type=int,
|
| 421 |
+
default=4,
|
| 422 |
+
help=("The dimension of the LoRA update matrices."),
|
| 423 |
+
)
|
| 424 |
+
parser.add_argument(
|
| 425 |
+
"--tracker_name",
|
| 426 |
+
type=str,
|
| 427 |
+
default="diffusion-dpo-lora",
|
| 428 |
+
help=("The name of the tracker to report results to."),
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
if input_args is not None:
|
| 432 |
+
args = parser.parse_args(input_args)
|
| 433 |
+
else:
|
| 434 |
+
args = parser.parse_args()
|
| 435 |
+
|
| 436 |
+
if args.dataset_name is None:
|
| 437 |
+
raise ValueError("Must provide a `dataset_name`.")
|
| 438 |
+
|
| 439 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 440 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 441 |
+
args.local_rank = env_local_rank
|
| 442 |
+
|
| 443 |
+
return args
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def tokenize_captions(tokenizer, examples):
|
| 447 |
+
max_length = tokenizer.model_max_length
|
| 448 |
+
captions = []
|
| 449 |
+
for caption in examples["caption"]:
|
| 450 |
+
captions.append(caption)
|
| 451 |
+
|
| 452 |
+
text_inputs = tokenizer(
|
| 453 |
+
captions, truncation=True, padding="max_length", max_length=max_length, return_tensors="pt"
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
return text_inputs.input_ids
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
@torch.no_grad()
|
| 460 |
+
def encode_prompt(text_encoder, input_ids):
|
| 461 |
+
text_input_ids = input_ids.to(text_encoder.device)
|
| 462 |
+
attention_mask = None
|
| 463 |
+
|
| 464 |
+
prompt_embeds = text_encoder(text_input_ids, attention_mask=attention_mask)
|
| 465 |
+
prompt_embeds = prompt_embeds[0]
|
| 466 |
+
|
| 467 |
+
return prompt_embeds
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def main(args):
|
| 471 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 472 |
+
raise ValueError(
|
| 473 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 474 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 478 |
+
|
| 479 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 480 |
+
|
| 481 |
+
accelerator = Accelerator(
|
| 482 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 483 |
+
mixed_precision=args.mixed_precision,
|
| 484 |
+
log_with=args.report_to,
|
| 485 |
+
project_config=accelerator_project_config,
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Disable AMP for MPS.
|
| 489 |
+
if torch.backends.mps.is_available():
|
| 490 |
+
accelerator.native_amp = False
|
| 491 |
+
|
| 492 |
+
# Make one log on every process with the configuration for debugging.
|
| 493 |
+
logging.basicConfig(
|
| 494 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 495 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 496 |
+
level=logging.INFO,
|
| 497 |
+
)
|
| 498 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 499 |
+
if accelerator.is_local_main_process:
|
| 500 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 501 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 502 |
+
else:
|
| 503 |
+
transformers.utils.logging.set_verbosity_error()
|
| 504 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 505 |
+
|
| 506 |
+
# If passed along, set the training seed now.
|
| 507 |
+
if args.seed is not None:
|
| 508 |
+
set_seed(args.seed)
|
| 509 |
+
|
| 510 |
+
# Handle the repository creation
|
| 511 |
+
if accelerator.is_main_process:
|
| 512 |
+
if args.output_dir is not None:
|
| 513 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 514 |
+
|
| 515 |
+
if args.push_to_hub:
|
| 516 |
+
repo_id = create_repo(
|
| 517 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 518 |
+
).repo_id
|
| 519 |
+
|
| 520 |
+
# Load the tokenizer
|
| 521 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 522 |
+
args.pretrained_model_name_or_path,
|
| 523 |
+
subfolder="tokenizer",
|
| 524 |
+
revision=args.revision,
|
| 525 |
+
use_fast=False,
|
| 526 |
+
)
|
| 527 |
+
|
| 528 |
+
# import correct text encoder class
|
| 529 |
+
text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
|
| 530 |
+
|
| 531 |
+
# Load scheduler and models
|
| 532 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 533 |
+
text_encoder = text_encoder_cls.from_pretrained(
|
| 534 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 535 |
+
)
|
| 536 |
+
vae = AutoencoderKL.from_pretrained(
|
| 537 |
+
args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 541 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
vae.requires_grad_(False)
|
| 545 |
+
text_encoder.requires_grad_(False)
|
| 546 |
+
unet.requires_grad_(False)
|
| 547 |
+
|
| 548 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 549 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 550 |
+
weight_dtype = torch.float32
|
| 551 |
+
if accelerator.mixed_precision == "fp16":
|
| 552 |
+
weight_dtype = torch.float16
|
| 553 |
+
elif accelerator.mixed_precision == "bf16":
|
| 554 |
+
weight_dtype = torch.bfloat16
|
| 555 |
+
|
| 556 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 557 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 558 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 559 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 560 |
+
|
| 561 |
+
# Set up LoRA.
|
| 562 |
+
unet_lora_config = LoraConfig(
|
| 563 |
+
r=args.rank,
|
| 564 |
+
lora_alpha=args.rank,
|
| 565 |
+
init_lora_weights="gaussian",
|
| 566 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 567 |
+
)
|
| 568 |
+
# Add adapter and make sure the trainable params are in float32.
|
| 569 |
+
unet.add_adapter(unet_lora_config)
|
| 570 |
+
if args.mixed_precision == "fp16":
|
| 571 |
+
for param in unet.parameters():
|
| 572 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 573 |
+
if param.requires_grad:
|
| 574 |
+
param.data = param.to(torch.float32)
|
| 575 |
+
|
| 576 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 577 |
+
if is_xformers_available():
|
| 578 |
+
import xformers
|
| 579 |
+
|
| 580 |
+
xformers_version = version.parse(xformers.__version__)
|
| 581 |
+
if xformers_version == version.parse("0.0.16"):
|
| 582 |
+
logger.warning(
|
| 583 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 584 |
+
)
|
| 585 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 586 |
+
else:
|
| 587 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 588 |
+
|
| 589 |
+
if args.gradient_checkpointing:
|
| 590 |
+
unet.enable_gradient_checkpointing()
|
| 591 |
+
|
| 592 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 593 |
+
def save_model_hook(models, weights, output_dir):
|
| 594 |
+
if accelerator.is_main_process:
|
| 595 |
+
# there are only two options here. Either are just the unet attn processor layers
|
| 596 |
+
# or there are the unet and text encoder atten layers
|
| 597 |
+
unet_lora_layers_to_save = None
|
| 598 |
+
|
| 599 |
+
for model in models:
|
| 600 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 601 |
+
unet_lora_layers_to_save = convert_state_dict_to_diffusers(get_peft_model_state_dict(model))
|
| 602 |
+
else:
|
| 603 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 604 |
+
|
| 605 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 606 |
+
weights.pop()
|
| 607 |
+
|
| 608 |
+
StableDiffusionLoraLoaderMixin.save_lora_weights(
|
| 609 |
+
output_dir,
|
| 610 |
+
unet_lora_layers=unet_lora_layers_to_save,
|
| 611 |
+
text_encoder_lora_layers=None,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
def load_model_hook(models, input_dir):
|
| 615 |
+
unet_ = None
|
| 616 |
+
|
| 617 |
+
while len(models) > 0:
|
| 618 |
+
model = models.pop()
|
| 619 |
+
|
| 620 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 621 |
+
unet_ = model
|
| 622 |
+
else:
|
| 623 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 624 |
+
|
| 625 |
+
lora_state_dict, network_alphas = StableDiffusionLoraLoaderMixin.lora_state_dict(input_dir)
|
| 626 |
+
StableDiffusionLoraLoaderMixin.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=unet_)
|
| 627 |
+
|
| 628 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 629 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 630 |
+
|
| 631 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 632 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 633 |
+
if args.allow_tf32:
|
| 634 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 635 |
+
|
| 636 |
+
if args.scale_lr:
|
| 637 |
+
args.learning_rate = (
|
| 638 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 642 |
+
if args.use_8bit_adam:
|
| 643 |
+
try:
|
| 644 |
+
import bitsandbytes as bnb
|
| 645 |
+
except ImportError:
|
| 646 |
+
raise ImportError(
|
| 647 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 651 |
+
else:
|
| 652 |
+
optimizer_class = torch.optim.AdamW
|
| 653 |
+
|
| 654 |
+
# Optimizer creation
|
| 655 |
+
params_to_optimize = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 656 |
+
optimizer = optimizer_class(
|
| 657 |
+
params_to_optimize,
|
| 658 |
+
lr=args.learning_rate,
|
| 659 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 660 |
+
weight_decay=args.adam_weight_decay,
|
| 661 |
+
eps=args.adam_epsilon,
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
# Dataset and DataLoaders creation:
|
| 665 |
+
train_dataset = load_dataset(
|
| 666 |
+
args.dataset_name,
|
| 667 |
+
cache_dir=args.cache_dir,
|
| 668 |
+
split=args.dataset_split_name,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
train_transforms = transforms.Compose(
|
| 672 |
+
[
|
| 673 |
+
transforms.Resize(int(args.resolution), interpolation=transforms.InterpolationMode.BILINEAR),
|
| 674 |
+
transforms.RandomCrop(args.resolution) if args.random_crop else transforms.CenterCrop(args.resolution),
|
| 675 |
+
transforms.Lambda(lambda x: x) if args.no_hflip else transforms.RandomHorizontalFlip(),
|
| 676 |
+
transforms.ToTensor(),
|
| 677 |
+
transforms.Normalize([0.5], [0.5]),
|
| 678 |
+
]
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
def preprocess_train(examples):
|
| 682 |
+
all_pixel_values = []
|
| 683 |
+
for col_name in ["jpg_0", "jpg_1"]:
|
| 684 |
+
images = [Image.open(io.BytesIO(im_bytes)).convert("RGB") for im_bytes in examples[col_name]]
|
| 685 |
+
pixel_values = [train_transforms(image) for image in images]
|
| 686 |
+
all_pixel_values.append(pixel_values)
|
| 687 |
+
|
| 688 |
+
# Double on channel dim, jpg_y then jpg_w
|
| 689 |
+
im_tup_iterator = zip(*all_pixel_values)
|
| 690 |
+
combined_pixel_values = []
|
| 691 |
+
for im_tup, label_0 in zip(im_tup_iterator, examples["label_0"]):
|
| 692 |
+
if label_0 == 0:
|
| 693 |
+
im_tup = im_tup[::-1]
|
| 694 |
+
combined_im = torch.cat(im_tup, dim=0) # no batch dim
|
| 695 |
+
combined_pixel_values.append(combined_im)
|
| 696 |
+
examples["pixel_values"] = combined_pixel_values
|
| 697 |
+
|
| 698 |
+
examples["input_ids"] = tokenize_captions(tokenizer, examples)
|
| 699 |
+
return examples
|
| 700 |
+
|
| 701 |
+
with accelerator.main_process_first():
|
| 702 |
+
if args.max_train_samples is not None:
|
| 703 |
+
train_dataset = train_dataset.shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 704 |
+
# Set the training transforms
|
| 705 |
+
train_dataset = train_dataset.with_transform(preprocess_train)
|
| 706 |
+
|
| 707 |
+
def collate_fn(examples):
|
| 708 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 709 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 710 |
+
final_dict = {"pixel_values": pixel_values}
|
| 711 |
+
final_dict["input_ids"] = torch.stack([example["input_ids"] for example in examples])
|
| 712 |
+
return final_dict
|
| 713 |
+
|
| 714 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 715 |
+
train_dataset,
|
| 716 |
+
batch_size=args.train_batch_size,
|
| 717 |
+
shuffle=True,
|
| 718 |
+
collate_fn=collate_fn,
|
| 719 |
+
num_workers=args.dataloader_num_workers,
|
| 720 |
+
)
|
| 721 |
+
|
| 722 |
+
# Scheduler and math around the number of training steps.
|
| 723 |
+
overrode_max_train_steps = False
|
| 724 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 725 |
+
if args.max_train_steps is None:
|
| 726 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 727 |
+
overrode_max_train_steps = True
|
| 728 |
+
|
| 729 |
+
lr_scheduler = get_scheduler(
|
| 730 |
+
args.lr_scheduler,
|
| 731 |
+
optimizer=optimizer,
|
| 732 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 733 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 734 |
+
num_cycles=args.lr_num_cycles,
|
| 735 |
+
power=args.lr_power,
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 739 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 743 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 744 |
+
if overrode_max_train_steps:
|
| 745 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 746 |
+
# Afterwards we recalculate our number of training epochs
|
| 747 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 748 |
+
|
| 749 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 750 |
+
# The trackers initializes automatically on the main process.
|
| 751 |
+
if accelerator.is_main_process:
|
| 752 |
+
accelerator.init_trackers(args.tracker_name, config=vars(args))
|
| 753 |
+
|
| 754 |
+
# Train!
|
| 755 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 756 |
+
|
| 757 |
+
logger.info("***** Running training *****")
|
| 758 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 759 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 760 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 761 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 762 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 763 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 764 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 765 |
+
global_step = 0
|
| 766 |
+
first_epoch = 0
|
| 767 |
+
|
| 768 |
+
# Potentially load in the weights and states from a previous save
|
| 769 |
+
if args.resume_from_checkpoint:
|
| 770 |
+
if args.resume_from_checkpoint != "latest":
|
| 771 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 772 |
+
else:
|
| 773 |
+
# Get the mos recent checkpoint
|
| 774 |
+
dirs = os.listdir(args.output_dir)
|
| 775 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 776 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 777 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 778 |
+
|
| 779 |
+
if path is None:
|
| 780 |
+
accelerator.print(
|
| 781 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 782 |
+
)
|
| 783 |
+
args.resume_from_checkpoint = None
|
| 784 |
+
initial_global_step = 0
|
| 785 |
+
else:
|
| 786 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 787 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 788 |
+
global_step = int(path.split("-")[1])
|
| 789 |
+
|
| 790 |
+
initial_global_step = global_step
|
| 791 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 792 |
+
else:
|
| 793 |
+
initial_global_step = 0
|
| 794 |
+
|
| 795 |
+
progress_bar = tqdm(
|
| 796 |
+
range(0, args.max_train_steps),
|
| 797 |
+
initial=initial_global_step,
|
| 798 |
+
desc="Steps",
|
| 799 |
+
# Only show the progress bar once on each machine.
|
| 800 |
+
disable=not accelerator.is_local_main_process,
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
unet.train()
|
| 804 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 805 |
+
for step, batch in enumerate(train_dataloader):
|
| 806 |
+
with accelerator.accumulate(unet):
|
| 807 |
+
# (batch_size, 2*channels, h, w) -> (2*batch_size, channels, h, w)
|
| 808 |
+
pixel_values = batch["pixel_values"].to(dtype=weight_dtype)
|
| 809 |
+
feed_pixel_values = torch.cat(pixel_values.chunk(2, dim=1))
|
| 810 |
+
|
| 811 |
+
latents = []
|
| 812 |
+
for i in range(0, feed_pixel_values.shape[0], args.vae_encode_batch_size):
|
| 813 |
+
latents.append(
|
| 814 |
+
vae.encode(feed_pixel_values[i : i + args.vae_encode_batch_size]).latent_dist.sample()
|
| 815 |
+
)
|
| 816 |
+
latents = torch.cat(latents, dim=0)
|
| 817 |
+
latents = latents * vae.config.scaling_factor
|
| 818 |
+
|
| 819 |
+
# Sample noise that we'll add to the latents
|
| 820 |
+
noise = torch.randn_like(latents).chunk(2)[0].repeat(2, 1, 1, 1)
|
| 821 |
+
|
| 822 |
+
# Sample a random timestep for each image
|
| 823 |
+
bsz = latents.shape[0] // 2
|
| 824 |
+
timesteps = torch.randint(
|
| 825 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device, dtype=torch.long
|
| 826 |
+
).repeat(2)
|
| 827 |
+
|
| 828 |
+
# Add noise to the model input according to the noise magnitude at each timestep
|
| 829 |
+
# (this is the forward diffusion process)
|
| 830 |
+
noisy_model_input = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 831 |
+
|
| 832 |
+
# Get the text embedding for conditioning
|
| 833 |
+
encoder_hidden_states = encode_prompt(text_encoder, batch["input_ids"]).repeat(2, 1, 1)
|
| 834 |
+
|
| 835 |
+
# Predict the noise residual
|
| 836 |
+
model_pred = unet(
|
| 837 |
+
noisy_model_input,
|
| 838 |
+
timesteps,
|
| 839 |
+
encoder_hidden_states,
|
| 840 |
+
).sample
|
| 841 |
+
|
| 842 |
+
# Get the target for loss depending on the prediction type
|
| 843 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 844 |
+
target = noise
|
| 845 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 846 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 847 |
+
else:
|
| 848 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 849 |
+
|
| 850 |
+
# Compute losses.
|
| 851 |
+
model_losses = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
| 852 |
+
model_losses = model_losses.mean(dim=list(range(1, len(model_losses.shape))))
|
| 853 |
+
model_losses_w, model_losses_l = model_losses.chunk(2)
|
| 854 |
+
|
| 855 |
+
# For logging
|
| 856 |
+
raw_model_loss = 0.5 * (model_losses_w.mean() + model_losses_l.mean())
|
| 857 |
+
model_diff = model_losses_w - model_losses_l # These are both LBS (as is t)
|
| 858 |
+
|
| 859 |
+
# Reference model predictions.
|
| 860 |
+
accelerator.unwrap_model(unet).disable_adapters()
|
| 861 |
+
with torch.no_grad():
|
| 862 |
+
ref_preds = unet(
|
| 863 |
+
noisy_model_input,
|
| 864 |
+
timesteps,
|
| 865 |
+
encoder_hidden_states,
|
| 866 |
+
).sample.detach()
|
| 867 |
+
ref_loss = F.mse_loss(ref_preds.float(), target.float(), reduction="none")
|
| 868 |
+
ref_loss = ref_loss.mean(dim=list(range(1, len(ref_loss.shape))))
|
| 869 |
+
|
| 870 |
+
ref_losses_w, ref_losses_l = ref_loss.chunk(2)
|
| 871 |
+
ref_diff = ref_losses_w - ref_losses_l
|
| 872 |
+
raw_ref_loss = ref_loss.mean()
|
| 873 |
+
|
| 874 |
+
# Re-enable adapters.
|
| 875 |
+
accelerator.unwrap_model(unet).enable_adapters()
|
| 876 |
+
|
| 877 |
+
# Final loss.
|
| 878 |
+
logits = ref_diff - model_diff
|
| 879 |
+
if args.loss_type == "sigmoid":
|
| 880 |
+
loss = -1 * F.logsigmoid(args.beta_dpo * logits).mean()
|
| 881 |
+
elif args.loss_type == "hinge":
|
| 882 |
+
loss = torch.relu(1 - args.beta_dpo * logits).mean()
|
| 883 |
+
elif args.loss_type == "ipo":
|
| 884 |
+
losses = (logits - 1 / (2 * args.beta)) ** 2
|
| 885 |
+
loss = losses.mean()
|
| 886 |
+
else:
|
| 887 |
+
raise ValueError(f"Unknown loss type {args.loss_type}")
|
| 888 |
+
|
| 889 |
+
implicit_acc = (logits > 0).sum().float() / logits.size(0)
|
| 890 |
+
implicit_acc += 0.5 * (logits == 0).sum().float() / logits.size(0)
|
| 891 |
+
|
| 892 |
+
accelerator.backward(loss)
|
| 893 |
+
if accelerator.sync_gradients:
|
| 894 |
+
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
|
| 895 |
+
optimizer.step()
|
| 896 |
+
lr_scheduler.step()
|
| 897 |
+
optimizer.zero_grad()
|
| 898 |
+
|
| 899 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 900 |
+
if accelerator.sync_gradients:
|
| 901 |
+
progress_bar.update(1)
|
| 902 |
+
global_step += 1
|
| 903 |
+
|
| 904 |
+
if accelerator.is_main_process:
|
| 905 |
+
if global_step % args.checkpointing_steps == 0:
|
| 906 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 907 |
+
if args.checkpoints_total_limit is not None:
|
| 908 |
+
checkpoints = os.listdir(args.output_dir)
|
| 909 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 910 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 911 |
+
|
| 912 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 913 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 914 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 915 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 916 |
+
|
| 917 |
+
logger.info(
|
| 918 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 919 |
+
)
|
| 920 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 921 |
+
|
| 922 |
+
for removing_checkpoint in removing_checkpoints:
|
| 923 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 924 |
+
shutil.rmtree(removing_checkpoint)
|
| 925 |
+
|
| 926 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 927 |
+
accelerator.save_state(save_path)
|
| 928 |
+
logger.info(f"Saved state to {save_path}")
|
| 929 |
+
|
| 930 |
+
if args.run_validation and global_step % args.validation_steps == 0:
|
| 931 |
+
log_validation(
|
| 932 |
+
args, unet=unet, accelerator=accelerator, weight_dtype=weight_dtype, epoch=epoch
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
logs = {
|
| 936 |
+
"loss": loss.detach().item(),
|
| 937 |
+
"raw_model_loss": raw_model_loss.detach().item(),
|
| 938 |
+
"ref_loss": raw_ref_loss.detach().item(),
|
| 939 |
+
"implicit_acc": implicit_acc.detach().item(),
|
| 940 |
+
"lr": lr_scheduler.get_last_lr()[0],
|
| 941 |
+
}
|
| 942 |
+
progress_bar.set_postfix(**logs)
|
| 943 |
+
accelerator.log(logs, step=global_step)
|
| 944 |
+
|
| 945 |
+
if global_step >= args.max_train_steps:
|
| 946 |
+
break
|
| 947 |
+
|
| 948 |
+
# Save the lora layers
|
| 949 |
+
accelerator.wait_for_everyone()
|
| 950 |
+
if accelerator.is_main_process:
|
| 951 |
+
unet = accelerator.unwrap_model(unet)
|
| 952 |
+
unet = unet.to(torch.float32)
|
| 953 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
|
| 954 |
+
|
| 955 |
+
StableDiffusionLoraLoaderMixin.save_lora_weights(
|
| 956 |
+
save_directory=args.output_dir, unet_lora_layers=unet_lora_state_dict, text_encoder_lora_layers=None
|
| 957 |
+
)
|
| 958 |
+
|
| 959 |
+
# Final validation?
|
| 960 |
+
if args.run_validation:
|
| 961 |
+
log_validation(
|
| 962 |
+
args,
|
| 963 |
+
unet=None,
|
| 964 |
+
accelerator=accelerator,
|
| 965 |
+
weight_dtype=weight_dtype,
|
| 966 |
+
epoch=epoch,
|
| 967 |
+
is_final_validation=True,
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
if args.push_to_hub:
|
| 971 |
+
upload_folder(
|
| 972 |
+
repo_id=repo_id,
|
| 973 |
+
folder_path=args.output_dir,
|
| 974 |
+
commit_message="End of training",
|
| 975 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
accelerator.end_training()
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
if __name__ == "__main__":
|
| 982 |
+
args = parse_args()
|
| 983 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_dpo/train_diffusion_dpo_sdxl.py
ADDED
|
@@ -0,0 +1,1141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 bram-w, The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import contextlib
|
| 19 |
+
import io
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
import shutil
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
import torch.utils.checkpoint
|
| 31 |
+
import transformers
|
| 32 |
+
import wandb
|
| 33 |
+
from accelerate import Accelerator
|
| 34 |
+
from accelerate.logging import get_logger
|
| 35 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 36 |
+
from datasets import load_dataset
|
| 37 |
+
from huggingface_hub import create_repo, upload_folder
|
| 38 |
+
from packaging import version
|
| 39 |
+
from peft import LoraConfig
|
| 40 |
+
from peft.utils import get_peft_model_state_dict
|
| 41 |
+
from PIL import Image
|
| 42 |
+
from torchvision import transforms
|
| 43 |
+
from torchvision.transforms.functional import crop
|
| 44 |
+
from tqdm.auto import tqdm
|
| 45 |
+
from transformers import AutoTokenizer, PretrainedConfig
|
| 46 |
+
|
| 47 |
+
import diffusers
|
| 48 |
+
from diffusers import (
|
| 49 |
+
AutoencoderKL,
|
| 50 |
+
DDPMScheduler,
|
| 51 |
+
DiffusionPipeline,
|
| 52 |
+
UNet2DConditionModel,
|
| 53 |
+
)
|
| 54 |
+
from diffusers.loaders import StableDiffusionXLLoraLoaderMixin
|
| 55 |
+
from diffusers.optimization import get_scheduler
|
| 56 |
+
from diffusers.utils import check_min_version, convert_state_dict_to_diffusers
|
| 57 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 61 |
+
check_min_version("0.25.0.dev0")
|
| 62 |
+
|
| 63 |
+
logger = get_logger(__name__)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
VALIDATION_PROMPTS = [
|
| 67 |
+
"portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography",
|
| 68 |
+
"Self-portrait oil painting, a beautiful cyborg with golden hair, 8k",
|
| 69 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 70 |
+
"A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece",
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def import_model_class_from_model_name_or_path(
|
| 75 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 76 |
+
):
|
| 77 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 78 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 79 |
+
)
|
| 80 |
+
model_class = text_encoder_config.architectures[0]
|
| 81 |
+
|
| 82 |
+
if model_class == "CLIPTextModel":
|
| 83 |
+
from transformers import CLIPTextModel
|
| 84 |
+
|
| 85 |
+
return CLIPTextModel
|
| 86 |
+
elif model_class == "CLIPTextModelWithProjection":
|
| 87 |
+
from transformers import CLIPTextModelWithProjection
|
| 88 |
+
|
| 89 |
+
return CLIPTextModelWithProjection
|
| 90 |
+
else:
|
| 91 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def log_validation(args, unet, vae, accelerator, weight_dtype, epoch, is_final_validation=False):
|
| 95 |
+
logger.info(f"Running validation... \n Generating images with prompts:\n {VALIDATION_PROMPTS}.")
|
| 96 |
+
|
| 97 |
+
if is_final_validation:
|
| 98 |
+
if args.mixed_precision == "fp16":
|
| 99 |
+
vae.to(weight_dtype)
|
| 100 |
+
|
| 101 |
+
# create pipeline
|
| 102 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 103 |
+
args.pretrained_model_name_or_path,
|
| 104 |
+
vae=vae,
|
| 105 |
+
revision=args.revision,
|
| 106 |
+
variant=args.variant,
|
| 107 |
+
torch_dtype=weight_dtype,
|
| 108 |
+
)
|
| 109 |
+
if not is_final_validation:
|
| 110 |
+
pipeline.unet = accelerator.unwrap_model(unet)
|
| 111 |
+
else:
|
| 112 |
+
pipeline.load_lora_weights(args.output_dir, weight_name="pytorch_lora_weights.safetensors")
|
| 113 |
+
|
| 114 |
+
pipeline = pipeline.to(accelerator.device)
|
| 115 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 116 |
+
|
| 117 |
+
# run inference
|
| 118 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 119 |
+
images = []
|
| 120 |
+
context = contextlib.nullcontext() if is_final_validation else torch.cuda.amp.autocast()
|
| 121 |
+
|
| 122 |
+
guidance_scale = 5.0
|
| 123 |
+
num_inference_steps = 25
|
| 124 |
+
if args.is_turbo:
|
| 125 |
+
guidance_scale = 0.0
|
| 126 |
+
num_inference_steps = 4
|
| 127 |
+
for prompt in VALIDATION_PROMPTS:
|
| 128 |
+
with context:
|
| 129 |
+
image = pipeline(
|
| 130 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 131 |
+
).images[0]
|
| 132 |
+
images.append(image)
|
| 133 |
+
|
| 134 |
+
tracker_key = "test" if is_final_validation else "validation"
|
| 135 |
+
for tracker in accelerator.trackers:
|
| 136 |
+
if tracker.name == "tensorboard":
|
| 137 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 138 |
+
tracker.writer.add_images(tracker_key, np_images, epoch, dataformats="NHWC")
|
| 139 |
+
if tracker.name == "wandb":
|
| 140 |
+
tracker.log(
|
| 141 |
+
{
|
| 142 |
+
tracker_key: [
|
| 143 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}") for i, image in enumerate(images)
|
| 144 |
+
]
|
| 145 |
+
}
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# Also log images without the LoRA params for comparison.
|
| 149 |
+
if is_final_validation:
|
| 150 |
+
pipeline.disable_lora()
|
| 151 |
+
no_lora_images = [
|
| 152 |
+
pipeline(
|
| 153 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 154 |
+
).images[0]
|
| 155 |
+
for prompt in VALIDATION_PROMPTS
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
for tracker in accelerator.trackers:
|
| 159 |
+
if tracker.name == "tensorboard":
|
| 160 |
+
np_images = np.stack([np.asarray(img) for img in no_lora_images])
|
| 161 |
+
tracker.writer.add_images("test_without_lora", np_images, epoch, dataformats="NHWC")
|
| 162 |
+
if tracker.name == "wandb":
|
| 163 |
+
tracker.log(
|
| 164 |
+
{
|
| 165 |
+
"test_without_lora": [
|
| 166 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}")
|
| 167 |
+
for i, image in enumerate(no_lora_images)
|
| 168 |
+
]
|
| 169 |
+
}
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def parse_args(input_args=None):
|
| 174 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--pretrained_model_name_or_path",
|
| 177 |
+
type=str,
|
| 178 |
+
default=None,
|
| 179 |
+
required=True,
|
| 180 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--pretrained_vae_model_name_or_path",
|
| 184 |
+
type=str,
|
| 185 |
+
default=None,
|
| 186 |
+
help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--revision",
|
| 190 |
+
type=str,
|
| 191 |
+
default=None,
|
| 192 |
+
required=False,
|
| 193 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--dataset_name",
|
| 197 |
+
type=str,
|
| 198 |
+
default=None,
|
| 199 |
+
help=(
|
| 200 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 201 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 202 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 203 |
+
),
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--dataset_split_name",
|
| 207 |
+
type=str,
|
| 208 |
+
default="validation",
|
| 209 |
+
help="Dataset split to be used during training. Helpful to specify for conducting experimental runs.",
|
| 210 |
+
)
|
| 211 |
+
parser.add_argument(
|
| 212 |
+
"--variant",
|
| 213 |
+
type=str,
|
| 214 |
+
default=None,
|
| 215 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 216 |
+
)
|
| 217 |
+
parser.add_argument(
|
| 218 |
+
"--run_validation",
|
| 219 |
+
default=False,
|
| 220 |
+
action="store_true",
|
| 221 |
+
help="Whether to run validation inference in between training and also after training. Helps to track progress.",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--validation_steps",
|
| 225 |
+
type=int,
|
| 226 |
+
default=200,
|
| 227 |
+
help="Run validation every X steps.",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--max_train_samples",
|
| 231 |
+
type=int,
|
| 232 |
+
default=None,
|
| 233 |
+
help=(
|
| 234 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 235 |
+
"value if set."
|
| 236 |
+
),
|
| 237 |
+
)
|
| 238 |
+
parser.add_argument(
|
| 239 |
+
"--output_dir",
|
| 240 |
+
type=str,
|
| 241 |
+
default="diffusion-dpo-lora",
|
| 242 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 243 |
+
)
|
| 244 |
+
parser.add_argument(
|
| 245 |
+
"--cache_dir",
|
| 246 |
+
type=str,
|
| 247 |
+
default=None,
|
| 248 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 251 |
+
parser.add_argument(
|
| 252 |
+
"--resolution",
|
| 253 |
+
type=int,
|
| 254 |
+
default=1024,
|
| 255 |
+
help=(
|
| 256 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 257 |
+
" resolution"
|
| 258 |
+
),
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"--vae_encode_batch_size",
|
| 262 |
+
type=int,
|
| 263 |
+
default=8,
|
| 264 |
+
help="Batch size to use for VAE encoding of the images for efficient processing.",
|
| 265 |
+
)
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
"--no_hflip",
|
| 268 |
+
action="store_true",
|
| 269 |
+
help="whether to randomly flip images horizontally",
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--random_crop",
|
| 273 |
+
default=False,
|
| 274 |
+
action="store_true",
|
| 275 |
+
help=(
|
| 276 |
+
"Whether to random crop the input images to the resolution. If not set, the images will be center-cropped."
|
| 277 |
+
),
|
| 278 |
+
)
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 281 |
+
)
|
| 282 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--max_train_steps",
|
| 285 |
+
type=int,
|
| 286 |
+
default=None,
|
| 287 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 288 |
+
)
|
| 289 |
+
parser.add_argument(
|
| 290 |
+
"--checkpointing_steps",
|
| 291 |
+
type=int,
|
| 292 |
+
default=500,
|
| 293 |
+
help=(
|
| 294 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 295 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 296 |
+
" training using `--resume_from_checkpoint`."
|
| 297 |
+
),
|
| 298 |
+
)
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--checkpoints_total_limit",
|
| 301 |
+
type=int,
|
| 302 |
+
default=None,
|
| 303 |
+
help=("Max number of checkpoints to store."),
|
| 304 |
+
)
|
| 305 |
+
parser.add_argument(
|
| 306 |
+
"--resume_from_checkpoint",
|
| 307 |
+
type=str,
|
| 308 |
+
default=None,
|
| 309 |
+
help=(
|
| 310 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 311 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 312 |
+
),
|
| 313 |
+
)
|
| 314 |
+
parser.add_argument(
|
| 315 |
+
"--gradient_accumulation_steps",
|
| 316 |
+
type=int,
|
| 317 |
+
default=1,
|
| 318 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 319 |
+
)
|
| 320 |
+
parser.add_argument(
|
| 321 |
+
"--gradient_checkpointing",
|
| 322 |
+
action="store_true",
|
| 323 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 324 |
+
)
|
| 325 |
+
parser.add_argument(
|
| 326 |
+
"--beta_dpo",
|
| 327 |
+
type=int,
|
| 328 |
+
default=5000,
|
| 329 |
+
help="DPO KL Divergence penalty.",
|
| 330 |
+
)
|
| 331 |
+
parser.add_argument(
|
| 332 |
+
"--learning_rate",
|
| 333 |
+
type=float,
|
| 334 |
+
default=5e-4,
|
| 335 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--scale_lr",
|
| 339 |
+
action="store_true",
|
| 340 |
+
default=False,
|
| 341 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 342 |
+
)
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--lr_scheduler",
|
| 345 |
+
type=str,
|
| 346 |
+
default="constant",
|
| 347 |
+
help=(
|
| 348 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 349 |
+
' "constant", "constant_with_warmup"]'
|
| 350 |
+
),
|
| 351 |
+
)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 354 |
+
)
|
| 355 |
+
parser.add_argument(
|
| 356 |
+
"--lr_num_cycles",
|
| 357 |
+
type=int,
|
| 358 |
+
default=1,
|
| 359 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 360 |
+
)
|
| 361 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--dataloader_num_workers",
|
| 364 |
+
type=int,
|
| 365 |
+
default=0,
|
| 366 |
+
help=(
|
| 367 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 368 |
+
),
|
| 369 |
+
)
|
| 370 |
+
parser.add_argument(
|
| 371 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 374 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 375 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 376 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 377 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 378 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 379 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 380 |
+
parser.add_argument(
|
| 381 |
+
"--hub_model_id",
|
| 382 |
+
type=str,
|
| 383 |
+
default=None,
|
| 384 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 385 |
+
)
|
| 386 |
+
parser.add_argument(
|
| 387 |
+
"--logging_dir",
|
| 388 |
+
type=str,
|
| 389 |
+
default="logs",
|
| 390 |
+
help=(
|
| 391 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 392 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 393 |
+
),
|
| 394 |
+
)
|
| 395 |
+
parser.add_argument(
|
| 396 |
+
"--allow_tf32",
|
| 397 |
+
action="store_true",
|
| 398 |
+
help=(
|
| 399 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 400 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 401 |
+
),
|
| 402 |
+
)
|
| 403 |
+
parser.add_argument(
|
| 404 |
+
"--report_to",
|
| 405 |
+
type=str,
|
| 406 |
+
default="tensorboard",
|
| 407 |
+
help=(
|
| 408 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 409 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 410 |
+
),
|
| 411 |
+
)
|
| 412 |
+
parser.add_argument(
|
| 413 |
+
"--mixed_precision",
|
| 414 |
+
type=str,
|
| 415 |
+
default=None,
|
| 416 |
+
choices=["no", "fp16", "bf16"],
|
| 417 |
+
help=(
|
| 418 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 419 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 420 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 421 |
+
),
|
| 422 |
+
)
|
| 423 |
+
parser.add_argument(
|
| 424 |
+
"--prior_generation_precision",
|
| 425 |
+
type=str,
|
| 426 |
+
default=None,
|
| 427 |
+
choices=["no", "fp32", "fp16", "bf16"],
|
| 428 |
+
help=(
|
| 429 |
+
"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 430 |
+
" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
|
| 431 |
+
),
|
| 432 |
+
)
|
| 433 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 434 |
+
parser.add_argument(
|
| 435 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 436 |
+
)
|
| 437 |
+
parser.add_argument(
|
| 438 |
+
"--is_turbo",
|
| 439 |
+
action="store_true",
|
| 440 |
+
help=("Use if tuning SDXL Turbo instead of SDXL"),
|
| 441 |
+
)
|
| 442 |
+
parser.add_argument(
|
| 443 |
+
"--rank",
|
| 444 |
+
type=int,
|
| 445 |
+
default=4,
|
| 446 |
+
help=("The dimension of the LoRA update matrices."),
|
| 447 |
+
)
|
| 448 |
+
parser.add_argument(
|
| 449 |
+
"--tracker_name",
|
| 450 |
+
type=str,
|
| 451 |
+
default="diffusion-dpo-lora-sdxl",
|
| 452 |
+
help=("The name of the tracker to report results to."),
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
if input_args is not None:
|
| 456 |
+
args = parser.parse_args(input_args)
|
| 457 |
+
else:
|
| 458 |
+
args = parser.parse_args()
|
| 459 |
+
|
| 460 |
+
if args.dataset_name is None:
|
| 461 |
+
raise ValueError("Must provide a `dataset_name`.")
|
| 462 |
+
|
| 463 |
+
if args.is_turbo:
|
| 464 |
+
assert "turbo" in args.pretrained_model_name_or_path
|
| 465 |
+
|
| 466 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 467 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 468 |
+
args.local_rank = env_local_rank
|
| 469 |
+
|
| 470 |
+
return args
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def tokenize_captions(tokenizers, examples):
|
| 474 |
+
captions = []
|
| 475 |
+
for caption in examples["caption"]:
|
| 476 |
+
captions.append(caption)
|
| 477 |
+
|
| 478 |
+
tokens_one = tokenizers[0](
|
| 479 |
+
captions, truncation=True, padding="max_length", max_length=tokenizers[0].model_max_length, return_tensors="pt"
|
| 480 |
+
).input_ids
|
| 481 |
+
tokens_two = tokenizers[1](
|
| 482 |
+
captions, truncation=True, padding="max_length", max_length=tokenizers[1].model_max_length, return_tensors="pt"
|
| 483 |
+
).input_ids
|
| 484 |
+
|
| 485 |
+
return tokens_one, tokens_two
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
@torch.no_grad()
|
| 489 |
+
def encode_prompt(text_encoders, text_input_ids_list):
|
| 490 |
+
prompt_embeds_list = []
|
| 491 |
+
|
| 492 |
+
for i, text_encoder in enumerate(text_encoders):
|
| 493 |
+
text_input_ids = text_input_ids_list[i]
|
| 494 |
+
|
| 495 |
+
prompt_embeds = text_encoder(
|
| 496 |
+
text_input_ids.to(text_encoder.device),
|
| 497 |
+
output_hidden_states=True,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 501 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
| 502 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 503 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 504 |
+
prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
|
| 505 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 506 |
+
|
| 507 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 508 |
+
pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
|
| 509 |
+
return prompt_embeds, pooled_prompt_embeds
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def main(args):
|
| 513 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 514 |
+
raise ValueError(
|
| 515 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 516 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 520 |
+
|
| 521 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 522 |
+
|
| 523 |
+
accelerator = Accelerator(
|
| 524 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 525 |
+
mixed_precision=args.mixed_precision,
|
| 526 |
+
log_with=args.report_to,
|
| 527 |
+
project_config=accelerator_project_config,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# Disable AMP for MPS.
|
| 531 |
+
if torch.backends.mps.is_available():
|
| 532 |
+
accelerator.native_amp = False
|
| 533 |
+
|
| 534 |
+
# Make one log on every process with the configuration for debugging.
|
| 535 |
+
logging.basicConfig(
|
| 536 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 537 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 538 |
+
level=logging.INFO,
|
| 539 |
+
)
|
| 540 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 541 |
+
if accelerator.is_local_main_process:
|
| 542 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 543 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 544 |
+
else:
|
| 545 |
+
transformers.utils.logging.set_verbosity_error()
|
| 546 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 547 |
+
|
| 548 |
+
# If passed along, set the training seed now.
|
| 549 |
+
if args.seed is not None:
|
| 550 |
+
set_seed(args.seed)
|
| 551 |
+
|
| 552 |
+
# Handle the repository creation
|
| 553 |
+
if accelerator.is_main_process:
|
| 554 |
+
if args.output_dir is not None:
|
| 555 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 556 |
+
|
| 557 |
+
if args.push_to_hub:
|
| 558 |
+
repo_id = create_repo(
|
| 559 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 560 |
+
).repo_id
|
| 561 |
+
|
| 562 |
+
# Load the tokenizers
|
| 563 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 564 |
+
args.pretrained_model_name_or_path,
|
| 565 |
+
subfolder="tokenizer",
|
| 566 |
+
revision=args.revision,
|
| 567 |
+
use_fast=False,
|
| 568 |
+
)
|
| 569 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 570 |
+
args.pretrained_model_name_or_path,
|
| 571 |
+
subfolder="tokenizer_2",
|
| 572 |
+
revision=args.revision,
|
| 573 |
+
use_fast=False,
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
# import correct text encoder classes
|
| 577 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 578 |
+
args.pretrained_model_name_or_path, args.revision
|
| 579 |
+
)
|
| 580 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 581 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
# Load scheduler and models
|
| 585 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 586 |
+
|
| 587 |
+
def enforce_zero_terminal_snr(scheduler):
|
| 588 |
+
# Modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_ddpm.py#L93
|
| 589 |
+
# Original implementation https://huggingface.co/papers/2305.08891
|
| 590 |
+
# Turbo needs zero terminal SNR
|
| 591 |
+
# Turbo: https://static1.squarespace.com/static/6213c340453c3f502425776e/t/65663480a92fba51d0e1023f/1701197769659/adversarial_diffusion_distillation.pdf
|
| 592 |
+
# Convert betas to alphas_bar_sqrt
|
| 593 |
+
alphas = 1 - scheduler.betas
|
| 594 |
+
alphas_bar = alphas.cumprod(0)
|
| 595 |
+
alphas_bar_sqrt = alphas_bar.sqrt()
|
| 596 |
+
|
| 597 |
+
# Store old values.
|
| 598 |
+
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
|
| 599 |
+
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
|
| 600 |
+
# Shift so last timestep is zero.
|
| 601 |
+
alphas_bar_sqrt -= alphas_bar_sqrt_T
|
| 602 |
+
# Scale so first timestep is back to old value.
|
| 603 |
+
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
|
| 604 |
+
|
| 605 |
+
alphas_bar = alphas_bar_sqrt**2
|
| 606 |
+
alphas = alphas_bar[1:] / alphas_bar[:-1]
|
| 607 |
+
alphas = torch.cat([alphas_bar[0:1], alphas])
|
| 608 |
+
|
| 609 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 610 |
+
scheduler.alphas_cumprod = alphas_cumprod
|
| 611 |
+
return
|
| 612 |
+
|
| 613 |
+
if args.is_turbo:
|
| 614 |
+
enforce_zero_terminal_snr(noise_scheduler)
|
| 615 |
+
|
| 616 |
+
text_encoder_one = text_encoder_cls_one.from_pretrained(
|
| 617 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 618 |
+
)
|
| 619 |
+
text_encoder_two = text_encoder_cls_two.from_pretrained(
|
| 620 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
| 621 |
+
)
|
| 622 |
+
vae_path = (
|
| 623 |
+
args.pretrained_model_name_or_path
|
| 624 |
+
if args.pretrained_vae_model_name_or_path is None
|
| 625 |
+
else args.pretrained_vae_model_name_or_path
|
| 626 |
+
)
|
| 627 |
+
vae = AutoencoderKL.from_pretrained(
|
| 628 |
+
vae_path,
|
| 629 |
+
subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
|
| 630 |
+
revision=args.revision,
|
| 631 |
+
variant=args.variant,
|
| 632 |
+
)
|
| 633 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 634 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# We only train the additional adapter LoRA layers
|
| 638 |
+
vae.requires_grad_(False)
|
| 639 |
+
text_encoder_one.requires_grad_(False)
|
| 640 |
+
text_encoder_two.requires_grad_(False)
|
| 641 |
+
unet.requires_grad_(False)
|
| 642 |
+
|
| 643 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 644 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 645 |
+
weight_dtype = torch.float32
|
| 646 |
+
if accelerator.mixed_precision == "fp16":
|
| 647 |
+
weight_dtype = torch.float16
|
| 648 |
+
elif accelerator.mixed_precision == "bf16":
|
| 649 |
+
weight_dtype = torch.bfloat16
|
| 650 |
+
|
| 651 |
+
# Move unet and text_encoders to device and cast to weight_dtype
|
| 652 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 653 |
+
text_encoder_one.to(accelerator.device, dtype=weight_dtype)
|
| 654 |
+
text_encoder_two.to(accelerator.device, dtype=weight_dtype)
|
| 655 |
+
|
| 656 |
+
# The VAE is always in float32 to avoid NaN losses.
|
| 657 |
+
vae.to(accelerator.device, dtype=torch.float32)
|
| 658 |
+
|
| 659 |
+
# Set up LoRA.
|
| 660 |
+
unet_lora_config = LoraConfig(
|
| 661 |
+
r=args.rank,
|
| 662 |
+
lora_alpha=args.rank,
|
| 663 |
+
init_lora_weights="gaussian",
|
| 664 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 665 |
+
)
|
| 666 |
+
# Add adapter and make sure the trainable params are in float32.
|
| 667 |
+
unet.add_adapter(unet_lora_config)
|
| 668 |
+
if args.mixed_precision == "fp16":
|
| 669 |
+
for param in unet.parameters():
|
| 670 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 671 |
+
if param.requires_grad:
|
| 672 |
+
param.data = param.to(torch.float32)
|
| 673 |
+
|
| 674 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 675 |
+
if is_xformers_available():
|
| 676 |
+
import xformers
|
| 677 |
+
|
| 678 |
+
xformers_version = version.parse(xformers.__version__)
|
| 679 |
+
if xformers_version == version.parse("0.0.16"):
|
| 680 |
+
logger.warning(
|
| 681 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 682 |
+
)
|
| 683 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 684 |
+
else:
|
| 685 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 686 |
+
|
| 687 |
+
if args.gradient_checkpointing:
|
| 688 |
+
unet.enable_gradient_checkpointing()
|
| 689 |
+
|
| 690 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 691 |
+
def save_model_hook(models, weights, output_dir):
|
| 692 |
+
if accelerator.is_main_process:
|
| 693 |
+
# there are only two options here. Either are just the unet attn processor layers
|
| 694 |
+
# or there are the unet and text encoder atten layers
|
| 695 |
+
unet_lora_layers_to_save = None
|
| 696 |
+
|
| 697 |
+
for model in models:
|
| 698 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 699 |
+
unet_lora_layers_to_save = convert_state_dict_to_diffusers(get_peft_model_state_dict(model))
|
| 700 |
+
else:
|
| 701 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 702 |
+
|
| 703 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 704 |
+
weights.pop()
|
| 705 |
+
|
| 706 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(output_dir, unet_lora_layers=unet_lora_layers_to_save)
|
| 707 |
+
|
| 708 |
+
def load_model_hook(models, input_dir):
|
| 709 |
+
unet_ = None
|
| 710 |
+
|
| 711 |
+
while len(models) > 0:
|
| 712 |
+
model = models.pop()
|
| 713 |
+
|
| 714 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 715 |
+
unet_ = model
|
| 716 |
+
else:
|
| 717 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 718 |
+
|
| 719 |
+
lora_state_dict, network_alphas = StableDiffusionXLLoraLoaderMixin.lora_state_dict(input_dir)
|
| 720 |
+
StableDiffusionXLLoraLoaderMixin.load_lora_into_unet(
|
| 721 |
+
lora_state_dict, network_alphas=network_alphas, unet=unet_
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 725 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 726 |
+
|
| 727 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 728 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 729 |
+
if args.allow_tf32:
|
| 730 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 731 |
+
|
| 732 |
+
if args.scale_lr:
|
| 733 |
+
args.learning_rate = (
|
| 734 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 738 |
+
if args.use_8bit_adam:
|
| 739 |
+
try:
|
| 740 |
+
import bitsandbytes as bnb
|
| 741 |
+
except ImportError:
|
| 742 |
+
raise ImportError(
|
| 743 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 747 |
+
else:
|
| 748 |
+
optimizer_class = torch.optim.AdamW
|
| 749 |
+
|
| 750 |
+
# Optimizer creation
|
| 751 |
+
params_to_optimize = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 752 |
+
optimizer = optimizer_class(
|
| 753 |
+
params_to_optimize,
|
| 754 |
+
lr=args.learning_rate,
|
| 755 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 756 |
+
weight_decay=args.adam_weight_decay,
|
| 757 |
+
eps=args.adam_epsilon,
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
# Dataset and DataLoaders creation:
|
| 761 |
+
train_dataset = load_dataset(
|
| 762 |
+
args.dataset_name,
|
| 763 |
+
cache_dir=args.cache_dir,
|
| 764 |
+
split=args.dataset_split_name,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Preprocessing the datasets.
|
| 768 |
+
train_resize = transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 769 |
+
train_crop = transforms.RandomCrop(args.resolution) if args.random_crop else transforms.CenterCrop(args.resolution)
|
| 770 |
+
train_flip = transforms.RandomHorizontalFlip(p=1.0)
|
| 771 |
+
to_tensor = transforms.ToTensor()
|
| 772 |
+
normalize = transforms.Normalize([0.5], [0.5])
|
| 773 |
+
|
| 774 |
+
def preprocess_train(examples):
|
| 775 |
+
all_pixel_values = []
|
| 776 |
+
images = [Image.open(io.BytesIO(im_bytes)).convert("RGB") for im_bytes in examples["jpg_0"]]
|
| 777 |
+
original_sizes = [(image.height, image.width) for image in images]
|
| 778 |
+
crop_top_lefts = []
|
| 779 |
+
|
| 780 |
+
for col_name in ["jpg_0", "jpg_1"]:
|
| 781 |
+
images = [Image.open(io.BytesIO(im_bytes)).convert("RGB") for im_bytes in examples[col_name]]
|
| 782 |
+
if col_name == "jpg_1":
|
| 783 |
+
# Need to bring down the image to the same resolution.
|
| 784 |
+
# This seems like the simplest reasonable approach.
|
| 785 |
+
# "::-1" because PIL resize takes (width, height).
|
| 786 |
+
images = [image.resize(original_sizes[i][::-1]) for i, image in enumerate(images)]
|
| 787 |
+
pixel_values = [to_tensor(image) for image in images]
|
| 788 |
+
all_pixel_values.append(pixel_values)
|
| 789 |
+
|
| 790 |
+
# Double on channel dim, jpg_y then jpg_w
|
| 791 |
+
im_tup_iterator = zip(*all_pixel_values)
|
| 792 |
+
combined_pixel_values = []
|
| 793 |
+
for im_tup, label_0 in zip(im_tup_iterator, examples["label_0"]):
|
| 794 |
+
if label_0 == 0:
|
| 795 |
+
im_tup = im_tup[::-1]
|
| 796 |
+
|
| 797 |
+
combined_im = torch.cat(im_tup, dim=0) # no batch dim
|
| 798 |
+
|
| 799 |
+
# Resize.
|
| 800 |
+
combined_im = train_resize(combined_im)
|
| 801 |
+
|
| 802 |
+
# Flipping.
|
| 803 |
+
if not args.no_hflip and random.random() < 0.5:
|
| 804 |
+
combined_im = train_flip(combined_im)
|
| 805 |
+
|
| 806 |
+
# Cropping.
|
| 807 |
+
if not args.random_crop:
|
| 808 |
+
y1 = max(0, int(round((combined_im.shape[1] - args.resolution) / 2.0)))
|
| 809 |
+
x1 = max(0, int(round((combined_im.shape[2] - args.resolution) / 2.0)))
|
| 810 |
+
combined_im = train_crop(combined_im)
|
| 811 |
+
else:
|
| 812 |
+
y1, x1, h, w = train_crop.get_params(combined_im, (args.resolution, args.resolution))
|
| 813 |
+
combined_im = crop(combined_im, y1, x1, h, w)
|
| 814 |
+
|
| 815 |
+
crop_top_left = (y1, x1)
|
| 816 |
+
crop_top_lefts.append(crop_top_left)
|
| 817 |
+
combined_im = normalize(combined_im)
|
| 818 |
+
combined_pixel_values.append(combined_im)
|
| 819 |
+
|
| 820 |
+
examples["pixel_values"] = combined_pixel_values
|
| 821 |
+
examples["original_sizes"] = original_sizes
|
| 822 |
+
examples["crop_top_lefts"] = crop_top_lefts
|
| 823 |
+
tokens_one, tokens_two = tokenize_captions([tokenizer_one, tokenizer_two], examples)
|
| 824 |
+
examples["input_ids_one"] = tokens_one
|
| 825 |
+
examples["input_ids_two"] = tokens_two
|
| 826 |
+
return examples
|
| 827 |
+
|
| 828 |
+
with accelerator.main_process_first():
|
| 829 |
+
if args.max_train_samples is not None:
|
| 830 |
+
train_dataset = train_dataset.shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 831 |
+
# Set the training transforms
|
| 832 |
+
train_dataset = train_dataset.with_transform(preprocess_train)
|
| 833 |
+
|
| 834 |
+
def collate_fn(examples):
|
| 835 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 836 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 837 |
+
original_sizes = [example["original_sizes"] for example in examples]
|
| 838 |
+
crop_top_lefts = [example["crop_top_lefts"] for example in examples]
|
| 839 |
+
input_ids_one = torch.stack([example["input_ids_one"] for example in examples])
|
| 840 |
+
input_ids_two = torch.stack([example["input_ids_two"] for example in examples])
|
| 841 |
+
|
| 842 |
+
return {
|
| 843 |
+
"pixel_values": pixel_values,
|
| 844 |
+
"input_ids_one": input_ids_one,
|
| 845 |
+
"input_ids_two": input_ids_two,
|
| 846 |
+
"original_sizes": original_sizes,
|
| 847 |
+
"crop_top_lefts": crop_top_lefts,
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 851 |
+
train_dataset,
|
| 852 |
+
batch_size=args.train_batch_size,
|
| 853 |
+
shuffle=True,
|
| 854 |
+
collate_fn=collate_fn,
|
| 855 |
+
num_workers=args.dataloader_num_workers,
|
| 856 |
+
)
|
| 857 |
+
|
| 858 |
+
# Scheduler and math around the number of training steps.
|
| 859 |
+
overrode_max_train_steps = False
|
| 860 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 861 |
+
if args.max_train_steps is None:
|
| 862 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 863 |
+
overrode_max_train_steps = True
|
| 864 |
+
|
| 865 |
+
lr_scheduler = get_scheduler(
|
| 866 |
+
args.lr_scheduler,
|
| 867 |
+
optimizer=optimizer,
|
| 868 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 869 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 870 |
+
num_cycles=args.lr_num_cycles,
|
| 871 |
+
power=args.lr_power,
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 875 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 879 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 880 |
+
if overrode_max_train_steps:
|
| 881 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 882 |
+
# Afterwards we recalculate our number of training epochs
|
| 883 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 884 |
+
|
| 885 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 886 |
+
# The trackers initializes automatically on the main process.
|
| 887 |
+
if accelerator.is_main_process:
|
| 888 |
+
accelerator.init_trackers(args.tracker_name, config=vars(args))
|
| 889 |
+
|
| 890 |
+
# Train!
|
| 891 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 892 |
+
|
| 893 |
+
logger.info("***** Running training *****")
|
| 894 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 895 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 896 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 897 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 898 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 899 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 900 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 901 |
+
global_step = 0
|
| 902 |
+
first_epoch = 0
|
| 903 |
+
|
| 904 |
+
# Potentially load in the weights and states from a previous save
|
| 905 |
+
if args.resume_from_checkpoint:
|
| 906 |
+
if args.resume_from_checkpoint != "latest":
|
| 907 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 908 |
+
else:
|
| 909 |
+
# Get the mos recent checkpoint
|
| 910 |
+
dirs = os.listdir(args.output_dir)
|
| 911 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 912 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 913 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 914 |
+
|
| 915 |
+
if path is None:
|
| 916 |
+
accelerator.print(
|
| 917 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 918 |
+
)
|
| 919 |
+
args.resume_from_checkpoint = None
|
| 920 |
+
initial_global_step = 0
|
| 921 |
+
else:
|
| 922 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 923 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 924 |
+
global_step = int(path.split("-")[1])
|
| 925 |
+
|
| 926 |
+
initial_global_step = global_step
|
| 927 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 928 |
+
else:
|
| 929 |
+
initial_global_step = 0
|
| 930 |
+
|
| 931 |
+
progress_bar = tqdm(
|
| 932 |
+
range(0, args.max_train_steps),
|
| 933 |
+
initial=initial_global_step,
|
| 934 |
+
desc="Steps",
|
| 935 |
+
# Only show the progress bar once on each machine.
|
| 936 |
+
disable=not accelerator.is_local_main_process,
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
unet.train()
|
| 940 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 941 |
+
for step, batch in enumerate(train_dataloader):
|
| 942 |
+
with accelerator.accumulate(unet):
|
| 943 |
+
# (batch_size, 2*channels, h, w) -> (2*batch_size, channels, h, w)
|
| 944 |
+
pixel_values = batch["pixel_values"].to(dtype=vae.dtype)
|
| 945 |
+
feed_pixel_values = torch.cat(pixel_values.chunk(2, dim=1))
|
| 946 |
+
|
| 947 |
+
latents = []
|
| 948 |
+
for i in range(0, feed_pixel_values.shape[0], args.vae_encode_batch_size):
|
| 949 |
+
latents.append(
|
| 950 |
+
vae.encode(feed_pixel_values[i : i + args.vae_encode_batch_size]).latent_dist.sample()
|
| 951 |
+
)
|
| 952 |
+
latents = torch.cat(latents, dim=0)
|
| 953 |
+
latents = latents * vae.config.scaling_factor
|
| 954 |
+
if args.pretrained_vae_model_name_or_path is None:
|
| 955 |
+
latents = latents.to(weight_dtype)
|
| 956 |
+
|
| 957 |
+
# Sample noise that we'll add to the latents
|
| 958 |
+
noise = torch.randn_like(latents).chunk(2)[0].repeat(2, 1, 1, 1)
|
| 959 |
+
|
| 960 |
+
# Sample a random timestep for each image
|
| 961 |
+
bsz = latents.shape[0] // 2
|
| 962 |
+
timesteps = torch.randint(
|
| 963 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device, dtype=torch.long
|
| 964 |
+
).repeat(2)
|
| 965 |
+
if args.is_turbo:
|
| 966 |
+
# Learn a 4 timestep schedule
|
| 967 |
+
timesteps_0_to_3 = timesteps % 4
|
| 968 |
+
timesteps = 250 * timesteps_0_to_3 + 249
|
| 969 |
+
|
| 970 |
+
# Add noise to the model input according to the noise magnitude at each timestep
|
| 971 |
+
# (this is the forward diffusion process)
|
| 972 |
+
noisy_model_input = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 973 |
+
|
| 974 |
+
# time ids
|
| 975 |
+
def compute_time_ids(original_size, crops_coords_top_left):
|
| 976 |
+
# Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
|
| 977 |
+
target_size = (args.resolution, args.resolution)
|
| 978 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 979 |
+
add_time_ids = torch.tensor([add_time_ids])
|
| 980 |
+
add_time_ids = add_time_ids.to(accelerator.device, dtype=weight_dtype)
|
| 981 |
+
return add_time_ids
|
| 982 |
+
|
| 983 |
+
add_time_ids = torch.cat(
|
| 984 |
+
[compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
|
| 985 |
+
).repeat(2, 1)
|
| 986 |
+
|
| 987 |
+
# Get the text embedding for conditioning
|
| 988 |
+
prompt_embeds, pooled_prompt_embeds = encode_prompt(
|
| 989 |
+
[text_encoder_one, text_encoder_two], [batch["input_ids_one"], batch["input_ids_two"]]
|
| 990 |
+
)
|
| 991 |
+
prompt_embeds = prompt_embeds.repeat(2, 1, 1)
|
| 992 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(2, 1)
|
| 993 |
+
|
| 994 |
+
# Predict the noise residual
|
| 995 |
+
model_pred = unet(
|
| 996 |
+
noisy_model_input,
|
| 997 |
+
timesteps,
|
| 998 |
+
prompt_embeds,
|
| 999 |
+
added_cond_kwargs={"time_ids": add_time_ids, "text_embeds": pooled_prompt_embeds},
|
| 1000 |
+
).sample
|
| 1001 |
+
|
| 1002 |
+
# Get the target for loss depending on the prediction type
|
| 1003 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 1004 |
+
target = noise
|
| 1005 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 1006 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 1007 |
+
else:
|
| 1008 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 1009 |
+
|
| 1010 |
+
# Compute losses.
|
| 1011 |
+
model_losses = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
| 1012 |
+
model_losses = model_losses.mean(dim=list(range(1, len(model_losses.shape))))
|
| 1013 |
+
model_losses_w, model_losses_l = model_losses.chunk(2)
|
| 1014 |
+
|
| 1015 |
+
# For logging
|
| 1016 |
+
raw_model_loss = 0.5 * (model_losses_w.mean() + model_losses_l.mean())
|
| 1017 |
+
model_diff = model_losses_w - model_losses_l # These are both LBS (as is t)
|
| 1018 |
+
|
| 1019 |
+
# Reference model predictions.
|
| 1020 |
+
accelerator.unwrap_model(unet).disable_adapters()
|
| 1021 |
+
with torch.no_grad():
|
| 1022 |
+
ref_preds = unet(
|
| 1023 |
+
noisy_model_input,
|
| 1024 |
+
timesteps,
|
| 1025 |
+
prompt_embeds,
|
| 1026 |
+
added_cond_kwargs={"time_ids": add_time_ids, "text_embeds": pooled_prompt_embeds},
|
| 1027 |
+
).sample
|
| 1028 |
+
ref_loss = F.mse_loss(ref_preds.float(), target.float(), reduction="none")
|
| 1029 |
+
ref_loss = ref_loss.mean(dim=list(range(1, len(ref_loss.shape))))
|
| 1030 |
+
|
| 1031 |
+
ref_losses_w, ref_losses_l = ref_loss.chunk(2)
|
| 1032 |
+
ref_diff = ref_losses_w - ref_losses_l
|
| 1033 |
+
raw_ref_loss = ref_loss.mean()
|
| 1034 |
+
|
| 1035 |
+
# Re-enable adapters.
|
| 1036 |
+
accelerator.unwrap_model(unet).enable_adapters()
|
| 1037 |
+
|
| 1038 |
+
# Final loss.
|
| 1039 |
+
scale_term = -0.5 * args.beta_dpo
|
| 1040 |
+
inside_term = scale_term * (model_diff - ref_diff)
|
| 1041 |
+
loss = -1 * F.logsigmoid(inside_term).mean()
|
| 1042 |
+
|
| 1043 |
+
implicit_acc = (inside_term > 0).sum().float() / inside_term.size(0)
|
| 1044 |
+
implicit_acc += 0.5 * (inside_term == 0).sum().float() / inside_term.size(0)
|
| 1045 |
+
|
| 1046 |
+
accelerator.backward(loss)
|
| 1047 |
+
if accelerator.sync_gradients:
|
| 1048 |
+
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
|
| 1049 |
+
optimizer.step()
|
| 1050 |
+
lr_scheduler.step()
|
| 1051 |
+
optimizer.zero_grad()
|
| 1052 |
+
|
| 1053 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1054 |
+
if accelerator.sync_gradients:
|
| 1055 |
+
progress_bar.update(1)
|
| 1056 |
+
global_step += 1
|
| 1057 |
+
|
| 1058 |
+
if accelerator.is_main_process:
|
| 1059 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1060 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1061 |
+
if args.checkpoints_total_limit is not None:
|
| 1062 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1063 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1064 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1065 |
+
|
| 1066 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1067 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1068 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1069 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1070 |
+
|
| 1071 |
+
logger.info(
|
| 1072 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1073 |
+
)
|
| 1074 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1075 |
+
|
| 1076 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1077 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1078 |
+
shutil.rmtree(removing_checkpoint)
|
| 1079 |
+
|
| 1080 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1081 |
+
accelerator.save_state(save_path)
|
| 1082 |
+
logger.info(f"Saved state to {save_path}")
|
| 1083 |
+
|
| 1084 |
+
if args.run_validation and global_step % args.validation_steps == 0:
|
| 1085 |
+
log_validation(
|
| 1086 |
+
args, unet=unet, vae=vae, accelerator=accelerator, weight_dtype=weight_dtype, epoch=epoch
|
| 1087 |
+
)
|
| 1088 |
+
|
| 1089 |
+
logs = {
|
| 1090 |
+
"loss": loss.detach().item(),
|
| 1091 |
+
"raw_model_loss": raw_model_loss.detach().item(),
|
| 1092 |
+
"ref_loss": raw_ref_loss.detach().item(),
|
| 1093 |
+
"implicit_acc": implicit_acc.detach().item(),
|
| 1094 |
+
"lr": lr_scheduler.get_last_lr()[0],
|
| 1095 |
+
}
|
| 1096 |
+
progress_bar.set_postfix(**logs)
|
| 1097 |
+
accelerator.log(logs, step=global_step)
|
| 1098 |
+
|
| 1099 |
+
if global_step >= args.max_train_steps:
|
| 1100 |
+
break
|
| 1101 |
+
|
| 1102 |
+
# Save the lora layers
|
| 1103 |
+
accelerator.wait_for_everyone()
|
| 1104 |
+
if accelerator.is_main_process:
|
| 1105 |
+
unet = accelerator.unwrap_model(unet)
|
| 1106 |
+
unet = unet.to(torch.float32)
|
| 1107 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
|
| 1108 |
+
|
| 1109 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(
|
| 1110 |
+
save_directory=args.output_dir,
|
| 1111 |
+
unet_lora_layers=unet_lora_state_dict,
|
| 1112 |
+
text_encoder_lora_layers=None,
|
| 1113 |
+
text_encoder_2_lora_layers=None,
|
| 1114 |
+
)
|
| 1115 |
+
|
| 1116 |
+
# Final validation?
|
| 1117 |
+
if args.run_validation:
|
| 1118 |
+
log_validation(
|
| 1119 |
+
args,
|
| 1120 |
+
unet=None,
|
| 1121 |
+
vae=vae,
|
| 1122 |
+
accelerator=accelerator,
|
| 1123 |
+
weight_dtype=weight_dtype,
|
| 1124 |
+
epoch=epoch,
|
| 1125 |
+
is_final_validation=True,
|
| 1126 |
+
)
|
| 1127 |
+
|
| 1128 |
+
if args.push_to_hub:
|
| 1129 |
+
upload_folder(
|
| 1130 |
+
repo_id=repo_id,
|
| 1131 |
+
folder_path=args.output_dir,
|
| 1132 |
+
commit_message="End of training",
|
| 1133 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1134 |
+
)
|
| 1135 |
+
|
| 1136 |
+
accelerator.end_training()
|
| 1137 |
+
|
| 1138 |
+
|
| 1139 |
+
if __name__ == "__main__":
|
| 1140 |
+
args = parse_args()
|
| 1141 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
This project has a new home now: [https://mapo-t2i.github.io/](https://mapo-t2i.github.io/). We formally studied the use of ORPO in the context of diffusion models and open-sourced our codebase, models, and datasets. We released our paper too!
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
datasets
|
| 2 |
+
accelerate
|
| 3 |
+
transformers
|
| 4 |
+
torchvision
|
| 5 |
+
wandb
|
| 6 |
+
peft
|
| 7 |
+
webdataset
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/train_diffusion_orpo_sdxl_lora.py
ADDED
|
@@ -0,0 +1,1093 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import contextlib
|
| 19 |
+
import io
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
import shutil
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
import torch.utils.checkpoint
|
| 31 |
+
import transformers
|
| 32 |
+
import wandb
|
| 33 |
+
from accelerate import Accelerator
|
| 34 |
+
from accelerate.logging import get_logger
|
| 35 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 36 |
+
from datasets import load_dataset
|
| 37 |
+
from huggingface_hub import create_repo, upload_folder
|
| 38 |
+
from packaging import version
|
| 39 |
+
from peft import LoraConfig, set_peft_model_state_dict
|
| 40 |
+
from peft.utils import get_peft_model_state_dict
|
| 41 |
+
from PIL import Image
|
| 42 |
+
from torchvision import transforms
|
| 43 |
+
from torchvision.transforms.functional import crop
|
| 44 |
+
from tqdm.auto import tqdm
|
| 45 |
+
from transformers import AutoTokenizer, PretrainedConfig
|
| 46 |
+
|
| 47 |
+
import diffusers
|
| 48 |
+
from diffusers import (
|
| 49 |
+
AutoencoderKL,
|
| 50 |
+
DDPMScheduler,
|
| 51 |
+
DiffusionPipeline,
|
| 52 |
+
UNet2DConditionModel,
|
| 53 |
+
)
|
| 54 |
+
from diffusers.loaders import StableDiffusionXLLoraLoaderMixin
|
| 55 |
+
from diffusers.optimization import get_scheduler
|
| 56 |
+
from diffusers.utils import check_min_version, convert_state_dict_to_diffusers, convert_unet_state_dict_to_peft
|
| 57 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 61 |
+
check_min_version("0.25.0.dev0")
|
| 62 |
+
|
| 63 |
+
logger = get_logger(__name__)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
VALIDATION_PROMPTS = [
|
| 67 |
+
"portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography",
|
| 68 |
+
"Self-portrait oil painting, a beautiful cyborg with golden hair, 8k",
|
| 69 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 70 |
+
"A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece",
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def import_model_class_from_model_name_or_path(
|
| 75 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 76 |
+
):
|
| 77 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 78 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 79 |
+
)
|
| 80 |
+
model_class = text_encoder_config.architectures[0]
|
| 81 |
+
|
| 82 |
+
if model_class == "CLIPTextModel":
|
| 83 |
+
from transformers import CLIPTextModel
|
| 84 |
+
|
| 85 |
+
return CLIPTextModel
|
| 86 |
+
elif model_class == "CLIPTextModelWithProjection":
|
| 87 |
+
from transformers import CLIPTextModelWithProjection
|
| 88 |
+
|
| 89 |
+
return CLIPTextModelWithProjection
|
| 90 |
+
else:
|
| 91 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def log_validation(args, unet, vae, accelerator, weight_dtype, epoch, is_final_validation=False):
|
| 95 |
+
logger.info(f"Running validation... \n Generating images with prompts:\n {VALIDATION_PROMPTS}.")
|
| 96 |
+
|
| 97 |
+
if is_final_validation:
|
| 98 |
+
if args.mixed_precision == "fp16":
|
| 99 |
+
vae.to(weight_dtype)
|
| 100 |
+
|
| 101 |
+
# create pipeline
|
| 102 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 103 |
+
args.pretrained_model_name_or_path,
|
| 104 |
+
vae=vae,
|
| 105 |
+
revision=args.revision,
|
| 106 |
+
variant=args.variant,
|
| 107 |
+
torch_dtype=weight_dtype,
|
| 108 |
+
)
|
| 109 |
+
if not is_final_validation:
|
| 110 |
+
pipeline.unet = accelerator.unwrap_model(unet)
|
| 111 |
+
else:
|
| 112 |
+
pipeline.load_lora_weights(args.output_dir, weight_name="pytorch_lora_weights.safetensors")
|
| 113 |
+
|
| 114 |
+
pipeline = pipeline.to(accelerator.device)
|
| 115 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 116 |
+
|
| 117 |
+
# run inference
|
| 118 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 119 |
+
images = []
|
| 120 |
+
context = contextlib.nullcontext() if is_final_validation else torch.cuda.amp.autocast()
|
| 121 |
+
|
| 122 |
+
guidance_scale = 5.0
|
| 123 |
+
num_inference_steps = 25
|
| 124 |
+
for prompt in VALIDATION_PROMPTS:
|
| 125 |
+
with context:
|
| 126 |
+
image = pipeline(
|
| 127 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 128 |
+
).images[0]
|
| 129 |
+
images.append(image)
|
| 130 |
+
|
| 131 |
+
tracker_key = "test" if is_final_validation else "validation"
|
| 132 |
+
for tracker in accelerator.trackers:
|
| 133 |
+
if tracker.name == "tensorboard":
|
| 134 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 135 |
+
tracker.writer.add_images(tracker_key, np_images, epoch, dataformats="NHWC")
|
| 136 |
+
if tracker.name == "wandb":
|
| 137 |
+
tracker.log(
|
| 138 |
+
{
|
| 139 |
+
tracker_key: [
|
| 140 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}") for i, image in enumerate(images)
|
| 141 |
+
]
|
| 142 |
+
}
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Also log images without the LoRA params for comparison.
|
| 146 |
+
if is_final_validation:
|
| 147 |
+
pipeline.disable_lora()
|
| 148 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 149 |
+
no_lora_images = [
|
| 150 |
+
pipeline(
|
| 151 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 152 |
+
).images[0]
|
| 153 |
+
for prompt in VALIDATION_PROMPTS
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
for tracker in accelerator.trackers:
|
| 157 |
+
if tracker.name == "tensorboard":
|
| 158 |
+
np_images = np.stack([np.asarray(img) for img in no_lora_images])
|
| 159 |
+
tracker.writer.add_images("test_without_lora", np_images, epoch, dataformats="NHWC")
|
| 160 |
+
if tracker.name == "wandb":
|
| 161 |
+
tracker.log(
|
| 162 |
+
{
|
| 163 |
+
"test_without_lora": [
|
| 164 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}")
|
| 165 |
+
for i, image in enumerate(no_lora_images)
|
| 166 |
+
]
|
| 167 |
+
}
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def parse_args(input_args=None):
|
| 172 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--pretrained_model_name_or_path",
|
| 175 |
+
type=str,
|
| 176 |
+
default=None,
|
| 177 |
+
required=True,
|
| 178 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--pretrained_vae_model_name_or_path",
|
| 182 |
+
type=str,
|
| 183 |
+
default=None,
|
| 184 |
+
help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--revision",
|
| 188 |
+
type=str,
|
| 189 |
+
default=None,
|
| 190 |
+
required=False,
|
| 191 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 192 |
+
)
|
| 193 |
+
parser.add_argument(
|
| 194 |
+
"--dataset_name",
|
| 195 |
+
type=str,
|
| 196 |
+
default=None,
|
| 197 |
+
help=(
|
| 198 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 199 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 200 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--dataset_split_name",
|
| 205 |
+
type=str,
|
| 206 |
+
default="validation",
|
| 207 |
+
help="Dataset split to be used during training. Helpful to specify for conducting experimental runs.",
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--variant",
|
| 211 |
+
type=str,
|
| 212 |
+
default=None,
|
| 213 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--run_validation",
|
| 217 |
+
default=False,
|
| 218 |
+
action="store_true",
|
| 219 |
+
help="Whether to run validation inference in between training and also after training. Helps to track progress.",
|
| 220 |
+
)
|
| 221 |
+
parser.add_argument(
|
| 222 |
+
"--validation_steps",
|
| 223 |
+
type=int,
|
| 224 |
+
default=200,
|
| 225 |
+
help="Run validation every X steps.",
|
| 226 |
+
)
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"--max_train_samples",
|
| 229 |
+
type=int,
|
| 230 |
+
default=None,
|
| 231 |
+
help=(
|
| 232 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 233 |
+
"value if set."
|
| 234 |
+
),
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--output_dir",
|
| 238 |
+
type=str,
|
| 239 |
+
default="diffusion-orpo-lora-sdxl",
|
| 240 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--cache_dir",
|
| 244 |
+
type=str,
|
| 245 |
+
default=None,
|
| 246 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 247 |
+
)
|
| 248 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 249 |
+
parser.add_argument(
|
| 250 |
+
"--resolution",
|
| 251 |
+
type=int,
|
| 252 |
+
default=1024,
|
| 253 |
+
help=(
|
| 254 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 255 |
+
" resolution"
|
| 256 |
+
),
|
| 257 |
+
)
|
| 258 |
+
parser.add_argument(
|
| 259 |
+
"--vae_encode_batch_size",
|
| 260 |
+
type=int,
|
| 261 |
+
default=8,
|
| 262 |
+
help="Batch size to use for VAE encoding of the images for efficient processing.",
|
| 263 |
+
)
|
| 264 |
+
parser.add_argument(
|
| 265 |
+
"--no_hflip",
|
| 266 |
+
action="store_true",
|
| 267 |
+
help="whether to randomly flip images horizontally",
|
| 268 |
+
)
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--random_crop",
|
| 271 |
+
default=False,
|
| 272 |
+
action="store_true",
|
| 273 |
+
help=(
|
| 274 |
+
"Whether to random crop the input images to the resolution. If not set, the images will be center-cropped."
|
| 275 |
+
),
|
| 276 |
+
)
|
| 277 |
+
parser.add_argument(
|
| 278 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 281 |
+
parser.add_argument(
|
| 282 |
+
"--max_train_steps",
|
| 283 |
+
type=int,
|
| 284 |
+
default=None,
|
| 285 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 286 |
+
)
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--checkpointing_steps",
|
| 289 |
+
type=int,
|
| 290 |
+
default=500,
|
| 291 |
+
help=(
|
| 292 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 293 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 294 |
+
" training using `--resume_from_checkpoint`."
|
| 295 |
+
),
|
| 296 |
+
)
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--checkpoints_total_limit",
|
| 299 |
+
type=int,
|
| 300 |
+
default=None,
|
| 301 |
+
help=("Max number of checkpoints to store."),
|
| 302 |
+
)
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--resume_from_checkpoint",
|
| 305 |
+
type=str,
|
| 306 |
+
default=None,
|
| 307 |
+
help=(
|
| 308 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 309 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 310 |
+
),
|
| 311 |
+
)
|
| 312 |
+
parser.add_argument(
|
| 313 |
+
"--gradient_accumulation_steps",
|
| 314 |
+
type=int,
|
| 315 |
+
default=1,
|
| 316 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 317 |
+
)
|
| 318 |
+
parser.add_argument(
|
| 319 |
+
"--gradient_checkpointing",
|
| 320 |
+
action="store_true",
|
| 321 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 322 |
+
)
|
| 323 |
+
parser.add_argument(
|
| 324 |
+
"--beta_orpo",
|
| 325 |
+
type=float,
|
| 326 |
+
default=0.1,
|
| 327 |
+
help="ORPO contribution factor.",
|
| 328 |
+
)
|
| 329 |
+
parser.add_argument(
|
| 330 |
+
"--learning_rate",
|
| 331 |
+
type=float,
|
| 332 |
+
default=5e-4,
|
| 333 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 334 |
+
)
|
| 335 |
+
parser.add_argument(
|
| 336 |
+
"--scale_lr",
|
| 337 |
+
action="store_true",
|
| 338 |
+
default=False,
|
| 339 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 340 |
+
)
|
| 341 |
+
parser.add_argument(
|
| 342 |
+
"--lr_scheduler",
|
| 343 |
+
type=str,
|
| 344 |
+
default="constant",
|
| 345 |
+
help=(
|
| 346 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 347 |
+
' "constant", "constant_with_warmup"]'
|
| 348 |
+
),
|
| 349 |
+
)
|
| 350 |
+
parser.add_argument(
|
| 351 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 352 |
+
)
|
| 353 |
+
parser.add_argument(
|
| 354 |
+
"--lr_num_cycles",
|
| 355 |
+
type=int,
|
| 356 |
+
default=1,
|
| 357 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 358 |
+
)
|
| 359 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 360 |
+
parser.add_argument(
|
| 361 |
+
"--dataloader_num_workers",
|
| 362 |
+
type=int,
|
| 363 |
+
default=0,
|
| 364 |
+
help=(
|
| 365 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 366 |
+
),
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 370 |
+
)
|
| 371 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 372 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 373 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 374 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 375 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 376 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 377 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 378 |
+
parser.add_argument(
|
| 379 |
+
"--hub_model_id",
|
| 380 |
+
type=str,
|
| 381 |
+
default=None,
|
| 382 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 383 |
+
)
|
| 384 |
+
parser.add_argument(
|
| 385 |
+
"--logging_dir",
|
| 386 |
+
type=str,
|
| 387 |
+
default="logs",
|
| 388 |
+
help=(
|
| 389 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 390 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 391 |
+
),
|
| 392 |
+
)
|
| 393 |
+
parser.add_argument(
|
| 394 |
+
"--allow_tf32",
|
| 395 |
+
action="store_true",
|
| 396 |
+
help=(
|
| 397 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 398 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 399 |
+
),
|
| 400 |
+
)
|
| 401 |
+
parser.add_argument(
|
| 402 |
+
"--report_to",
|
| 403 |
+
type=str,
|
| 404 |
+
default="tensorboard",
|
| 405 |
+
help=(
|
| 406 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 407 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 408 |
+
),
|
| 409 |
+
)
|
| 410 |
+
parser.add_argument(
|
| 411 |
+
"--mixed_precision",
|
| 412 |
+
type=str,
|
| 413 |
+
default=None,
|
| 414 |
+
choices=["no", "fp16", "bf16"],
|
| 415 |
+
help=(
|
| 416 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 417 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 418 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 419 |
+
),
|
| 420 |
+
)
|
| 421 |
+
parser.add_argument(
|
| 422 |
+
"--prior_generation_precision",
|
| 423 |
+
type=str,
|
| 424 |
+
default=None,
|
| 425 |
+
choices=["no", "fp32", "fp16", "bf16"],
|
| 426 |
+
help=(
|
| 427 |
+
"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 428 |
+
" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
|
| 429 |
+
),
|
| 430 |
+
)
|
| 431 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 432 |
+
parser.add_argument(
|
| 433 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 434 |
+
)
|
| 435 |
+
parser.add_argument(
|
| 436 |
+
"--rank",
|
| 437 |
+
type=int,
|
| 438 |
+
default=4,
|
| 439 |
+
help=("The dimension of the LoRA update matrices."),
|
| 440 |
+
)
|
| 441 |
+
parser.add_argument(
|
| 442 |
+
"--tracker_name",
|
| 443 |
+
type=str,
|
| 444 |
+
default="diffusion-orpo-lora-sdxl",
|
| 445 |
+
help=("The name of the tracker to report results to."),
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if input_args is not None:
|
| 449 |
+
args = parser.parse_args(input_args)
|
| 450 |
+
else:
|
| 451 |
+
args = parser.parse_args()
|
| 452 |
+
|
| 453 |
+
if args.dataset_name is None:
|
| 454 |
+
raise ValueError("Must provide a `dataset_name`.")
|
| 455 |
+
|
| 456 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 457 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 458 |
+
args.local_rank = env_local_rank
|
| 459 |
+
|
| 460 |
+
return args
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def tokenize_captions(tokenizers, examples):
|
| 464 |
+
captions = []
|
| 465 |
+
for caption in examples["caption"]:
|
| 466 |
+
captions.append(caption)
|
| 467 |
+
|
| 468 |
+
tokens_one = tokenizers[0](
|
| 469 |
+
captions, truncation=True, padding="max_length", max_length=tokenizers[0].model_max_length, return_tensors="pt"
|
| 470 |
+
).input_ids
|
| 471 |
+
tokens_two = tokenizers[1](
|
| 472 |
+
captions, truncation=True, padding="max_length", max_length=tokenizers[1].model_max_length, return_tensors="pt"
|
| 473 |
+
).input_ids
|
| 474 |
+
|
| 475 |
+
return tokens_one, tokens_two
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@torch.no_grad()
|
| 479 |
+
def encode_prompt(text_encoders, text_input_ids_list):
|
| 480 |
+
prompt_embeds_list = []
|
| 481 |
+
|
| 482 |
+
for i, text_encoder in enumerate(text_encoders):
|
| 483 |
+
text_input_ids = text_input_ids_list[i]
|
| 484 |
+
|
| 485 |
+
prompt_embeds = text_encoder(
|
| 486 |
+
text_input_ids.to(text_encoder.device),
|
| 487 |
+
output_hidden_states=True,
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 491 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
| 492 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 493 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 494 |
+
prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
|
| 495 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 496 |
+
|
| 497 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 498 |
+
pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
|
| 499 |
+
return prompt_embeds, pooled_prompt_embeds
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def main(args):
|
| 503 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 504 |
+
raise ValueError(
|
| 505 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 506 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 510 |
+
|
| 511 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 512 |
+
|
| 513 |
+
accelerator = Accelerator(
|
| 514 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 515 |
+
mixed_precision=args.mixed_precision,
|
| 516 |
+
log_with=args.report_to,
|
| 517 |
+
project_config=accelerator_project_config,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
# Disable AMP for MPS.
|
| 521 |
+
if torch.backends.mps.is_available():
|
| 522 |
+
accelerator.native_amp = False
|
| 523 |
+
|
| 524 |
+
# Make one log on every process with the configuration for debugging.
|
| 525 |
+
logging.basicConfig(
|
| 526 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 527 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 528 |
+
level=logging.INFO,
|
| 529 |
+
)
|
| 530 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 531 |
+
if accelerator.is_local_main_process:
|
| 532 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 533 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 534 |
+
else:
|
| 535 |
+
transformers.utils.logging.set_verbosity_error()
|
| 536 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 537 |
+
|
| 538 |
+
# If passed along, set the training seed now.
|
| 539 |
+
if args.seed is not None:
|
| 540 |
+
set_seed(args.seed)
|
| 541 |
+
|
| 542 |
+
# Handle the repository creation
|
| 543 |
+
if accelerator.is_main_process:
|
| 544 |
+
if args.output_dir is not None:
|
| 545 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 546 |
+
|
| 547 |
+
if args.push_to_hub:
|
| 548 |
+
repo_id = create_repo(
|
| 549 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 550 |
+
).repo_id
|
| 551 |
+
|
| 552 |
+
# Load the tokenizers
|
| 553 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 554 |
+
args.pretrained_model_name_or_path,
|
| 555 |
+
subfolder="tokenizer",
|
| 556 |
+
revision=args.revision,
|
| 557 |
+
use_fast=False,
|
| 558 |
+
)
|
| 559 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 560 |
+
args.pretrained_model_name_or_path,
|
| 561 |
+
subfolder="tokenizer_2",
|
| 562 |
+
revision=args.revision,
|
| 563 |
+
use_fast=False,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# import correct text encoder classes
|
| 567 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 568 |
+
args.pretrained_model_name_or_path, args.revision
|
| 569 |
+
)
|
| 570 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 571 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
# Load scheduler and models
|
| 575 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 576 |
+
|
| 577 |
+
text_encoder_one = text_encoder_cls_one.from_pretrained(
|
| 578 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 579 |
+
)
|
| 580 |
+
text_encoder_two = text_encoder_cls_two.from_pretrained(
|
| 581 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
| 582 |
+
)
|
| 583 |
+
vae_path = (
|
| 584 |
+
args.pretrained_model_name_or_path
|
| 585 |
+
if args.pretrained_vae_model_name_or_path is None
|
| 586 |
+
else args.pretrained_vae_model_name_or_path
|
| 587 |
+
)
|
| 588 |
+
vae = AutoencoderKL.from_pretrained(
|
| 589 |
+
vae_path,
|
| 590 |
+
subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
|
| 591 |
+
revision=args.revision,
|
| 592 |
+
variant=args.variant,
|
| 593 |
+
)
|
| 594 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 595 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
# We only train the additional adapter LoRA layers
|
| 599 |
+
vae.requires_grad_(False)
|
| 600 |
+
text_encoder_one.requires_grad_(False)
|
| 601 |
+
text_encoder_two.requires_grad_(False)
|
| 602 |
+
unet.requires_grad_(False)
|
| 603 |
+
|
| 604 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 605 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 606 |
+
weight_dtype = torch.float32
|
| 607 |
+
if accelerator.mixed_precision == "fp16":
|
| 608 |
+
weight_dtype = torch.float16
|
| 609 |
+
elif accelerator.mixed_precision == "bf16":
|
| 610 |
+
weight_dtype = torch.bfloat16
|
| 611 |
+
|
| 612 |
+
# Move unet and text_encoders to device and cast to weight_dtype
|
| 613 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 614 |
+
text_encoder_one.to(accelerator.device, dtype=weight_dtype)
|
| 615 |
+
text_encoder_two.to(accelerator.device, dtype=weight_dtype)
|
| 616 |
+
|
| 617 |
+
# The VAE is always in float32 to avoid NaN losses.
|
| 618 |
+
vae.to(accelerator.device, dtype=torch.float32)
|
| 619 |
+
|
| 620 |
+
# Set up LoRA.
|
| 621 |
+
unet_lora_config = LoraConfig(
|
| 622 |
+
r=args.rank,
|
| 623 |
+
lora_alpha=args.rank,
|
| 624 |
+
init_lora_weights="gaussian",
|
| 625 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 626 |
+
)
|
| 627 |
+
# Add adapter and make sure the trainable params are in float32.
|
| 628 |
+
unet.add_adapter(unet_lora_config)
|
| 629 |
+
if args.mixed_precision == "fp16":
|
| 630 |
+
for param in unet.parameters():
|
| 631 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 632 |
+
if param.requires_grad:
|
| 633 |
+
param.data = param.to(torch.float32)
|
| 634 |
+
|
| 635 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 636 |
+
if is_xformers_available():
|
| 637 |
+
import xformers
|
| 638 |
+
|
| 639 |
+
xformers_version = version.parse(xformers.__version__)
|
| 640 |
+
if xformers_version == version.parse("0.0.16"):
|
| 641 |
+
logger.warning(
|
| 642 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 643 |
+
)
|
| 644 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 645 |
+
else:
|
| 646 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 647 |
+
|
| 648 |
+
if args.gradient_checkpointing:
|
| 649 |
+
unet.enable_gradient_checkpointing()
|
| 650 |
+
|
| 651 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 652 |
+
def save_model_hook(models, weights, output_dir):
|
| 653 |
+
if accelerator.is_main_process:
|
| 654 |
+
# there are only two options here. Either are just the unet attn processor layers
|
| 655 |
+
# or there are the unet and text encoder atten layers
|
| 656 |
+
unet_lora_layers_to_save = None
|
| 657 |
+
|
| 658 |
+
for model in models:
|
| 659 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 660 |
+
unet_lora_layers_to_save = convert_state_dict_to_diffusers(get_peft_model_state_dict(model))
|
| 661 |
+
else:
|
| 662 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 663 |
+
|
| 664 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 665 |
+
weights.pop()
|
| 666 |
+
|
| 667 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(
|
| 668 |
+
output_dir,
|
| 669 |
+
unet_lora_layers=unet_lora_layers_to_save,
|
| 670 |
+
text_encoder_lora_layers=None,
|
| 671 |
+
text_encoder_2_lora_layers=None,
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
def load_model_hook(models, input_dir):
|
| 675 |
+
unet_ = None
|
| 676 |
+
|
| 677 |
+
while len(models) > 0:
|
| 678 |
+
model = models.pop()
|
| 679 |
+
|
| 680 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 681 |
+
unet_ = model
|
| 682 |
+
else:
|
| 683 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 684 |
+
|
| 685 |
+
lora_state_dict, network_alphas = StableDiffusionXLLoraLoaderMixin.lora_state_dict(input_dir)
|
| 686 |
+
|
| 687 |
+
unet_state_dict = {f"{k.replace('unet.', '')}": v for k, v in lora_state_dict.items() if k.startswith("unet.")}
|
| 688 |
+
unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
|
| 689 |
+
incompatible_keys = set_peft_model_state_dict(unet_, unet_state_dict, adapter_name="default")
|
| 690 |
+
if incompatible_keys is not None:
|
| 691 |
+
# check only for unexpected keys
|
| 692 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 693 |
+
if unexpected_keys:
|
| 694 |
+
logger.warning(
|
| 695 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 696 |
+
f" {unexpected_keys}. "
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 700 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 701 |
+
|
| 702 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 703 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 704 |
+
if args.allow_tf32:
|
| 705 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 706 |
+
|
| 707 |
+
if args.scale_lr:
|
| 708 |
+
args.learning_rate = (
|
| 709 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 713 |
+
if args.use_8bit_adam:
|
| 714 |
+
try:
|
| 715 |
+
import bitsandbytes as bnb
|
| 716 |
+
except ImportError:
|
| 717 |
+
raise ImportError(
|
| 718 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 722 |
+
else:
|
| 723 |
+
optimizer_class = torch.optim.AdamW
|
| 724 |
+
|
| 725 |
+
# Optimizer creation
|
| 726 |
+
params_to_optimize = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 727 |
+
optimizer = optimizer_class(
|
| 728 |
+
params_to_optimize,
|
| 729 |
+
lr=args.learning_rate,
|
| 730 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 731 |
+
weight_decay=args.adam_weight_decay,
|
| 732 |
+
eps=args.adam_epsilon,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# Dataset and DataLoaders creation:
|
| 736 |
+
train_dataset = load_dataset(
|
| 737 |
+
args.dataset_name,
|
| 738 |
+
cache_dir=args.cache_dir,
|
| 739 |
+
split=args.dataset_split_name,
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
# Preprocessing the datasets.
|
| 743 |
+
train_resize = transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 744 |
+
train_crop = transforms.RandomCrop(args.resolution) if args.random_crop else transforms.CenterCrop(args.resolution)
|
| 745 |
+
train_flip = transforms.RandomHorizontalFlip(p=1.0)
|
| 746 |
+
to_tensor = transforms.ToTensor()
|
| 747 |
+
normalize = transforms.Normalize([0.5], [0.5])
|
| 748 |
+
|
| 749 |
+
def preprocess_train(examples):
|
| 750 |
+
all_pixel_values = []
|
| 751 |
+
images = [Image.open(io.BytesIO(im_bytes)).convert("RGB") for im_bytes in examples["jpg_0"]]
|
| 752 |
+
original_sizes = [(image.height, image.width) for image in images]
|
| 753 |
+
crop_top_lefts = []
|
| 754 |
+
|
| 755 |
+
for col_name in ["jpg_0", "jpg_1"]:
|
| 756 |
+
images = [Image.open(io.BytesIO(im_bytes)).convert("RGB") for im_bytes in examples[col_name]]
|
| 757 |
+
if col_name == "jpg_1":
|
| 758 |
+
# Need to bring down the image to the same resolution.
|
| 759 |
+
# This seems like the simplest reasonable approach.
|
| 760 |
+
# "::-1" because PIL resize takes (width, height).
|
| 761 |
+
images = [image.resize(original_sizes[i][::-1]) for i, image in enumerate(images)]
|
| 762 |
+
pixel_values = [to_tensor(image) for image in images]
|
| 763 |
+
all_pixel_values.append(pixel_values)
|
| 764 |
+
|
| 765 |
+
# Double on channel dim, jpg_y then jpg_w
|
| 766 |
+
im_tup_iterator = zip(*all_pixel_values)
|
| 767 |
+
combined_pixel_values = []
|
| 768 |
+
for im_tup, label_0 in zip(im_tup_iterator, examples["label_0"]):
|
| 769 |
+
# We randomize selection and rejection.
|
| 770 |
+
if label_0 == 0.5:
|
| 771 |
+
if random.random() < 0.5:
|
| 772 |
+
label_0 = 0
|
| 773 |
+
else:
|
| 774 |
+
label_0 = 1
|
| 775 |
+
|
| 776 |
+
if label_0 == 0:
|
| 777 |
+
im_tup = im_tup[::-1]
|
| 778 |
+
|
| 779 |
+
combined_im = torch.cat(im_tup, dim=0) # no batch dim
|
| 780 |
+
|
| 781 |
+
# Resize.
|
| 782 |
+
combined_im = train_resize(combined_im)
|
| 783 |
+
|
| 784 |
+
# Flipping.
|
| 785 |
+
if not args.no_hflip and random.random() < 0.5:
|
| 786 |
+
combined_im = train_flip(combined_im)
|
| 787 |
+
|
| 788 |
+
# Cropping.
|
| 789 |
+
if not args.random_crop:
|
| 790 |
+
y1 = max(0, int(round((combined_im.shape[1] - args.resolution) / 2.0)))
|
| 791 |
+
x1 = max(0, int(round((combined_im.shape[2] - args.resolution) / 2.0)))
|
| 792 |
+
combined_im = train_crop(combined_im)
|
| 793 |
+
else:
|
| 794 |
+
y1, x1, h, w = train_crop.get_params(combined_im, (args.resolution, args.resolution))
|
| 795 |
+
combined_im = crop(combined_im, y1, x1, h, w)
|
| 796 |
+
|
| 797 |
+
crop_top_left = (y1, x1)
|
| 798 |
+
crop_top_lefts.append(crop_top_left)
|
| 799 |
+
combined_im = normalize(combined_im)
|
| 800 |
+
combined_pixel_values.append(combined_im)
|
| 801 |
+
|
| 802 |
+
examples["pixel_values"] = combined_pixel_values
|
| 803 |
+
examples["original_sizes"] = original_sizes
|
| 804 |
+
examples["crop_top_lefts"] = crop_top_lefts
|
| 805 |
+
tokens_one, tokens_two = tokenize_captions([tokenizer_one, tokenizer_two], examples)
|
| 806 |
+
examples["input_ids_one"] = tokens_one
|
| 807 |
+
examples["input_ids_two"] = tokens_two
|
| 808 |
+
return examples
|
| 809 |
+
|
| 810 |
+
with accelerator.main_process_first():
|
| 811 |
+
if args.max_train_samples is not None:
|
| 812 |
+
train_dataset = train_dataset.shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 813 |
+
# Set the training transforms
|
| 814 |
+
train_dataset = train_dataset.with_transform(preprocess_train)
|
| 815 |
+
|
| 816 |
+
def collate_fn(examples):
|
| 817 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 818 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 819 |
+
original_sizes = [example["original_sizes"] for example in examples]
|
| 820 |
+
crop_top_lefts = [example["crop_top_lefts"] for example in examples]
|
| 821 |
+
input_ids_one = torch.stack([example["input_ids_one"] for example in examples])
|
| 822 |
+
input_ids_two = torch.stack([example["input_ids_two"] for example in examples])
|
| 823 |
+
|
| 824 |
+
return {
|
| 825 |
+
"pixel_values": pixel_values,
|
| 826 |
+
"input_ids_one": input_ids_one,
|
| 827 |
+
"input_ids_two": input_ids_two,
|
| 828 |
+
"original_sizes": original_sizes,
|
| 829 |
+
"crop_top_lefts": crop_top_lefts,
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 833 |
+
train_dataset,
|
| 834 |
+
batch_size=args.train_batch_size,
|
| 835 |
+
shuffle=True,
|
| 836 |
+
collate_fn=collate_fn,
|
| 837 |
+
num_workers=args.dataloader_num_workers,
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
# Scheduler and math around the number of training steps.
|
| 841 |
+
overrode_max_train_steps = False
|
| 842 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 843 |
+
if args.max_train_steps is None:
|
| 844 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 845 |
+
overrode_max_train_steps = True
|
| 846 |
+
|
| 847 |
+
lr_scheduler = get_scheduler(
|
| 848 |
+
args.lr_scheduler,
|
| 849 |
+
optimizer=optimizer,
|
| 850 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 851 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 852 |
+
num_cycles=args.lr_num_cycles,
|
| 853 |
+
power=args.lr_power,
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 857 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 861 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 862 |
+
if overrode_max_train_steps:
|
| 863 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 864 |
+
# Afterwards we recalculate our number of training epochs
|
| 865 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 866 |
+
|
| 867 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 868 |
+
# The trackers initializes automatically on the main process.
|
| 869 |
+
if accelerator.is_main_process:
|
| 870 |
+
accelerator.init_trackers(args.tracker_name, config=vars(args))
|
| 871 |
+
|
| 872 |
+
# Train!
|
| 873 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 874 |
+
|
| 875 |
+
logger.info("***** Running training *****")
|
| 876 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 877 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 878 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 879 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 880 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 881 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 882 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 883 |
+
global_step = 0
|
| 884 |
+
first_epoch = 0
|
| 885 |
+
|
| 886 |
+
# Potentially load in the weights and states from a previous save
|
| 887 |
+
if args.resume_from_checkpoint:
|
| 888 |
+
if args.resume_from_checkpoint != "latest":
|
| 889 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 890 |
+
else:
|
| 891 |
+
# Get the mos recent checkpoint
|
| 892 |
+
dirs = os.listdir(args.output_dir)
|
| 893 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 894 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 895 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 896 |
+
|
| 897 |
+
if path is None:
|
| 898 |
+
accelerator.print(
|
| 899 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 900 |
+
)
|
| 901 |
+
args.resume_from_checkpoint = None
|
| 902 |
+
initial_global_step = 0
|
| 903 |
+
else:
|
| 904 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 905 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 906 |
+
global_step = int(path.split("-")[1])
|
| 907 |
+
|
| 908 |
+
initial_global_step = global_step
|
| 909 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 910 |
+
else:
|
| 911 |
+
initial_global_step = 0
|
| 912 |
+
|
| 913 |
+
progress_bar = tqdm(
|
| 914 |
+
range(0, args.max_train_steps),
|
| 915 |
+
initial=initial_global_step,
|
| 916 |
+
desc="Steps",
|
| 917 |
+
# Only show the progress bar once on each machine.
|
| 918 |
+
disable=not accelerator.is_local_main_process,
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
unet.train()
|
| 922 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 923 |
+
for step, batch in enumerate(train_dataloader):
|
| 924 |
+
with accelerator.accumulate(unet):
|
| 925 |
+
# (batch_size, 2*channels, h, w) -> (2*batch_size, channels, h, w)
|
| 926 |
+
pixel_values = batch["pixel_values"].to(dtype=vae.dtype)
|
| 927 |
+
feed_pixel_values = torch.cat(pixel_values.chunk(2, dim=1))
|
| 928 |
+
|
| 929 |
+
latents = []
|
| 930 |
+
for i in range(0, feed_pixel_values.shape[0], args.vae_encode_batch_size):
|
| 931 |
+
latents.append(
|
| 932 |
+
vae.encode(feed_pixel_values[i : i + args.vae_encode_batch_size]).latent_dist.sample()
|
| 933 |
+
)
|
| 934 |
+
latents = torch.cat(latents, dim=0)
|
| 935 |
+
latents = latents * vae.config.scaling_factor
|
| 936 |
+
if args.pretrained_vae_model_name_or_path is None:
|
| 937 |
+
latents = latents.to(weight_dtype)
|
| 938 |
+
|
| 939 |
+
# Sample noise that we'll add to the latents
|
| 940 |
+
noise = torch.randn_like(latents).chunk(2)[0].repeat(2, 1, 1, 1)
|
| 941 |
+
|
| 942 |
+
# Sample a random timestep for each image
|
| 943 |
+
bsz = latents.shape[0] // 2
|
| 944 |
+
timesteps = torch.randint(
|
| 945 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device, dtype=torch.long
|
| 946 |
+
).repeat(2)
|
| 947 |
+
|
| 948 |
+
# Add noise to the model input according to the noise magnitude at each timestep
|
| 949 |
+
# (this is the forward diffusion process)
|
| 950 |
+
noisy_model_input = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 951 |
+
|
| 952 |
+
# time ids
|
| 953 |
+
def compute_time_ids(original_size, crops_coords_top_left):
|
| 954 |
+
# Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
|
| 955 |
+
target_size = (args.resolution, args.resolution)
|
| 956 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 957 |
+
add_time_ids = torch.tensor([add_time_ids])
|
| 958 |
+
add_time_ids = add_time_ids.to(accelerator.device, dtype=weight_dtype)
|
| 959 |
+
return add_time_ids
|
| 960 |
+
|
| 961 |
+
add_time_ids = torch.cat(
|
| 962 |
+
[compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
|
| 963 |
+
).repeat(2, 1)
|
| 964 |
+
|
| 965 |
+
# Get the text embedding for conditioning
|
| 966 |
+
prompt_embeds, pooled_prompt_embeds = encode_prompt(
|
| 967 |
+
[text_encoder_one, text_encoder_two], [batch["input_ids_one"], batch["input_ids_two"]]
|
| 968 |
+
)
|
| 969 |
+
prompt_embeds = prompt_embeds.repeat(2, 1, 1)
|
| 970 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(2, 1)
|
| 971 |
+
|
| 972 |
+
# Predict the noise residual
|
| 973 |
+
model_pred = unet(
|
| 974 |
+
noisy_model_input,
|
| 975 |
+
timesteps,
|
| 976 |
+
prompt_embeds,
|
| 977 |
+
added_cond_kwargs={"time_ids": add_time_ids, "text_embeds": pooled_prompt_embeds},
|
| 978 |
+
).sample
|
| 979 |
+
|
| 980 |
+
# Get the target for loss depending on the prediction type
|
| 981 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 982 |
+
target = noise
|
| 983 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 984 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 985 |
+
else:
|
| 986 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 987 |
+
|
| 988 |
+
# ODDS ratio loss.
|
| 989 |
+
# In the diffusion formulation, we're assuming that the MSE loss
|
| 990 |
+
# approximates the logp.
|
| 991 |
+
model_losses = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
| 992 |
+
model_losses = model_losses.mean(dim=list(range(1, len(model_losses.shape))))
|
| 993 |
+
model_losses_w, model_losses_l = model_losses.chunk(2)
|
| 994 |
+
log_odds = model_losses_w - model_losses_l
|
| 995 |
+
|
| 996 |
+
# Ratio loss.
|
| 997 |
+
ratio = F.logsigmoid(log_odds)
|
| 998 |
+
ratio_losses = args.beta_orpo * ratio
|
| 999 |
+
|
| 1000 |
+
# Full ORPO loss
|
| 1001 |
+
loss = model_losses_w.mean() - ratio_losses.mean()
|
| 1002 |
+
|
| 1003 |
+
# Backprop.
|
| 1004 |
+
accelerator.backward(loss)
|
| 1005 |
+
if accelerator.sync_gradients:
|
| 1006 |
+
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
|
| 1007 |
+
optimizer.step()
|
| 1008 |
+
lr_scheduler.step()
|
| 1009 |
+
optimizer.zero_grad()
|
| 1010 |
+
|
| 1011 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1012 |
+
if accelerator.sync_gradients:
|
| 1013 |
+
progress_bar.update(1)
|
| 1014 |
+
global_step += 1
|
| 1015 |
+
|
| 1016 |
+
if accelerator.is_main_process:
|
| 1017 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1018 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1019 |
+
if args.checkpoints_total_limit is not None:
|
| 1020 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1021 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1022 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1023 |
+
|
| 1024 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1025 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1026 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1027 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1028 |
+
|
| 1029 |
+
logger.info(
|
| 1030 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1031 |
+
)
|
| 1032 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1033 |
+
|
| 1034 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1035 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1036 |
+
shutil.rmtree(removing_checkpoint)
|
| 1037 |
+
|
| 1038 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1039 |
+
accelerator.save_state(save_path)
|
| 1040 |
+
logger.info(f"Saved state to {save_path}")
|
| 1041 |
+
|
| 1042 |
+
if args.run_validation and global_step % args.validation_steps == 0:
|
| 1043 |
+
log_validation(
|
| 1044 |
+
args, unet=unet, vae=vae, accelerator=accelerator, weight_dtype=weight_dtype, epoch=epoch
|
| 1045 |
+
)
|
| 1046 |
+
|
| 1047 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1048 |
+
progress_bar.set_postfix(**logs)
|
| 1049 |
+
accelerator.log(logs, step=global_step)
|
| 1050 |
+
|
| 1051 |
+
if global_step >= args.max_train_steps:
|
| 1052 |
+
break
|
| 1053 |
+
|
| 1054 |
+
# Save the lora layers
|
| 1055 |
+
accelerator.wait_for_everyone()
|
| 1056 |
+
if accelerator.is_main_process:
|
| 1057 |
+
unet = accelerator.unwrap_model(unet)
|
| 1058 |
+
unet = unet.to(torch.float32)
|
| 1059 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
|
| 1060 |
+
|
| 1061 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(
|
| 1062 |
+
save_directory=args.output_dir,
|
| 1063 |
+
unet_lora_layers=unet_lora_state_dict,
|
| 1064 |
+
text_encoder_lora_layers=None,
|
| 1065 |
+
text_encoder_2_lora_layers=None,
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
# Final validation?
|
| 1069 |
+
if args.run_validation:
|
| 1070 |
+
log_validation(
|
| 1071 |
+
args,
|
| 1072 |
+
unet=None,
|
| 1073 |
+
vae=vae,
|
| 1074 |
+
accelerator=accelerator,
|
| 1075 |
+
weight_dtype=weight_dtype,
|
| 1076 |
+
epoch=epoch,
|
| 1077 |
+
is_final_validation=True,
|
| 1078 |
+
)
|
| 1079 |
+
|
| 1080 |
+
if args.push_to_hub:
|
| 1081 |
+
upload_folder(
|
| 1082 |
+
repo_id=repo_id,
|
| 1083 |
+
folder_path=args.output_dir,
|
| 1084 |
+
commit_message="End of training",
|
| 1085 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1086 |
+
)
|
| 1087 |
+
|
| 1088 |
+
accelerator.end_training()
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
if __name__ == "__main__":
|
| 1092 |
+
args = parse_args()
|
| 1093 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/diffusion_orpo/train_diffusion_orpo_sdxl_lora_wds.py
ADDED
|
@@ -0,0 +1,1096 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import contextlib
|
| 19 |
+
import logging
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import random
|
| 23 |
+
import shutil
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
import transformers
|
| 31 |
+
import wandb
|
| 32 |
+
import webdataset as wds
|
| 33 |
+
from accelerate import Accelerator
|
| 34 |
+
from accelerate.logging import get_logger
|
| 35 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 36 |
+
from huggingface_hub import create_repo, upload_folder
|
| 37 |
+
from packaging import version
|
| 38 |
+
from peft import LoraConfig, set_peft_model_state_dict
|
| 39 |
+
from peft.utils import get_peft_model_state_dict
|
| 40 |
+
from torchvision import transforms
|
| 41 |
+
from torchvision.transforms.functional import crop
|
| 42 |
+
from tqdm.auto import tqdm
|
| 43 |
+
from transformers import AutoTokenizer, PretrainedConfig
|
| 44 |
+
|
| 45 |
+
import diffusers
|
| 46 |
+
from diffusers import (
|
| 47 |
+
AutoencoderKL,
|
| 48 |
+
DDPMScheduler,
|
| 49 |
+
DiffusionPipeline,
|
| 50 |
+
UNet2DConditionModel,
|
| 51 |
+
)
|
| 52 |
+
from diffusers.loaders import StableDiffusionXLLoraLoaderMixin
|
| 53 |
+
from diffusers.optimization import get_scheduler
|
| 54 |
+
from diffusers.utils import check_min_version, convert_state_dict_to_diffusers, convert_unet_state_dict_to_peft
|
| 55 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 59 |
+
check_min_version("0.25.0.dev0")
|
| 60 |
+
|
| 61 |
+
logger = get_logger(__name__)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
VALIDATION_PROMPTS = [
|
| 65 |
+
"portrait photo of a girl, photograph, highly detailed face, depth of field, moody light, golden hour, style by Dan Winters, Russell James, Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography",
|
| 66 |
+
"Self-portrait oil painting, a beautiful cyborg with golden hair, 8k",
|
| 67 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 68 |
+
"A photo of beautiful mountain with realistic sunset and blue lake, highly detailed, masterpiece",
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def import_model_class_from_model_name_or_path(
|
| 73 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 74 |
+
):
|
| 75 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 76 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 77 |
+
)
|
| 78 |
+
model_class = text_encoder_config.architectures[0]
|
| 79 |
+
|
| 80 |
+
if model_class == "CLIPTextModel":
|
| 81 |
+
from transformers import CLIPTextModel
|
| 82 |
+
|
| 83 |
+
return CLIPTextModel
|
| 84 |
+
elif model_class == "CLIPTextModelWithProjection":
|
| 85 |
+
from transformers import CLIPTextModelWithProjection
|
| 86 |
+
|
| 87 |
+
return CLIPTextModelWithProjection
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def log_validation(args, unet, vae, accelerator, weight_dtype, epoch, is_final_validation=False):
|
| 93 |
+
logger.info(f"Running validation... \n Generating images with prompts:\n {VALIDATION_PROMPTS}.")
|
| 94 |
+
|
| 95 |
+
if is_final_validation:
|
| 96 |
+
if args.mixed_precision == "fp16":
|
| 97 |
+
vae.to(weight_dtype)
|
| 98 |
+
|
| 99 |
+
# create pipeline
|
| 100 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 101 |
+
args.pretrained_model_name_or_path,
|
| 102 |
+
vae=vae,
|
| 103 |
+
revision=args.revision,
|
| 104 |
+
variant=args.variant,
|
| 105 |
+
torch_dtype=weight_dtype,
|
| 106 |
+
)
|
| 107 |
+
if not is_final_validation:
|
| 108 |
+
pipeline.unet = accelerator.unwrap_model(unet)
|
| 109 |
+
else:
|
| 110 |
+
pipeline.load_lora_weights(args.output_dir, weight_name="pytorch_lora_weights.safetensors")
|
| 111 |
+
|
| 112 |
+
pipeline = pipeline.to(accelerator.device)
|
| 113 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 114 |
+
|
| 115 |
+
# run inference
|
| 116 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 117 |
+
images = []
|
| 118 |
+
context = contextlib.nullcontext() if is_final_validation else torch.cuda.amp.autocast()
|
| 119 |
+
|
| 120 |
+
guidance_scale = 5.0
|
| 121 |
+
num_inference_steps = 25
|
| 122 |
+
for prompt in VALIDATION_PROMPTS:
|
| 123 |
+
with context:
|
| 124 |
+
image = pipeline(
|
| 125 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 126 |
+
).images[0]
|
| 127 |
+
images.append(image)
|
| 128 |
+
|
| 129 |
+
tracker_key = "test" if is_final_validation else "validation"
|
| 130 |
+
for tracker in accelerator.trackers:
|
| 131 |
+
if tracker.name == "tensorboard":
|
| 132 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 133 |
+
tracker.writer.add_images(tracker_key, np_images, epoch, dataformats="NHWC")
|
| 134 |
+
if tracker.name == "wandb":
|
| 135 |
+
tracker.log(
|
| 136 |
+
{
|
| 137 |
+
tracker_key: [
|
| 138 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}") for i, image in enumerate(images)
|
| 139 |
+
]
|
| 140 |
+
}
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# Also log images without the LoRA params for comparison.
|
| 144 |
+
if is_final_validation:
|
| 145 |
+
pipeline.disable_lora()
|
| 146 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed) if args.seed else None
|
| 147 |
+
no_lora_images = [
|
| 148 |
+
pipeline(
|
| 149 |
+
prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=generator
|
| 150 |
+
).images[0]
|
| 151 |
+
for prompt in VALIDATION_PROMPTS
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
for tracker in accelerator.trackers:
|
| 155 |
+
if tracker.name == "tensorboard":
|
| 156 |
+
np_images = np.stack([np.asarray(img) for img in no_lora_images])
|
| 157 |
+
tracker.writer.add_images("test_without_lora", np_images, epoch, dataformats="NHWC")
|
| 158 |
+
if tracker.name == "wandb":
|
| 159 |
+
tracker.log(
|
| 160 |
+
{
|
| 161 |
+
"test_without_lora": [
|
| 162 |
+
wandb.Image(image, caption=f"{i}: {VALIDATION_PROMPTS[i]}")
|
| 163 |
+
for i, image in enumerate(no_lora_images)
|
| 164 |
+
]
|
| 165 |
+
}
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def parse_args(input_args=None):
|
| 170 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--pretrained_model_name_or_path",
|
| 173 |
+
type=str,
|
| 174 |
+
default=None,
|
| 175 |
+
required=True,
|
| 176 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 177 |
+
)
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--pretrained_vae_model_name_or_path",
|
| 180 |
+
type=str,
|
| 181 |
+
default=None,
|
| 182 |
+
help="Path to pretrained VAE model with better numerical stability. More details: https://github.com/huggingface/diffusers/pull/4038.",
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--revision",
|
| 186 |
+
type=str,
|
| 187 |
+
default=None,
|
| 188 |
+
required=False,
|
| 189 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 190 |
+
)
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--dataset_path",
|
| 193 |
+
type=str,
|
| 194 |
+
default="pipe:aws s3 cp s3://diffusion-preference-opt/{00000..00644}.tar -",
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--num_train_examples",
|
| 198 |
+
type=int,
|
| 199 |
+
default=1001352,
|
| 200 |
+
)
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--variant",
|
| 203 |
+
type=str,
|
| 204 |
+
default=None,
|
| 205 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 206 |
+
)
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--run_validation",
|
| 209 |
+
default=False,
|
| 210 |
+
action="store_true",
|
| 211 |
+
help="Whether to run validation inference in between training and also after training. Helps to track progress.",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--validation_steps",
|
| 215 |
+
type=int,
|
| 216 |
+
default=200,
|
| 217 |
+
help="Run validation every X steps.",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--output_dir",
|
| 221 |
+
type=str,
|
| 222 |
+
default="diffusion-orpo-lora-sdxl",
|
| 223 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--cache_dir",
|
| 227 |
+
type=str,
|
| 228 |
+
default=None,
|
| 229 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 230 |
+
)
|
| 231 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--resolution",
|
| 234 |
+
type=int,
|
| 235 |
+
default=1024,
|
| 236 |
+
help=(
|
| 237 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 238 |
+
" resolution"
|
| 239 |
+
),
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--vae_encode_batch_size",
|
| 243 |
+
type=int,
|
| 244 |
+
default=8,
|
| 245 |
+
help="Batch size to use for VAE encoding of the images for efficient processing.",
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--no_hflip",
|
| 249 |
+
action="store_true",
|
| 250 |
+
help="whether to randomly flip images horizontally",
|
| 251 |
+
)
|
| 252 |
+
parser.add_argument(
|
| 253 |
+
"--random_crop",
|
| 254 |
+
default=False,
|
| 255 |
+
action="store_true",
|
| 256 |
+
help=(
|
| 257 |
+
"Whether to random crop the input images to the resolution. If not set, the images will be center-cropped."
|
| 258 |
+
),
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument("--global_batch_size", type=int, default=64, help="Total batch size.")
|
| 261 |
+
parser.add_argument(
|
| 262 |
+
"--per_gpu_batch_size", type=int, default=8, help="Number of samples in a batch for a single GPU."
|
| 263 |
+
)
|
| 264 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--max_train_steps",
|
| 267 |
+
type=int,
|
| 268 |
+
default=None,
|
| 269 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--checkpointing_steps",
|
| 273 |
+
type=int,
|
| 274 |
+
default=500,
|
| 275 |
+
help=(
|
| 276 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 277 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 278 |
+
" training using `--resume_from_checkpoint`."
|
| 279 |
+
),
|
| 280 |
+
)
|
| 281 |
+
parser.add_argument(
|
| 282 |
+
"--checkpoints_total_limit",
|
| 283 |
+
type=int,
|
| 284 |
+
default=None,
|
| 285 |
+
help=("Max number of checkpoints to store."),
|
| 286 |
+
)
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--resume_from_checkpoint",
|
| 289 |
+
type=str,
|
| 290 |
+
default=None,
|
| 291 |
+
help=(
|
| 292 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 293 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 294 |
+
),
|
| 295 |
+
)
|
| 296 |
+
parser.add_argument(
|
| 297 |
+
"--gradient_accumulation_steps",
|
| 298 |
+
type=int,
|
| 299 |
+
default=1,
|
| 300 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 301 |
+
)
|
| 302 |
+
parser.add_argument(
|
| 303 |
+
"--gradient_checkpointing",
|
| 304 |
+
action="store_true",
|
| 305 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 306 |
+
)
|
| 307 |
+
parser.add_argument(
|
| 308 |
+
"--beta_orpo",
|
| 309 |
+
type=float,
|
| 310 |
+
default=0.1,
|
| 311 |
+
help="ORPO contribution factor.",
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument(
|
| 314 |
+
"--learning_rate",
|
| 315 |
+
type=float,
|
| 316 |
+
default=5e-4,
|
| 317 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 318 |
+
)
|
| 319 |
+
parser.add_argument(
|
| 320 |
+
"--scale_lr",
|
| 321 |
+
action="store_true",
|
| 322 |
+
default=False,
|
| 323 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 324 |
+
)
|
| 325 |
+
parser.add_argument(
|
| 326 |
+
"--lr_scheduler",
|
| 327 |
+
type=str,
|
| 328 |
+
default="constant",
|
| 329 |
+
help=(
|
| 330 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 331 |
+
' "constant", "constant_with_warmup"]'
|
| 332 |
+
),
|
| 333 |
+
)
|
| 334 |
+
parser.add_argument(
|
| 335 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--lr_num_cycles",
|
| 339 |
+
type=int,
|
| 340 |
+
default=1,
|
| 341 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 342 |
+
)
|
| 343 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 344 |
+
parser.add_argument(
|
| 345 |
+
"--dataloader_num_workers",
|
| 346 |
+
type=int,
|
| 347 |
+
default=0,
|
| 348 |
+
help=(
|
| 349 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 350 |
+
),
|
| 351 |
+
)
|
| 352 |
+
parser.add_argument(
|
| 353 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 354 |
+
)
|
| 355 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 356 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 357 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 358 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 359 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 360 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 361 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--hub_model_id",
|
| 364 |
+
type=str,
|
| 365 |
+
default=None,
|
| 366 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--logging_dir",
|
| 370 |
+
type=str,
|
| 371 |
+
default="logs",
|
| 372 |
+
help=(
|
| 373 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 374 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 375 |
+
),
|
| 376 |
+
)
|
| 377 |
+
parser.add_argument(
|
| 378 |
+
"--allow_tf32",
|
| 379 |
+
action="store_true",
|
| 380 |
+
help=(
|
| 381 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 382 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 383 |
+
),
|
| 384 |
+
)
|
| 385 |
+
parser.add_argument(
|
| 386 |
+
"--report_to",
|
| 387 |
+
type=str,
|
| 388 |
+
default="tensorboard",
|
| 389 |
+
help=(
|
| 390 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 391 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 392 |
+
),
|
| 393 |
+
)
|
| 394 |
+
parser.add_argument(
|
| 395 |
+
"--mixed_precision",
|
| 396 |
+
type=str,
|
| 397 |
+
default=None,
|
| 398 |
+
choices=["no", "fp16", "bf16"],
|
| 399 |
+
help=(
|
| 400 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 401 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 402 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 403 |
+
),
|
| 404 |
+
)
|
| 405 |
+
parser.add_argument(
|
| 406 |
+
"--prior_generation_precision",
|
| 407 |
+
type=str,
|
| 408 |
+
default=None,
|
| 409 |
+
choices=["no", "fp32", "fp16", "bf16"],
|
| 410 |
+
help=(
|
| 411 |
+
"Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 412 |
+
" 1.10.and an Nvidia Ampere GPU. Default to fp16 if a GPU is available else fp32."
|
| 413 |
+
),
|
| 414 |
+
)
|
| 415 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 416 |
+
parser.add_argument(
|
| 417 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 418 |
+
)
|
| 419 |
+
parser.add_argument(
|
| 420 |
+
"--rank",
|
| 421 |
+
type=int,
|
| 422 |
+
default=4,
|
| 423 |
+
help=("The dimension of the LoRA update matrices."),
|
| 424 |
+
)
|
| 425 |
+
parser.add_argument(
|
| 426 |
+
"--tracker_name",
|
| 427 |
+
type=str,
|
| 428 |
+
default="diffusion-orpo-lora-sdxl",
|
| 429 |
+
help=("The name of the tracker to report results to."),
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
if input_args is not None:
|
| 433 |
+
args = parser.parse_args(input_args)
|
| 434 |
+
else:
|
| 435 |
+
args = parser.parse_args()
|
| 436 |
+
|
| 437 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 438 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 439 |
+
args.local_rank = env_local_rank
|
| 440 |
+
|
| 441 |
+
return args
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def tokenize_captions(tokenizers, sample):
|
| 445 |
+
tokens_one = tokenizers[0](
|
| 446 |
+
sample["original_prompt"],
|
| 447 |
+
truncation=True,
|
| 448 |
+
padding="max_length",
|
| 449 |
+
max_length=tokenizers[0].model_max_length,
|
| 450 |
+
return_tensors="pt",
|
| 451 |
+
).input_ids
|
| 452 |
+
tokens_two = tokenizers[1](
|
| 453 |
+
sample["original_prompt"],
|
| 454 |
+
truncation=True,
|
| 455 |
+
padding="max_length",
|
| 456 |
+
max_length=tokenizers[1].model_max_length,
|
| 457 |
+
return_tensors="pt",
|
| 458 |
+
).input_ids
|
| 459 |
+
|
| 460 |
+
return tokens_one, tokens_two
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
@torch.no_grad()
|
| 464 |
+
def encode_prompt(text_encoders, text_input_ids_list):
|
| 465 |
+
prompt_embeds_list = []
|
| 466 |
+
|
| 467 |
+
for i, text_encoder in enumerate(text_encoders):
|
| 468 |
+
text_input_ids = text_input_ids_list[i]
|
| 469 |
+
|
| 470 |
+
prompt_embeds = text_encoder(
|
| 471 |
+
text_input_ids.to(text_encoder.device),
|
| 472 |
+
output_hidden_states=True,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
| 476 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
| 477 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
| 478 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 479 |
+
prompt_embeds = prompt_embeds.view(bs_embed, seq_len, -1)
|
| 480 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 481 |
+
|
| 482 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 483 |
+
pooled_prompt_embeds = pooled_prompt_embeds.view(bs_embed, -1)
|
| 484 |
+
return prompt_embeds, pooled_prompt_embeds
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def get_dataset(args):
|
| 488 |
+
dataset = (
|
| 489 |
+
wds.WebDataset(args.dataset_path, resampled=True, handler=wds.warn_and_continue)
|
| 490 |
+
.shuffle(690, handler=wds.warn_and_continue)
|
| 491 |
+
.decode("pil", handler=wds.warn_and_continue)
|
| 492 |
+
.rename(
|
| 493 |
+
original_prompt="original_prompt.txt",
|
| 494 |
+
jpg_0="jpg_0.jpg",
|
| 495 |
+
jpg_1="jpg_1.jpg",
|
| 496 |
+
label_0="label_0.txt",
|
| 497 |
+
label_1="label_1.txt",
|
| 498 |
+
handler=wds.warn_and_continue,
|
| 499 |
+
)
|
| 500 |
+
)
|
| 501 |
+
return dataset
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def get_loader(args, tokenizer_one, tokenizer_two):
|
| 505 |
+
# 1,001,352
|
| 506 |
+
num_batches = math.ceil(args.num_train_examples / args.global_batch_size)
|
| 507 |
+
num_worker_batches = math.ceil(
|
| 508 |
+
args.num_train_examples / (args.global_batch_size * args.dataloader_num_workers)
|
| 509 |
+
) # per dataloader worker
|
| 510 |
+
num_batches = num_worker_batches * args.dataloader_num_workers
|
| 511 |
+
num_samples = num_batches * args.global_batch_size
|
| 512 |
+
|
| 513 |
+
dataset = get_dataset(args)
|
| 514 |
+
|
| 515 |
+
train_resize = transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 516 |
+
train_crop = transforms.RandomCrop(args.resolution) if args.random_crop else transforms.CenterCrop(args.resolution)
|
| 517 |
+
train_flip = transforms.RandomHorizontalFlip(p=1.0)
|
| 518 |
+
to_tensor = transforms.ToTensor()
|
| 519 |
+
normalize = transforms.Normalize([0.5], [0.5])
|
| 520 |
+
|
| 521 |
+
def preprocess_images(sample):
|
| 522 |
+
jpg_0_image = sample["jpg_0"]
|
| 523 |
+
original_size = (jpg_0_image.height, jpg_0_image.width)
|
| 524 |
+
crop_top_left = []
|
| 525 |
+
|
| 526 |
+
jpg_1_image = sample["jpg_1"]
|
| 527 |
+
# Need to bring down the image to the same resolution.
|
| 528 |
+
# This seems like the simplest reasonable approach.
|
| 529 |
+
# "::-1" because PIL resize takes (width, height).
|
| 530 |
+
jpg_1_image = jpg_1_image.resize(original_size[::-1])
|
| 531 |
+
|
| 532 |
+
# We randomize selection and rejection.
|
| 533 |
+
label_0 = sample["label_0"]
|
| 534 |
+
if sample["label_0"] == 0.5:
|
| 535 |
+
if random.random() < 0.5:
|
| 536 |
+
label_0 = 0
|
| 537 |
+
else:
|
| 538 |
+
label_0 = 1
|
| 539 |
+
|
| 540 |
+
# Double on channel dim, jpg_y then jpg_w
|
| 541 |
+
if label_0 == 0:
|
| 542 |
+
pixel_values = torch.cat([to_tensor(image) for image in [jpg_1_image, jpg_0_image]])
|
| 543 |
+
else:
|
| 544 |
+
pixel_values = torch.cat([to_tensor(image) for image in [jpg_0_image, jpg_1_image]])
|
| 545 |
+
|
| 546 |
+
# Resize.
|
| 547 |
+
combined_im = train_resize(pixel_values)
|
| 548 |
+
|
| 549 |
+
# Flipping.
|
| 550 |
+
if not args.no_hflip and random.random() < 0.5:
|
| 551 |
+
combined_im = train_flip(combined_im)
|
| 552 |
+
|
| 553 |
+
# Cropping.
|
| 554 |
+
if not args.random_crop:
|
| 555 |
+
y1 = max(0, int(round((combined_im.shape[1] - args.resolution) / 2.0)))
|
| 556 |
+
x1 = max(0, int(round((combined_im.shape[2] - args.resolution) / 2.0)))
|
| 557 |
+
combined_im = train_crop(combined_im)
|
| 558 |
+
else:
|
| 559 |
+
y1, x1, h, w = train_crop.get_params(combined_im, (args.resolution, args.resolution))
|
| 560 |
+
combined_im = crop(combined_im, y1, x1, h, w)
|
| 561 |
+
|
| 562 |
+
crop_top_left = (y1, x1)
|
| 563 |
+
combined_im = normalize(combined_im)
|
| 564 |
+
tokens_one, tokens_two = tokenize_captions([tokenizer_one, tokenizer_two], sample)
|
| 565 |
+
|
| 566 |
+
return {
|
| 567 |
+
"pixel_values": combined_im,
|
| 568 |
+
"original_size": original_size,
|
| 569 |
+
"crop_top_left": crop_top_left,
|
| 570 |
+
"tokens_one": tokens_one,
|
| 571 |
+
"tokens_two": tokens_two,
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
def collate_fn(samples):
|
| 575 |
+
pixel_values = torch.stack([sample["pixel_values"] for sample in samples])
|
| 576 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 577 |
+
|
| 578 |
+
original_sizes = [example["original_size"] for example in samples]
|
| 579 |
+
crop_top_lefts = [example["crop_top_left"] for example in samples]
|
| 580 |
+
input_ids_one = torch.stack([example["tokens_one"] for example in samples])
|
| 581 |
+
input_ids_two = torch.stack([example["tokens_two"] for example in samples])
|
| 582 |
+
|
| 583 |
+
return {
|
| 584 |
+
"pixel_values": pixel_values,
|
| 585 |
+
"input_ids_one": input_ids_one,
|
| 586 |
+
"input_ids_two": input_ids_two,
|
| 587 |
+
"original_sizes": original_sizes,
|
| 588 |
+
"crop_top_lefts": crop_top_lefts,
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
dataset = dataset.map(preprocess_images, handler=wds.warn_and_continue)
|
| 592 |
+
dataset = dataset.batched(args.per_gpu_batch_size, partial=False, collation_fn=collate_fn)
|
| 593 |
+
dataset = dataset.with_epoch(num_worker_batches)
|
| 594 |
+
|
| 595 |
+
dataloader = wds.WebLoader(
|
| 596 |
+
dataset,
|
| 597 |
+
batch_size=None,
|
| 598 |
+
shuffle=False,
|
| 599 |
+
num_workers=args.dataloader_num_workers,
|
| 600 |
+
pin_memory=True,
|
| 601 |
+
persistent_workers=True,
|
| 602 |
+
)
|
| 603 |
+
# add meta-data to dataloader instance for convenience
|
| 604 |
+
dataloader.num_batches = num_batches
|
| 605 |
+
dataloader.num_samples = num_samples
|
| 606 |
+
return dataloader
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def main(args):
|
| 610 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 611 |
+
raise ValueError(
|
| 612 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 613 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 617 |
+
|
| 618 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 619 |
+
|
| 620 |
+
accelerator = Accelerator(
|
| 621 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 622 |
+
mixed_precision=args.mixed_precision,
|
| 623 |
+
log_with=args.report_to,
|
| 624 |
+
project_config=accelerator_project_config,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
# Disable AMP for MPS.
|
| 628 |
+
if torch.backends.mps.is_available():
|
| 629 |
+
accelerator.native_amp = False
|
| 630 |
+
|
| 631 |
+
# Make one log on every process with the configuration for debugging.
|
| 632 |
+
logging.basicConfig(
|
| 633 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 634 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 635 |
+
level=logging.INFO,
|
| 636 |
+
)
|
| 637 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 638 |
+
if accelerator.is_local_main_process:
|
| 639 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 640 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 641 |
+
else:
|
| 642 |
+
transformers.utils.logging.set_verbosity_error()
|
| 643 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 644 |
+
|
| 645 |
+
# If passed along, set the training seed now.
|
| 646 |
+
if args.seed is not None:
|
| 647 |
+
set_seed(args.seed)
|
| 648 |
+
|
| 649 |
+
# Handle the repository creation
|
| 650 |
+
if accelerator.is_main_process:
|
| 651 |
+
if args.output_dir is not None:
|
| 652 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 653 |
+
|
| 654 |
+
if args.push_to_hub:
|
| 655 |
+
repo_id = create_repo(
|
| 656 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 657 |
+
).repo_id
|
| 658 |
+
|
| 659 |
+
# Load the tokenizers
|
| 660 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 661 |
+
args.pretrained_model_name_or_path,
|
| 662 |
+
subfolder="tokenizer",
|
| 663 |
+
revision=args.revision,
|
| 664 |
+
use_fast=False,
|
| 665 |
+
)
|
| 666 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 667 |
+
args.pretrained_model_name_or_path,
|
| 668 |
+
subfolder="tokenizer_2",
|
| 669 |
+
revision=args.revision,
|
| 670 |
+
use_fast=False,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
# import correct text encoder classes
|
| 674 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 675 |
+
args.pretrained_model_name_or_path, args.revision
|
| 676 |
+
)
|
| 677 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 678 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
# Load scheduler and models
|
| 682 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 683 |
+
|
| 684 |
+
text_encoder_one = text_encoder_cls_one.from_pretrained(
|
| 685 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 686 |
+
)
|
| 687 |
+
text_encoder_two = text_encoder_cls_two.from_pretrained(
|
| 688 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
| 689 |
+
)
|
| 690 |
+
vae_path = (
|
| 691 |
+
args.pretrained_model_name_or_path
|
| 692 |
+
if args.pretrained_vae_model_name_or_path is None
|
| 693 |
+
else args.pretrained_vae_model_name_or_path
|
| 694 |
+
)
|
| 695 |
+
vae = AutoencoderKL.from_pretrained(
|
| 696 |
+
vae_path,
|
| 697 |
+
subfolder="vae" if args.pretrained_vae_model_name_or_path is None else None,
|
| 698 |
+
revision=args.revision,
|
| 699 |
+
variant=args.variant,
|
| 700 |
+
)
|
| 701 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 702 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision, variant=args.variant
|
| 703 |
+
)
|
| 704 |
+
|
| 705 |
+
# We only train the additional adapter LoRA layers
|
| 706 |
+
vae.requires_grad_(False)
|
| 707 |
+
text_encoder_one.requires_grad_(False)
|
| 708 |
+
text_encoder_two.requires_grad_(False)
|
| 709 |
+
unet.requires_grad_(False)
|
| 710 |
+
|
| 711 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 712 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 713 |
+
weight_dtype = torch.float32
|
| 714 |
+
if accelerator.mixed_precision == "fp16":
|
| 715 |
+
weight_dtype = torch.float16
|
| 716 |
+
elif accelerator.mixed_precision == "bf16":
|
| 717 |
+
weight_dtype = torch.bfloat16
|
| 718 |
+
|
| 719 |
+
# Move unet and text_encoders to device and cast to weight_dtype
|
| 720 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 721 |
+
text_encoder_one.to(accelerator.device, dtype=weight_dtype)
|
| 722 |
+
text_encoder_two.to(accelerator.device, dtype=weight_dtype)
|
| 723 |
+
|
| 724 |
+
# The VAE is always in float32 to avoid NaN losses.
|
| 725 |
+
vae.to(accelerator.device, dtype=torch.float32)
|
| 726 |
+
|
| 727 |
+
# Set up LoRA.
|
| 728 |
+
unet_lora_config = LoraConfig(
|
| 729 |
+
r=args.rank,
|
| 730 |
+
lora_alpha=args.rank,
|
| 731 |
+
init_lora_weights="gaussian",
|
| 732 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 733 |
+
)
|
| 734 |
+
# Add adapter and make sure the trainable params are in float32.
|
| 735 |
+
unet.add_adapter(unet_lora_config)
|
| 736 |
+
if args.mixed_precision == "fp16":
|
| 737 |
+
for param in unet.parameters():
|
| 738 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 739 |
+
if param.requires_grad:
|
| 740 |
+
param.data = param.to(torch.float32)
|
| 741 |
+
|
| 742 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 743 |
+
if is_xformers_available():
|
| 744 |
+
import xformers
|
| 745 |
+
|
| 746 |
+
xformers_version = version.parse(xformers.__version__)
|
| 747 |
+
if xformers_version == version.parse("0.0.16"):
|
| 748 |
+
logger.warning(
|
| 749 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 750 |
+
)
|
| 751 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 752 |
+
else:
|
| 753 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 754 |
+
|
| 755 |
+
if args.gradient_checkpointing:
|
| 756 |
+
unet.enable_gradient_checkpointing()
|
| 757 |
+
|
| 758 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 759 |
+
def save_model_hook(models, weights, output_dir):
|
| 760 |
+
if accelerator.is_main_process:
|
| 761 |
+
# there are only two options here. Either are just the unet attn processor layers
|
| 762 |
+
# or there are the unet and text encoder atten layers
|
| 763 |
+
unet_lora_layers_to_save = None
|
| 764 |
+
|
| 765 |
+
for model in models:
|
| 766 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 767 |
+
unet_lora_layers_to_save = convert_state_dict_to_diffusers(get_peft_model_state_dict(model))
|
| 768 |
+
else:
|
| 769 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 770 |
+
|
| 771 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 772 |
+
weights.pop()
|
| 773 |
+
|
| 774 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(
|
| 775 |
+
output_dir,
|
| 776 |
+
unet_lora_layers=unet_lora_layers_to_save,
|
| 777 |
+
text_encoder_lora_layers=None,
|
| 778 |
+
text_encoder_2_lora_layers=None,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
def load_model_hook(models, input_dir):
|
| 782 |
+
unet_ = None
|
| 783 |
+
|
| 784 |
+
while len(models) > 0:
|
| 785 |
+
model = models.pop()
|
| 786 |
+
|
| 787 |
+
if isinstance(model, type(accelerator.unwrap_model(unet))):
|
| 788 |
+
unet_ = model
|
| 789 |
+
else:
|
| 790 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 791 |
+
|
| 792 |
+
lora_state_dict, network_alphas = StableDiffusionXLLoraLoaderMixin.lora_state_dict(input_dir)
|
| 793 |
+
|
| 794 |
+
unet_state_dict = {f"{k.replace('unet.', '')}": v for k, v in lora_state_dict.items() if k.startswith("unet.")}
|
| 795 |
+
unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
|
| 796 |
+
incompatible_keys = set_peft_model_state_dict(unet_, unet_state_dict, adapter_name="default")
|
| 797 |
+
if incompatible_keys is not None:
|
| 798 |
+
# check only for unexpected keys
|
| 799 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 800 |
+
if unexpected_keys:
|
| 801 |
+
logger.warning(
|
| 802 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 803 |
+
f" {unexpected_keys}. "
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 807 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 808 |
+
|
| 809 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 810 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 811 |
+
if args.allow_tf32:
|
| 812 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 813 |
+
|
| 814 |
+
if args.scale_lr:
|
| 815 |
+
args.learning_rate = (
|
| 816 |
+
args.learning_rate * args.gradient_accumulation_steps * args.per_gpu_batch_size * accelerator.num_processes
|
| 817 |
+
)
|
| 818 |
+
|
| 819 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 820 |
+
if args.use_8bit_adam:
|
| 821 |
+
try:
|
| 822 |
+
import bitsandbytes as bnb
|
| 823 |
+
except ImportError:
|
| 824 |
+
raise ImportError(
|
| 825 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 829 |
+
else:
|
| 830 |
+
optimizer_class = torch.optim.AdamW
|
| 831 |
+
|
| 832 |
+
# Optimizer creation
|
| 833 |
+
params_to_optimize = list(filter(lambda p: p.requires_grad, unet.parameters()))
|
| 834 |
+
optimizer = optimizer_class(
|
| 835 |
+
params_to_optimize,
|
| 836 |
+
lr=args.learning_rate,
|
| 837 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 838 |
+
weight_decay=args.adam_weight_decay,
|
| 839 |
+
eps=args.adam_epsilon,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
# Dataset and DataLoaders creation:
|
| 843 |
+
args.global_batch_size = args.per_gpu_batch_size * accelerator.num_processes
|
| 844 |
+
train_dataloader = get_loader(args, tokenizer_one=tokenizer_one, tokenizer_two=tokenizer_two)
|
| 845 |
+
|
| 846 |
+
# Scheduler and math around the number of training steps.
|
| 847 |
+
overrode_max_train_steps = False
|
| 848 |
+
num_update_steps_per_epoch = math.ceil(train_dataloader.num_batches / args.gradient_accumulation_steps)
|
| 849 |
+
if args.max_train_steps is None:
|
| 850 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 851 |
+
overrode_max_train_steps = True
|
| 852 |
+
|
| 853 |
+
lr_scheduler = get_scheduler(
|
| 854 |
+
args.lr_scheduler,
|
| 855 |
+
optimizer=optimizer,
|
| 856 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 857 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 858 |
+
num_cycles=args.lr_num_cycles,
|
| 859 |
+
power=args.lr_power,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
unet, optimizer, lr_scheduler = accelerator.prepare(unet, optimizer, lr_scheduler)
|
| 863 |
+
|
| 864 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 865 |
+
num_update_steps_per_epoch = math.ceil(train_dataloader.num_batches / args.gradient_accumulation_steps)
|
| 866 |
+
if overrode_max_train_steps:
|
| 867 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 868 |
+
# Afterwards we recalculate our number of training epochs
|
| 869 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 870 |
+
|
| 871 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 872 |
+
# The trackers initializes automatically on the main process.
|
| 873 |
+
if accelerator.is_main_process:
|
| 874 |
+
accelerator.init_trackers(args.tracker_name, config=vars(args))
|
| 875 |
+
|
| 876 |
+
# Train!
|
| 877 |
+
total_batch_size = args.per_gpu_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 878 |
+
|
| 879 |
+
logger.info("***** Running training *****")
|
| 880 |
+
logger.info(f" Num examples = {train_dataloader.num_samples}")
|
| 881 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 882 |
+
logger.info(f" Instantaneous batch size per device = {args.per_gpu_batch_size}")
|
| 883 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 884 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 885 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 886 |
+
global_step = 0
|
| 887 |
+
first_epoch = 0
|
| 888 |
+
|
| 889 |
+
# Potentially load in the weights and states from a previous save
|
| 890 |
+
if args.resume_from_checkpoint:
|
| 891 |
+
if args.resume_from_checkpoint != "latest":
|
| 892 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 893 |
+
else:
|
| 894 |
+
# Get the mos recent checkpoint
|
| 895 |
+
dirs = os.listdir(args.output_dir)
|
| 896 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 897 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 898 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 899 |
+
|
| 900 |
+
if path is None:
|
| 901 |
+
accelerator.print(
|
| 902 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 903 |
+
)
|
| 904 |
+
args.resume_from_checkpoint = None
|
| 905 |
+
initial_global_step = 0
|
| 906 |
+
else:
|
| 907 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 908 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 909 |
+
global_step = int(path.split("-")[1])
|
| 910 |
+
|
| 911 |
+
initial_global_step = global_step
|
| 912 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 913 |
+
else:
|
| 914 |
+
initial_global_step = 0
|
| 915 |
+
|
| 916 |
+
progress_bar = tqdm(
|
| 917 |
+
range(0, args.max_train_steps),
|
| 918 |
+
initial=initial_global_step,
|
| 919 |
+
desc="Steps",
|
| 920 |
+
# Only show the progress bar once on each machine.
|
| 921 |
+
disable=not accelerator.is_local_main_process,
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
unet.train()
|
| 925 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 926 |
+
for step, batch in enumerate(train_dataloader):
|
| 927 |
+
with accelerator.accumulate(unet):
|
| 928 |
+
# (batch_size, 2*channels, h, w) -> (2*batch_size, channels, h, w)
|
| 929 |
+
pixel_values = batch["pixel_values"].to(dtype=vae.dtype, device=accelerator.device, non_blocking=True)
|
| 930 |
+
feed_pixel_values = torch.cat(pixel_values.chunk(2, dim=1))
|
| 931 |
+
|
| 932 |
+
latents = []
|
| 933 |
+
for i in range(0, feed_pixel_values.shape[0], args.vae_encode_batch_size):
|
| 934 |
+
latents.append(
|
| 935 |
+
vae.encode(feed_pixel_values[i : i + args.vae_encode_batch_size]).latent_dist.sample()
|
| 936 |
+
)
|
| 937 |
+
latents = torch.cat(latents, dim=0)
|
| 938 |
+
latents = latents * vae.config.scaling_factor
|
| 939 |
+
if args.pretrained_vae_model_name_or_path is None:
|
| 940 |
+
latents = latents.to(weight_dtype)
|
| 941 |
+
|
| 942 |
+
# Sample noise that we'll add to the latents
|
| 943 |
+
noise = torch.randn_like(latents).chunk(2)[0].repeat(2, 1, 1, 1)
|
| 944 |
+
|
| 945 |
+
# Sample a random timestep for each image
|
| 946 |
+
bsz = latents.shape[0] // 2
|
| 947 |
+
timesteps = torch.randint(
|
| 948 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device, dtype=torch.long
|
| 949 |
+
).repeat(2)
|
| 950 |
+
|
| 951 |
+
# Add noise to the model input according to the noise magnitude at each timestep
|
| 952 |
+
# (this is the forward diffusion process)
|
| 953 |
+
noisy_model_input = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 954 |
+
|
| 955 |
+
# time ids
|
| 956 |
+
def compute_time_ids(original_size, crops_coords_top_left):
|
| 957 |
+
# Adapted from pipeline.StableDiffusionXLPipeline._get_add_time_ids
|
| 958 |
+
target_size = (args.resolution, args.resolution)
|
| 959 |
+
add_time_ids = list(tuple(original_size) + tuple(crops_coords_top_left) + target_size)
|
| 960 |
+
add_time_ids = torch.tensor([add_time_ids])
|
| 961 |
+
add_time_ids = add_time_ids.to(accelerator.device, dtype=weight_dtype)
|
| 962 |
+
return add_time_ids
|
| 963 |
+
|
| 964 |
+
add_time_ids = torch.cat(
|
| 965 |
+
[compute_time_ids(s, c) for s, c in zip(batch["original_sizes"], batch["crop_top_lefts"])]
|
| 966 |
+
).repeat(2, 1)
|
| 967 |
+
|
| 968 |
+
# Get the text embedding for conditioning
|
| 969 |
+
prompt_embeds, pooled_prompt_embeds = encode_prompt(
|
| 970 |
+
[text_encoder_one, text_encoder_two], [batch["input_ids_one"], batch["input_ids_two"]]
|
| 971 |
+
)
|
| 972 |
+
prompt_embeds = prompt_embeds.repeat(2, 1, 1)
|
| 973 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(2, 1)
|
| 974 |
+
|
| 975 |
+
# Predict the noise residual
|
| 976 |
+
model_pred = unet(
|
| 977 |
+
noisy_model_input,
|
| 978 |
+
timesteps,
|
| 979 |
+
prompt_embeds,
|
| 980 |
+
added_cond_kwargs={"time_ids": add_time_ids, "text_embeds": pooled_prompt_embeds},
|
| 981 |
+
).sample
|
| 982 |
+
|
| 983 |
+
# Get the target for loss depending on the prediction type
|
| 984 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 985 |
+
target = noise
|
| 986 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 987 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 988 |
+
else:
|
| 989 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 990 |
+
|
| 991 |
+
# ODDS ratio loss.
|
| 992 |
+
# In the diffusion formulation, we're assuming that the MSE loss
|
| 993 |
+
# approximates the logp.
|
| 994 |
+
model_losses = F.mse_loss(model_pred.float(), target.float(), reduction="none")
|
| 995 |
+
model_losses = model_losses.mean(dim=list(range(1, len(model_losses.shape))))
|
| 996 |
+
model_losses_w, model_losses_l = model_losses.chunk(2)
|
| 997 |
+
log_odds = model_losses_w - model_losses_l
|
| 998 |
+
|
| 999 |
+
# Ratio loss.
|
| 1000 |
+
ratio = F.logsigmoid(log_odds)
|
| 1001 |
+
ratio_losses = args.beta_orpo * ratio
|
| 1002 |
+
|
| 1003 |
+
# Full ORPO loss
|
| 1004 |
+
loss = model_losses_w.mean() - ratio_losses.mean()
|
| 1005 |
+
|
| 1006 |
+
# Backprop.
|
| 1007 |
+
accelerator.backward(loss)
|
| 1008 |
+
if accelerator.sync_gradients:
|
| 1009 |
+
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
|
| 1010 |
+
optimizer.step()
|
| 1011 |
+
lr_scheduler.step()
|
| 1012 |
+
optimizer.zero_grad()
|
| 1013 |
+
|
| 1014 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1015 |
+
if accelerator.sync_gradients:
|
| 1016 |
+
progress_bar.update(1)
|
| 1017 |
+
global_step += 1
|
| 1018 |
+
|
| 1019 |
+
if accelerator.is_main_process:
|
| 1020 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1021 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1022 |
+
if args.checkpoints_total_limit is not None:
|
| 1023 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1024 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1025 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1026 |
+
|
| 1027 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1028 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1029 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1030 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1031 |
+
|
| 1032 |
+
logger.info(
|
| 1033 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1034 |
+
)
|
| 1035 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1036 |
+
|
| 1037 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1038 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1039 |
+
shutil.rmtree(removing_checkpoint)
|
| 1040 |
+
|
| 1041 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1042 |
+
accelerator.save_state(save_path)
|
| 1043 |
+
logger.info(f"Saved state to {save_path}")
|
| 1044 |
+
|
| 1045 |
+
if args.run_validation and global_step % args.validation_steps == 0:
|
| 1046 |
+
log_validation(
|
| 1047 |
+
args, unet=unet, vae=vae, accelerator=accelerator, weight_dtype=weight_dtype, epoch=epoch
|
| 1048 |
+
)
|
| 1049 |
+
|
| 1050 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1051 |
+
progress_bar.set_postfix(**logs)
|
| 1052 |
+
accelerator.log(logs, step=global_step)
|
| 1053 |
+
|
| 1054 |
+
if global_step >= args.max_train_steps:
|
| 1055 |
+
break
|
| 1056 |
+
|
| 1057 |
+
# Save the lora layers
|
| 1058 |
+
accelerator.wait_for_everyone()
|
| 1059 |
+
if accelerator.is_main_process:
|
| 1060 |
+
unet = accelerator.unwrap_model(unet)
|
| 1061 |
+
unet = unet.to(torch.float32)
|
| 1062 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unet))
|
| 1063 |
+
|
| 1064 |
+
StableDiffusionXLLoraLoaderMixin.save_lora_weights(
|
| 1065 |
+
save_directory=args.output_dir,
|
| 1066 |
+
unet_lora_layers=unet_lora_state_dict,
|
| 1067 |
+
text_encoder_lora_layers=None,
|
| 1068 |
+
text_encoder_2_lora_layers=None,
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
# Final validation?
|
| 1072 |
+
if args.run_validation:
|
| 1073 |
+
log_validation(
|
| 1074 |
+
args,
|
| 1075 |
+
unet=None,
|
| 1076 |
+
vae=vae,
|
| 1077 |
+
accelerator=accelerator,
|
| 1078 |
+
weight_dtype=weight_dtype,
|
| 1079 |
+
epoch=epoch,
|
| 1080 |
+
is_final_validation=True,
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
if args.push_to_hub:
|
| 1084 |
+
upload_folder(
|
| 1085 |
+
repo_id=repo_id,
|
| 1086 |
+
folder_path=args.output_dir,
|
| 1087 |
+
commit_message="End of training",
|
| 1088 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
accelerator.end_training()
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
if __name__ == "__main__":
|
| 1095 |
+
args = parse_args()
|
| 1096 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dreambooth for the inpainting model
|
| 2 |
+
|
| 3 |
+
This script was added by @thedarkzeno .
|
| 4 |
+
|
| 5 |
+
Please note that this script is not actively maintained, you can open an issue and tag @thedarkzeno or @patil-suraj though.
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-inpainting"
|
| 9 |
+
export INSTANCE_DIR="path-to-instance-images"
|
| 10 |
+
export OUTPUT_DIR="path-to-save-model"
|
| 11 |
+
|
| 12 |
+
accelerate launch train_dreambooth_inpaint.py \
|
| 13 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 14 |
+
--instance_data_dir=$INSTANCE_DIR \
|
| 15 |
+
--output_dir=$OUTPUT_DIR \
|
| 16 |
+
--instance_prompt="a photo of sks dog" \
|
| 17 |
+
--resolution=512 \
|
| 18 |
+
--train_batch_size=1 \
|
| 19 |
+
--gradient_accumulation_steps=1 \
|
| 20 |
+
--learning_rate=5e-6 \
|
| 21 |
+
--lr_scheduler="constant" \
|
| 22 |
+
--lr_warmup_steps=0 \
|
| 23 |
+
--max_train_steps=400
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
### Training with prior-preservation loss
|
| 27 |
+
|
| 28 |
+
Prior-preservation is used to avoid overfitting and language-drift. Refer to the paper to learn more about it. For prior-preservation we first generate images using the model with a class prompt and then use those during training along with our data.
|
| 29 |
+
According to the paper, it's recommended to generate `num_epochs * num_samples` images for prior-preservation. 200-300 works well for most cases.
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-inpainting"
|
| 33 |
+
export INSTANCE_DIR="path-to-instance-images"
|
| 34 |
+
export CLASS_DIR="path-to-class-images"
|
| 35 |
+
export OUTPUT_DIR="path-to-save-model"
|
| 36 |
+
|
| 37 |
+
accelerate launch train_dreambooth_inpaint.py \
|
| 38 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 39 |
+
--instance_data_dir=$INSTANCE_DIR \
|
| 40 |
+
--class_data_dir=$CLASS_DIR \
|
| 41 |
+
--output_dir=$OUTPUT_DIR \
|
| 42 |
+
--with_prior_preservation --prior_loss_weight=1.0 \
|
| 43 |
+
--instance_prompt="a photo of sks dog" \
|
| 44 |
+
--class_prompt="a photo of dog" \
|
| 45 |
+
--resolution=512 \
|
| 46 |
+
--train_batch_size=1 \
|
| 47 |
+
--gradient_accumulation_steps=1 \
|
| 48 |
+
--learning_rate=5e-6 \
|
| 49 |
+
--lr_scheduler="constant" \
|
| 50 |
+
--lr_warmup_steps=0 \
|
| 51 |
+
--num_class_images=200 \
|
| 52 |
+
--max_train_steps=800
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
### Training with gradient checkpointing and 8-bit optimizer:
|
| 57 |
+
|
| 58 |
+
With the help of gradient checkpointing and the 8-bit optimizer from bitsandbytes it's possible to run train dreambooth on a 16GB GPU.
|
| 59 |
+
|
| 60 |
+
To install `bitandbytes` please refer to this [readme](https://github.com/TimDettmers/bitsandbytes#requirements--installation).
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-inpainting"
|
| 64 |
+
export INSTANCE_DIR="path-to-instance-images"
|
| 65 |
+
export CLASS_DIR="path-to-class-images"
|
| 66 |
+
export OUTPUT_DIR="path-to-save-model"
|
| 67 |
+
|
| 68 |
+
accelerate launch train_dreambooth_inpaint.py \
|
| 69 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 70 |
+
--instance_data_dir=$INSTANCE_DIR \
|
| 71 |
+
--class_data_dir=$CLASS_DIR \
|
| 72 |
+
--output_dir=$OUTPUT_DIR \
|
| 73 |
+
--with_prior_preservation --prior_loss_weight=1.0 \
|
| 74 |
+
--instance_prompt="a photo of sks dog" \
|
| 75 |
+
--class_prompt="a photo of dog" \
|
| 76 |
+
--resolution=512 \
|
| 77 |
+
--train_batch_size=1 \
|
| 78 |
+
--gradient_accumulation_steps=2 --gradient_checkpointing \
|
| 79 |
+
--use_8bit_adam \
|
| 80 |
+
--learning_rate=5e-6 \
|
| 81 |
+
--lr_scheduler="constant" \
|
| 82 |
+
--lr_warmup_steps=0 \
|
| 83 |
+
--num_class_images=200 \
|
| 84 |
+
--max_train_steps=800
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
### Fine-tune text encoder with the UNet.
|
| 88 |
+
|
| 89 |
+
The script also allows to fine-tune the `text_encoder` along with the `unet`. It's been observed experimentally that fine-tuning `text_encoder` gives much better results especially on faces.
|
| 90 |
+
Pass the `--train_text_encoder` argument to the script to enable training `text_encoder`.
|
| 91 |
+
|
| 92 |
+
___Note: Training text encoder requires more memory, with this option the training won't fit on 16GB GPU. It needs at least 24GB VRAM.___
|
| 93 |
+
|
| 94 |
+
```bash
|
| 95 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-inpainting"
|
| 96 |
+
export INSTANCE_DIR="path-to-instance-images"
|
| 97 |
+
export CLASS_DIR="path-to-class-images"
|
| 98 |
+
export OUTPUT_DIR="path-to-save-model"
|
| 99 |
+
|
| 100 |
+
accelerate launch train_dreambooth_inpaint.py \
|
| 101 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 102 |
+
--train_text_encoder \
|
| 103 |
+
--instance_data_dir=$INSTANCE_DIR \
|
| 104 |
+
--class_data_dir=$CLASS_DIR \
|
| 105 |
+
--output_dir=$OUTPUT_DIR \
|
| 106 |
+
--with_prior_preservation --prior_loss_weight=1.0 \
|
| 107 |
+
--instance_prompt="a photo of sks dog" \
|
| 108 |
+
--class_prompt="a photo of dog" \
|
| 109 |
+
--resolution=512 \
|
| 110 |
+
--train_batch_size=1 \
|
| 111 |
+
--use_8bit_adam \
|
| 112 |
+
--gradient_checkpointing \
|
| 113 |
+
--learning_rate=2e-6 \
|
| 114 |
+
--lr_scheduler="constant" \
|
| 115 |
+
--lr_warmup_steps=0 \
|
| 116 |
+
--num_class_images=200 \
|
| 117 |
+
--max_train_steps=800
|
| 118 |
+
```
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diffusers==0.9.0
|
| 2 |
+
accelerate>=0.16.0
|
| 3 |
+
torchvision
|
| 4 |
+
transformers>=4.21.0
|
| 5 |
+
ftfy
|
| 6 |
+
tensorboard
|
| 7 |
+
Jinja2
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/train_dreambooth_inpaint.py
ADDED
|
@@ -0,0 +1,812 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.utils.checkpoint
|
| 12 |
+
from accelerate import Accelerator
|
| 13 |
+
from accelerate.logging import get_logger
|
| 14 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 15 |
+
from huggingface_hub import create_repo, upload_folder
|
| 16 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 17 |
+
from PIL import Image, ImageDraw
|
| 18 |
+
from torch.utils.data import Dataset
|
| 19 |
+
from torchvision import transforms
|
| 20 |
+
from tqdm.auto import tqdm
|
| 21 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKL,
|
| 25 |
+
DDPMScheduler,
|
| 26 |
+
StableDiffusionInpaintPipeline,
|
| 27 |
+
StableDiffusionPipeline,
|
| 28 |
+
UNet2DConditionModel,
|
| 29 |
+
)
|
| 30 |
+
from diffusers.optimization import get_scheduler
|
| 31 |
+
from diffusers.utils import check_min_version
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 35 |
+
check_min_version("0.13.0.dev0")
|
| 36 |
+
|
| 37 |
+
logger = get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def prepare_mask_and_masked_image(image, mask):
|
| 41 |
+
image = np.array(image.convert("RGB"))
|
| 42 |
+
image = image[None].transpose(0, 3, 1, 2)
|
| 43 |
+
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
|
| 44 |
+
|
| 45 |
+
mask = np.array(mask.convert("L"))
|
| 46 |
+
mask = mask.astype(np.float32) / 255.0
|
| 47 |
+
mask = mask[None, None]
|
| 48 |
+
mask[mask < 0.5] = 0
|
| 49 |
+
mask[mask >= 0.5] = 1
|
| 50 |
+
mask = torch.from_numpy(mask)
|
| 51 |
+
|
| 52 |
+
masked_image = image * (mask < 0.5)
|
| 53 |
+
|
| 54 |
+
return mask, masked_image
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# generate random masks
|
| 58 |
+
def random_mask(im_shape, ratio=1, mask_full_image=False):
|
| 59 |
+
mask = Image.new("L", im_shape, 0)
|
| 60 |
+
draw = ImageDraw.Draw(mask)
|
| 61 |
+
size = (random.randint(0, int(im_shape[0] * ratio)), random.randint(0, int(im_shape[1] * ratio)))
|
| 62 |
+
# use this to always mask the whole image
|
| 63 |
+
if mask_full_image:
|
| 64 |
+
size = (int(im_shape[0] * ratio), int(im_shape[1] * ratio))
|
| 65 |
+
limits = (im_shape[0] - size[0] // 2, im_shape[1] - size[1] // 2)
|
| 66 |
+
center = (random.randint(size[0] // 2, limits[0]), random.randint(size[1] // 2, limits[1]))
|
| 67 |
+
draw_type = random.randint(0, 1)
|
| 68 |
+
if draw_type == 0 or mask_full_image:
|
| 69 |
+
draw.rectangle(
|
| 70 |
+
(center[0] - size[0] // 2, center[1] - size[1] // 2, center[0] + size[0] // 2, center[1] + size[1] // 2),
|
| 71 |
+
fill=255,
|
| 72 |
+
)
|
| 73 |
+
else:
|
| 74 |
+
draw.ellipse(
|
| 75 |
+
(center[0] - size[0] // 2, center[1] - size[1] // 2, center[0] + size[0] // 2, center[1] + size[1] // 2),
|
| 76 |
+
fill=255,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return mask
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def parse_args():
|
| 83 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 84 |
+
parser.add_argument(
|
| 85 |
+
"--pretrained_model_name_or_path",
|
| 86 |
+
type=str,
|
| 87 |
+
default=None,
|
| 88 |
+
required=True,
|
| 89 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 90 |
+
)
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--tokenizer_name",
|
| 93 |
+
type=str,
|
| 94 |
+
default=None,
|
| 95 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument(
|
| 98 |
+
"--instance_data_dir",
|
| 99 |
+
type=str,
|
| 100 |
+
default=None,
|
| 101 |
+
required=True,
|
| 102 |
+
help="A folder containing the training data of instance images.",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument(
|
| 105 |
+
"--class_data_dir",
|
| 106 |
+
type=str,
|
| 107 |
+
default=None,
|
| 108 |
+
required=False,
|
| 109 |
+
help="A folder containing the training data of class images.",
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--instance_prompt",
|
| 113 |
+
type=str,
|
| 114 |
+
default=None,
|
| 115 |
+
help="The prompt with identifier specifying the instance",
|
| 116 |
+
)
|
| 117 |
+
parser.add_argument(
|
| 118 |
+
"--class_prompt",
|
| 119 |
+
type=str,
|
| 120 |
+
default=None,
|
| 121 |
+
help="The prompt to specify images in the same class as provided instance images.",
|
| 122 |
+
)
|
| 123 |
+
parser.add_argument(
|
| 124 |
+
"--with_prior_preservation",
|
| 125 |
+
default=False,
|
| 126 |
+
action="store_true",
|
| 127 |
+
help="Flag to add prior preservation loss.",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
|
| 130 |
+
parser.add_argument(
|
| 131 |
+
"--num_class_images",
|
| 132 |
+
type=int,
|
| 133 |
+
default=100,
|
| 134 |
+
help=(
|
| 135 |
+
"Minimal class images for prior preservation loss. If not have enough images, additional images will be"
|
| 136 |
+
" sampled with class_prompt."
|
| 137 |
+
),
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--output_dir",
|
| 141 |
+
type=str,
|
| 142 |
+
default="text-inversion-model",
|
| 143 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--resolution",
|
| 148 |
+
type=int,
|
| 149 |
+
default=512,
|
| 150 |
+
help=(
|
| 151 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 152 |
+
" resolution"
|
| 153 |
+
),
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument(
|
| 156 |
+
"--center_crop",
|
| 157 |
+
default=False,
|
| 158 |
+
action="store_true",
|
| 159 |
+
help=(
|
| 160 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 161 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 167 |
+
)
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 170 |
+
)
|
| 171 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 172 |
+
parser.add_argument(
|
| 173 |
+
"--max_train_steps",
|
| 174 |
+
type=int,
|
| 175 |
+
default=None,
|
| 176 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 177 |
+
)
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--gradient_accumulation_steps",
|
| 180 |
+
type=int,
|
| 181 |
+
default=1,
|
| 182 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--gradient_checkpointing",
|
| 186 |
+
action="store_true",
|
| 187 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 188 |
+
)
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--learning_rate",
|
| 191 |
+
type=float,
|
| 192 |
+
default=5e-6,
|
| 193 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--scale_lr",
|
| 197 |
+
action="store_true",
|
| 198 |
+
default=False,
|
| 199 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 200 |
+
)
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--lr_scheduler",
|
| 203 |
+
type=str,
|
| 204 |
+
default="constant",
|
| 205 |
+
help=(
|
| 206 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 207 |
+
' "constant", "constant_with_warmup"]'
|
| 208 |
+
),
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 215 |
+
)
|
| 216 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 217 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 218 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 219 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 220 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 221 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 222 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--hub_model_id",
|
| 225 |
+
type=str,
|
| 226 |
+
default=None,
|
| 227 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--logging_dir",
|
| 231 |
+
type=str,
|
| 232 |
+
default="logs",
|
| 233 |
+
help=(
|
| 234 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 235 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 236 |
+
),
|
| 237 |
+
)
|
| 238 |
+
parser.add_argument(
|
| 239 |
+
"--mixed_precision",
|
| 240 |
+
type=str,
|
| 241 |
+
default="no",
|
| 242 |
+
choices=["no", "fp16", "bf16"],
|
| 243 |
+
help=(
|
| 244 |
+
"Whether to use mixed precision. Choose"
|
| 245 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 246 |
+
"and an Nvidia Ampere GPU."
|
| 247 |
+
),
|
| 248 |
+
)
|
| 249 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 250 |
+
parser.add_argument(
|
| 251 |
+
"--checkpointing_steps",
|
| 252 |
+
type=int,
|
| 253 |
+
default=500,
|
| 254 |
+
help=(
|
| 255 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 256 |
+
" checkpoints in case they are better than the last checkpoint and are suitable for resuming training"
|
| 257 |
+
" using `--resume_from_checkpoint`."
|
| 258 |
+
),
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"--checkpoints_total_limit",
|
| 262 |
+
type=int,
|
| 263 |
+
default=None,
|
| 264 |
+
help=(
|
| 265 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 266 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 267 |
+
" for more docs"
|
| 268 |
+
),
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--resume_from_checkpoint",
|
| 272 |
+
type=str,
|
| 273 |
+
default=None,
|
| 274 |
+
help=(
|
| 275 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 276 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 277 |
+
),
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
args = parser.parse_args()
|
| 281 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 282 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 283 |
+
args.local_rank = env_local_rank
|
| 284 |
+
|
| 285 |
+
if args.instance_data_dir is None:
|
| 286 |
+
raise ValueError("You must specify a train data directory.")
|
| 287 |
+
|
| 288 |
+
if args.with_prior_preservation:
|
| 289 |
+
if args.class_data_dir is None:
|
| 290 |
+
raise ValueError("You must specify a data directory for class images.")
|
| 291 |
+
if args.class_prompt is None:
|
| 292 |
+
raise ValueError("You must specify prompt for class images.")
|
| 293 |
+
|
| 294 |
+
return args
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class DreamBoothDataset(Dataset):
|
| 298 |
+
"""
|
| 299 |
+
A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
|
| 300 |
+
It pre-processes the images and the tokenizes prompts.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
def __init__(
|
| 304 |
+
self,
|
| 305 |
+
instance_data_root,
|
| 306 |
+
instance_prompt,
|
| 307 |
+
tokenizer,
|
| 308 |
+
class_data_root=None,
|
| 309 |
+
class_prompt=None,
|
| 310 |
+
size=512,
|
| 311 |
+
center_crop=False,
|
| 312 |
+
):
|
| 313 |
+
self.size = size
|
| 314 |
+
self.center_crop = center_crop
|
| 315 |
+
self.tokenizer = tokenizer
|
| 316 |
+
|
| 317 |
+
self.instance_data_root = Path(instance_data_root)
|
| 318 |
+
if not self.instance_data_root.exists():
|
| 319 |
+
raise ValueError("Instance images root doesn't exists.")
|
| 320 |
+
|
| 321 |
+
self.instance_images_path = list(Path(instance_data_root).iterdir())
|
| 322 |
+
self.num_instance_images = len(self.instance_images_path)
|
| 323 |
+
self.instance_prompt = instance_prompt
|
| 324 |
+
self._length = self.num_instance_images
|
| 325 |
+
|
| 326 |
+
if class_data_root is not None:
|
| 327 |
+
self.class_data_root = Path(class_data_root)
|
| 328 |
+
self.class_data_root.mkdir(parents=True, exist_ok=True)
|
| 329 |
+
self.class_images_path = list(self.class_data_root.iterdir())
|
| 330 |
+
self.num_class_images = len(self.class_images_path)
|
| 331 |
+
self._length = max(self.num_class_images, self.num_instance_images)
|
| 332 |
+
self.class_prompt = class_prompt
|
| 333 |
+
else:
|
| 334 |
+
self.class_data_root = None
|
| 335 |
+
|
| 336 |
+
self.image_transforms_resize_and_crop = transforms.Compose(
|
| 337 |
+
[
|
| 338 |
+
transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 339 |
+
transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
|
| 340 |
+
]
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
self.image_transforms = transforms.Compose(
|
| 344 |
+
[
|
| 345 |
+
transforms.ToTensor(),
|
| 346 |
+
transforms.Normalize([0.5], [0.5]),
|
| 347 |
+
]
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
def __len__(self):
|
| 351 |
+
return self._length
|
| 352 |
+
|
| 353 |
+
def __getitem__(self, index):
|
| 354 |
+
example = {}
|
| 355 |
+
instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
|
| 356 |
+
if not instance_image.mode == "RGB":
|
| 357 |
+
instance_image = instance_image.convert("RGB")
|
| 358 |
+
instance_image = self.image_transforms_resize_and_crop(instance_image)
|
| 359 |
+
|
| 360 |
+
example["PIL_images"] = instance_image
|
| 361 |
+
example["instance_images"] = self.image_transforms(instance_image)
|
| 362 |
+
|
| 363 |
+
example["instance_prompt_ids"] = self.tokenizer(
|
| 364 |
+
self.instance_prompt,
|
| 365 |
+
padding="do_not_pad",
|
| 366 |
+
truncation=True,
|
| 367 |
+
max_length=self.tokenizer.model_max_length,
|
| 368 |
+
).input_ids
|
| 369 |
+
|
| 370 |
+
if self.class_data_root:
|
| 371 |
+
class_image = Image.open(self.class_images_path[index % self.num_class_images])
|
| 372 |
+
if not class_image.mode == "RGB":
|
| 373 |
+
class_image = class_image.convert("RGB")
|
| 374 |
+
class_image = self.image_transforms_resize_and_crop(class_image)
|
| 375 |
+
example["class_images"] = self.image_transforms(class_image)
|
| 376 |
+
example["class_PIL_images"] = class_image
|
| 377 |
+
example["class_prompt_ids"] = self.tokenizer(
|
| 378 |
+
self.class_prompt,
|
| 379 |
+
padding="do_not_pad",
|
| 380 |
+
truncation=True,
|
| 381 |
+
max_length=self.tokenizer.model_max_length,
|
| 382 |
+
).input_ids
|
| 383 |
+
|
| 384 |
+
return example
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
class PromptDataset(Dataset):
|
| 388 |
+
"""A simple dataset to prepare the prompts to generate class images on multiple GPUs."""
|
| 389 |
+
|
| 390 |
+
def __init__(self, prompt, num_samples):
|
| 391 |
+
self.prompt = prompt
|
| 392 |
+
self.num_samples = num_samples
|
| 393 |
+
|
| 394 |
+
def __len__(self):
|
| 395 |
+
return self.num_samples
|
| 396 |
+
|
| 397 |
+
def __getitem__(self, index):
|
| 398 |
+
example = {}
|
| 399 |
+
example["prompt"] = self.prompt
|
| 400 |
+
example["index"] = index
|
| 401 |
+
return example
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def main():
|
| 405 |
+
args = parse_args()
|
| 406 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 407 |
+
|
| 408 |
+
project_config = ProjectConfiguration(
|
| 409 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
accelerator = Accelerator(
|
| 413 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 414 |
+
mixed_precision=args.mixed_precision,
|
| 415 |
+
log_with="tensorboard",
|
| 416 |
+
project_config=project_config,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
|
| 420 |
+
# This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
|
| 421 |
+
# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
|
| 422 |
+
if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
"Gradient accumulation is not supported when training the text encoder in distributed training. "
|
| 425 |
+
"Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
if args.seed is not None:
|
| 429 |
+
set_seed(args.seed)
|
| 430 |
+
|
| 431 |
+
if args.with_prior_preservation:
|
| 432 |
+
class_images_dir = Path(args.class_data_dir)
|
| 433 |
+
if not class_images_dir.exists():
|
| 434 |
+
class_images_dir.mkdir(parents=True)
|
| 435 |
+
cur_class_images = len(list(class_images_dir.iterdir()))
|
| 436 |
+
|
| 437 |
+
if cur_class_images < args.num_class_images:
|
| 438 |
+
torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32
|
| 439 |
+
pipeline = StableDiffusionInpaintPipeline.from_pretrained(
|
| 440 |
+
args.pretrained_model_name_or_path, torch_dtype=torch_dtype, safety_checker=None
|
| 441 |
+
)
|
| 442 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 443 |
+
|
| 444 |
+
num_new_images = args.num_class_images - cur_class_images
|
| 445 |
+
logger.info(f"Number of class images to sample: {num_new_images}.")
|
| 446 |
+
|
| 447 |
+
sample_dataset = PromptDataset(args.class_prompt, num_new_images)
|
| 448 |
+
sample_dataloader = torch.utils.data.DataLoader(
|
| 449 |
+
sample_dataset, batch_size=args.sample_batch_size, num_workers=1
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
sample_dataloader = accelerator.prepare(sample_dataloader)
|
| 453 |
+
pipeline.to(accelerator.device)
|
| 454 |
+
transform_to_pil = transforms.ToPILImage()
|
| 455 |
+
for example in tqdm(
|
| 456 |
+
sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
|
| 457 |
+
):
|
| 458 |
+
bsz = len(example["prompt"])
|
| 459 |
+
fake_images = torch.rand((3, args.resolution, args.resolution))
|
| 460 |
+
transform_to_pil = transforms.ToPILImage()
|
| 461 |
+
fake_pil_images = transform_to_pil(fake_images)
|
| 462 |
+
|
| 463 |
+
fake_mask = random_mask((args.resolution, args.resolution), ratio=1, mask_full_image=True)
|
| 464 |
+
|
| 465 |
+
images = pipeline(prompt=example["prompt"], mask_image=fake_mask, image=fake_pil_images).images
|
| 466 |
+
|
| 467 |
+
for i, image in enumerate(images):
|
| 468 |
+
hash_image = insecure_hashlib.sha1(image.tobytes()).hexdigest()
|
| 469 |
+
image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
|
| 470 |
+
image.save(image_filename)
|
| 471 |
+
|
| 472 |
+
del pipeline
|
| 473 |
+
if torch.cuda.is_available():
|
| 474 |
+
torch.cuda.empty_cache()
|
| 475 |
+
|
| 476 |
+
# Handle the repository creation
|
| 477 |
+
if accelerator.is_main_process:
|
| 478 |
+
if args.output_dir is not None:
|
| 479 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 480 |
+
|
| 481 |
+
if args.push_to_hub:
|
| 482 |
+
repo_id = create_repo(
|
| 483 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 484 |
+
).repo_id
|
| 485 |
+
|
| 486 |
+
# Load the tokenizer
|
| 487 |
+
if args.tokenizer_name:
|
| 488 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 489 |
+
elif args.pretrained_model_name_or_path:
|
| 490 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 491 |
+
|
| 492 |
+
# Load models and create wrapper for stable diffusion
|
| 493 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 494 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 495 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 496 |
+
|
| 497 |
+
vae.requires_grad_(False)
|
| 498 |
+
if not args.train_text_encoder:
|
| 499 |
+
text_encoder.requires_grad_(False)
|
| 500 |
+
|
| 501 |
+
if args.gradient_checkpointing:
|
| 502 |
+
unet.enable_gradient_checkpointing()
|
| 503 |
+
if args.train_text_encoder:
|
| 504 |
+
text_encoder.gradient_checkpointing_enable()
|
| 505 |
+
|
| 506 |
+
if args.scale_lr:
|
| 507 |
+
args.learning_rate = (
|
| 508 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 512 |
+
if args.use_8bit_adam:
|
| 513 |
+
try:
|
| 514 |
+
import bitsandbytes as bnb
|
| 515 |
+
except ImportError:
|
| 516 |
+
raise ImportError(
|
| 517 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 521 |
+
else:
|
| 522 |
+
optimizer_class = torch.optim.AdamW
|
| 523 |
+
|
| 524 |
+
params_to_optimize = (
|
| 525 |
+
itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
|
| 526 |
+
)
|
| 527 |
+
optimizer = optimizer_class(
|
| 528 |
+
params_to_optimize,
|
| 529 |
+
lr=args.learning_rate,
|
| 530 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 531 |
+
weight_decay=args.adam_weight_decay,
|
| 532 |
+
eps=args.adam_epsilon,
|
| 533 |
+
)
|
| 534 |
+
|
| 535 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 536 |
+
|
| 537 |
+
train_dataset = DreamBoothDataset(
|
| 538 |
+
instance_data_root=args.instance_data_dir,
|
| 539 |
+
instance_prompt=args.instance_prompt,
|
| 540 |
+
class_data_root=args.class_data_dir if args.with_prior_preservation else None,
|
| 541 |
+
class_prompt=args.class_prompt,
|
| 542 |
+
tokenizer=tokenizer,
|
| 543 |
+
size=args.resolution,
|
| 544 |
+
center_crop=args.center_crop,
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
def collate_fn(examples):
|
| 548 |
+
input_ids = [example["instance_prompt_ids"] for example in examples]
|
| 549 |
+
pixel_values = [example["instance_images"] for example in examples]
|
| 550 |
+
|
| 551 |
+
# Concat class and instance examples for prior preservation.
|
| 552 |
+
# We do this to avoid doing two forward passes.
|
| 553 |
+
if args.with_prior_preservation:
|
| 554 |
+
input_ids += [example["class_prompt_ids"] for example in examples]
|
| 555 |
+
pixel_values += [example["class_images"] for example in examples]
|
| 556 |
+
pior_pil = [example["class_PIL_images"] for example in examples]
|
| 557 |
+
|
| 558 |
+
masks = []
|
| 559 |
+
masked_images = []
|
| 560 |
+
for example in examples:
|
| 561 |
+
pil_image = example["PIL_images"]
|
| 562 |
+
# generate a random mask
|
| 563 |
+
mask = random_mask(pil_image.size, 1, False)
|
| 564 |
+
# prepare mask and masked image
|
| 565 |
+
mask, masked_image = prepare_mask_and_masked_image(pil_image, mask)
|
| 566 |
+
|
| 567 |
+
masks.append(mask)
|
| 568 |
+
masked_images.append(masked_image)
|
| 569 |
+
|
| 570 |
+
if args.with_prior_preservation:
|
| 571 |
+
for pil_image in pior_pil:
|
| 572 |
+
# generate a random mask
|
| 573 |
+
mask = random_mask(pil_image.size, 1, False)
|
| 574 |
+
# prepare mask and masked image
|
| 575 |
+
mask, masked_image = prepare_mask_and_masked_image(pil_image, mask)
|
| 576 |
+
|
| 577 |
+
masks.append(mask)
|
| 578 |
+
masked_images.append(masked_image)
|
| 579 |
+
|
| 580 |
+
pixel_values = torch.stack(pixel_values)
|
| 581 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 582 |
+
|
| 583 |
+
input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids
|
| 584 |
+
masks = torch.stack(masks)
|
| 585 |
+
masked_images = torch.stack(masked_images)
|
| 586 |
+
batch = {"input_ids": input_ids, "pixel_values": pixel_values, "masks": masks, "masked_images": masked_images}
|
| 587 |
+
return batch
|
| 588 |
+
|
| 589 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 590 |
+
train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
# Scheduler and math around the number of training steps.
|
| 594 |
+
overrode_max_train_steps = False
|
| 595 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 596 |
+
if args.max_train_steps is None:
|
| 597 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 598 |
+
overrode_max_train_steps = True
|
| 599 |
+
|
| 600 |
+
lr_scheduler = get_scheduler(
|
| 601 |
+
args.lr_scheduler,
|
| 602 |
+
optimizer=optimizer,
|
| 603 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 604 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
if args.train_text_encoder:
|
| 608 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 609 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 610 |
+
)
|
| 611 |
+
else:
|
| 612 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 613 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 614 |
+
)
|
| 615 |
+
accelerator.register_for_checkpointing(lr_scheduler)
|
| 616 |
+
|
| 617 |
+
weight_dtype = torch.float32
|
| 618 |
+
if args.mixed_precision == "fp16":
|
| 619 |
+
weight_dtype = torch.float16
|
| 620 |
+
elif args.mixed_precision == "bf16":
|
| 621 |
+
weight_dtype = torch.bfloat16
|
| 622 |
+
|
| 623 |
+
# Move text_encode and vae to gpu.
|
| 624 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 625 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 626 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 627 |
+
if not args.train_text_encoder:
|
| 628 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 629 |
+
|
| 630 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 631 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 632 |
+
if overrode_max_train_steps:
|
| 633 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 634 |
+
# Afterwards we recalculate our number of training epochs
|
| 635 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 636 |
+
|
| 637 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 638 |
+
# The trackers initializes automatically on the main process.
|
| 639 |
+
if accelerator.is_main_process:
|
| 640 |
+
accelerator.init_trackers("dreambooth", config=vars(args))
|
| 641 |
+
|
| 642 |
+
# Train!
|
| 643 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 644 |
+
|
| 645 |
+
logger.info("***** Running training *****")
|
| 646 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 647 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 648 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 649 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 650 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 651 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 652 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 653 |
+
global_step = 0
|
| 654 |
+
first_epoch = 0
|
| 655 |
+
|
| 656 |
+
if args.resume_from_checkpoint:
|
| 657 |
+
if args.resume_from_checkpoint != "latest":
|
| 658 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 659 |
+
else:
|
| 660 |
+
# Get the most recent checkpoint
|
| 661 |
+
dirs = os.listdir(args.output_dir)
|
| 662 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 663 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 664 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 665 |
+
|
| 666 |
+
if path is None:
|
| 667 |
+
accelerator.print(
|
| 668 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 669 |
+
)
|
| 670 |
+
args.resume_from_checkpoint = None
|
| 671 |
+
else:
|
| 672 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 673 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 674 |
+
global_step = int(path.split("-")[1])
|
| 675 |
+
|
| 676 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 677 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 678 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 679 |
+
|
| 680 |
+
# Only show the progress bar once on each machine.
|
| 681 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 682 |
+
progress_bar.set_description("Steps")
|
| 683 |
+
|
| 684 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 685 |
+
unet.train()
|
| 686 |
+
for step, batch in enumerate(train_dataloader):
|
| 687 |
+
# Skip steps until we reach the resumed step
|
| 688 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 689 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 690 |
+
progress_bar.update(1)
|
| 691 |
+
continue
|
| 692 |
+
|
| 693 |
+
with accelerator.accumulate(unet):
|
| 694 |
+
# Convert images to latent space
|
| 695 |
+
|
| 696 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 697 |
+
latents = latents * vae.config.scaling_factor
|
| 698 |
+
|
| 699 |
+
# Convert masked images to latent space
|
| 700 |
+
masked_latents = vae.encode(
|
| 701 |
+
batch["masked_images"].reshape(batch["pixel_values"].shape).to(dtype=weight_dtype)
|
| 702 |
+
).latent_dist.sample()
|
| 703 |
+
masked_latents = masked_latents * vae.config.scaling_factor
|
| 704 |
+
|
| 705 |
+
masks = batch["masks"]
|
| 706 |
+
# resize the mask to latents shape as we concatenate the mask to the latents
|
| 707 |
+
mask = torch.stack(
|
| 708 |
+
[
|
| 709 |
+
torch.nn.functional.interpolate(mask, size=(args.resolution // 8, args.resolution // 8))
|
| 710 |
+
for mask in masks
|
| 711 |
+
]
|
| 712 |
+
)
|
| 713 |
+
mask = mask.reshape(-1, 1, args.resolution // 8, args.resolution // 8)
|
| 714 |
+
|
| 715 |
+
# Sample noise that we'll add to the latents
|
| 716 |
+
noise = torch.randn_like(latents)
|
| 717 |
+
bsz = latents.shape[0]
|
| 718 |
+
# Sample a random timestep for each image
|
| 719 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 720 |
+
timesteps = timesteps.long()
|
| 721 |
+
|
| 722 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 723 |
+
# (this is the forward diffusion process)
|
| 724 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 725 |
+
|
| 726 |
+
# concatenate the noised latents with the mask and the masked latents
|
| 727 |
+
latent_model_input = torch.cat([noisy_latents, mask, masked_latents], dim=1)
|
| 728 |
+
|
| 729 |
+
# Get the text embedding for conditioning
|
| 730 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 731 |
+
|
| 732 |
+
# Predict the noise residual
|
| 733 |
+
noise_pred = unet(latent_model_input, timesteps, encoder_hidden_states).sample
|
| 734 |
+
|
| 735 |
+
# Get the target for loss depending on the prediction type
|
| 736 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 737 |
+
target = noise
|
| 738 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 739 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 740 |
+
else:
|
| 741 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 742 |
+
|
| 743 |
+
if args.with_prior_preservation:
|
| 744 |
+
# Chunk the noise and noise_pred into two parts and compute the loss on each part separately.
|
| 745 |
+
noise_pred, noise_pred_prior = torch.chunk(noise_pred, 2, dim=0)
|
| 746 |
+
target, target_prior = torch.chunk(target, 2, dim=0)
|
| 747 |
+
|
| 748 |
+
# Compute instance loss
|
| 749 |
+
loss = F.mse_loss(noise_pred.float(), target.float(), reduction="none").mean([1, 2, 3]).mean()
|
| 750 |
+
|
| 751 |
+
# Compute prior loss
|
| 752 |
+
prior_loss = F.mse_loss(noise_pred_prior.float(), target_prior.float(), reduction="mean")
|
| 753 |
+
|
| 754 |
+
# Add the prior loss to the instance loss.
|
| 755 |
+
loss = loss + args.prior_loss_weight * prior_loss
|
| 756 |
+
else:
|
| 757 |
+
loss = F.mse_loss(noise_pred.float(), target.float(), reduction="mean")
|
| 758 |
+
|
| 759 |
+
accelerator.backward(loss)
|
| 760 |
+
if accelerator.sync_gradients:
|
| 761 |
+
params_to_clip = (
|
| 762 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 763 |
+
if args.train_text_encoder
|
| 764 |
+
else unet.parameters()
|
| 765 |
+
)
|
| 766 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 767 |
+
optimizer.step()
|
| 768 |
+
lr_scheduler.step()
|
| 769 |
+
optimizer.zero_grad()
|
| 770 |
+
|
| 771 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 772 |
+
if accelerator.sync_gradients:
|
| 773 |
+
progress_bar.update(1)
|
| 774 |
+
global_step += 1
|
| 775 |
+
|
| 776 |
+
if global_step % args.checkpointing_steps == 0:
|
| 777 |
+
if accelerator.is_main_process:
|
| 778 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 779 |
+
accelerator.save_state(save_path)
|
| 780 |
+
logger.info(f"Saved state to {save_path}")
|
| 781 |
+
|
| 782 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 783 |
+
progress_bar.set_postfix(**logs)
|
| 784 |
+
accelerator.log(logs, step=global_step)
|
| 785 |
+
|
| 786 |
+
if global_step >= args.max_train_steps:
|
| 787 |
+
break
|
| 788 |
+
|
| 789 |
+
accelerator.wait_for_everyone()
|
| 790 |
+
|
| 791 |
+
# Create the pipeline using using the trained modules and save it.
|
| 792 |
+
if accelerator.is_main_process:
|
| 793 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 794 |
+
args.pretrained_model_name_or_path,
|
| 795 |
+
unet=accelerator.unwrap_model(unet),
|
| 796 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 797 |
+
)
|
| 798 |
+
pipeline.save_pretrained(args.output_dir)
|
| 799 |
+
|
| 800 |
+
if args.push_to_hub:
|
| 801 |
+
upload_folder(
|
| 802 |
+
repo_id=repo_id,
|
| 803 |
+
folder_path=args.output_dir,
|
| 804 |
+
commit_message="End of training",
|
| 805 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
accelerator.end_training()
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
if __name__ == "__main__":
|
| 812 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/dreambooth_inpaint/train_dreambooth_inpaint_lora.py
ADDED
|
@@ -0,0 +1,831 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
import torch.utils.checkpoint
|
| 11 |
+
from accelerate import Accelerator
|
| 12 |
+
from accelerate.logging import get_logger
|
| 13 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 14 |
+
from huggingface_hub import create_repo, upload_folder
|
| 15 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 16 |
+
from PIL import Image, ImageDraw
|
| 17 |
+
from torch.utils.data import Dataset
|
| 18 |
+
from torchvision import transforms
|
| 19 |
+
from tqdm.auto import tqdm
|
| 20 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 21 |
+
|
| 22 |
+
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionInpaintPipeline, UNet2DConditionModel
|
| 23 |
+
from diffusers.loaders import AttnProcsLayers
|
| 24 |
+
from diffusers.models.attention_processor import LoRAAttnProcessor
|
| 25 |
+
from diffusers.optimization import get_scheduler
|
| 26 |
+
from diffusers.utils import check_min_version
|
| 27 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 31 |
+
check_min_version("0.13.0.dev0")
|
| 32 |
+
|
| 33 |
+
logger = get_logger(__name__)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def prepare_mask_and_masked_image(image, mask):
|
| 37 |
+
image = np.array(image.convert("RGB"))
|
| 38 |
+
image = image[None].transpose(0, 3, 1, 2)
|
| 39 |
+
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
|
| 40 |
+
|
| 41 |
+
mask = np.array(mask.convert("L"))
|
| 42 |
+
mask = mask.astype(np.float32) / 255.0
|
| 43 |
+
mask = mask[None, None]
|
| 44 |
+
mask[mask < 0.5] = 0
|
| 45 |
+
mask[mask >= 0.5] = 1
|
| 46 |
+
mask = torch.from_numpy(mask)
|
| 47 |
+
|
| 48 |
+
masked_image = image * (mask < 0.5)
|
| 49 |
+
|
| 50 |
+
return mask, masked_image
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# generate random masks
|
| 54 |
+
def random_mask(im_shape, ratio=1, mask_full_image=False):
|
| 55 |
+
mask = Image.new("L", im_shape, 0)
|
| 56 |
+
draw = ImageDraw.Draw(mask)
|
| 57 |
+
size = (random.randint(0, int(im_shape[0] * ratio)), random.randint(0, int(im_shape[1] * ratio)))
|
| 58 |
+
# use this to always mask the whole image
|
| 59 |
+
if mask_full_image:
|
| 60 |
+
size = (int(im_shape[0] * ratio), int(im_shape[1] * ratio))
|
| 61 |
+
limits = (im_shape[0] - size[0] // 2, im_shape[1] - size[1] // 2)
|
| 62 |
+
center = (random.randint(size[0] // 2, limits[0]), random.randint(size[1] // 2, limits[1]))
|
| 63 |
+
draw_type = random.randint(0, 1)
|
| 64 |
+
if draw_type == 0 or mask_full_image:
|
| 65 |
+
draw.rectangle(
|
| 66 |
+
(center[0] - size[0] // 2, center[1] - size[1] // 2, center[0] + size[0] // 2, center[1] + size[1] // 2),
|
| 67 |
+
fill=255,
|
| 68 |
+
)
|
| 69 |
+
else:
|
| 70 |
+
draw.ellipse(
|
| 71 |
+
(center[0] - size[0] // 2, center[1] - size[1] // 2, center[0] + size[0] // 2, center[1] + size[1] // 2),
|
| 72 |
+
fill=255,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
return mask
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def parse_args():
|
| 79 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--pretrained_model_name_or_path",
|
| 82 |
+
type=str,
|
| 83 |
+
default=None,
|
| 84 |
+
required=True,
|
| 85 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--tokenizer_name",
|
| 89 |
+
type=str,
|
| 90 |
+
default=None,
|
| 91 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 92 |
+
)
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--instance_data_dir",
|
| 95 |
+
type=str,
|
| 96 |
+
default=None,
|
| 97 |
+
required=True,
|
| 98 |
+
help="A folder containing the training data of instance images.",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--class_data_dir",
|
| 102 |
+
type=str,
|
| 103 |
+
default=None,
|
| 104 |
+
required=False,
|
| 105 |
+
help="A folder containing the training data of class images.",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--instance_prompt",
|
| 109 |
+
type=str,
|
| 110 |
+
default=None,
|
| 111 |
+
help="The prompt with identifier specifying the instance",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--class_prompt",
|
| 115 |
+
type=str,
|
| 116 |
+
default=None,
|
| 117 |
+
help="The prompt to specify images in the same class as provided instance images.",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--with_prior_preservation",
|
| 121 |
+
default=False,
|
| 122 |
+
action="store_true",
|
| 123 |
+
help="Flag to add prior preservation loss.",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
|
| 126 |
+
parser.add_argument(
|
| 127 |
+
"--num_class_images",
|
| 128 |
+
type=int,
|
| 129 |
+
default=100,
|
| 130 |
+
help=(
|
| 131 |
+
"Minimal class images for prior preservation loss. If not have enough images, additional images will be"
|
| 132 |
+
" sampled with class_prompt."
|
| 133 |
+
),
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--output_dir",
|
| 137 |
+
type=str,
|
| 138 |
+
default="dreambooth-inpaint-model",
|
| 139 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--resolution",
|
| 144 |
+
type=int,
|
| 145 |
+
default=512,
|
| 146 |
+
help=(
|
| 147 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 148 |
+
" resolution"
|
| 149 |
+
),
|
| 150 |
+
)
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"--center_crop",
|
| 153 |
+
default=False,
|
| 154 |
+
action="store_true",
|
| 155 |
+
help=(
|
| 156 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 157 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 158 |
+
),
|
| 159 |
+
)
|
| 160 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 166 |
+
)
|
| 167 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--max_train_steps",
|
| 170 |
+
type=int,
|
| 171 |
+
default=None,
|
| 172 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--gradient_accumulation_steps",
|
| 176 |
+
type=int,
|
| 177 |
+
default=1,
|
| 178 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--gradient_checkpointing",
|
| 182 |
+
action="store_true",
|
| 183 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 184 |
+
)
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--learning_rate",
|
| 187 |
+
type=float,
|
| 188 |
+
default=5e-6,
|
| 189 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 190 |
+
)
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--scale_lr",
|
| 193 |
+
action="store_true",
|
| 194 |
+
default=False,
|
| 195 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 196 |
+
)
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--lr_scheduler",
|
| 199 |
+
type=str,
|
| 200 |
+
default="constant",
|
| 201 |
+
help=(
|
| 202 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 203 |
+
' "constant", "constant_with_warmup"]'
|
| 204 |
+
),
|
| 205 |
+
)
|
| 206 |
+
parser.add_argument(
|
| 207 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 208 |
+
)
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 211 |
+
)
|
| 212 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 213 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 214 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 215 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 216 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 217 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 218 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--hub_model_id",
|
| 221 |
+
type=str,
|
| 222 |
+
default=None,
|
| 223 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--logging_dir",
|
| 227 |
+
type=str,
|
| 228 |
+
default="logs",
|
| 229 |
+
help=(
|
| 230 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 231 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 232 |
+
),
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument(
|
| 235 |
+
"--mixed_precision",
|
| 236 |
+
type=str,
|
| 237 |
+
default="no",
|
| 238 |
+
choices=["no", "fp16", "bf16"],
|
| 239 |
+
help=(
|
| 240 |
+
"Whether to use mixed precision. Choose"
|
| 241 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 242 |
+
"and an Nvidia Ampere GPU."
|
| 243 |
+
),
|
| 244 |
+
)
|
| 245 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--checkpointing_steps",
|
| 248 |
+
type=int,
|
| 249 |
+
default=500,
|
| 250 |
+
help=(
|
| 251 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 252 |
+
" checkpoints in case they are better than the last checkpoint and are suitable for resuming training"
|
| 253 |
+
" using `--resume_from_checkpoint`."
|
| 254 |
+
),
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
"--checkpoints_total_limit",
|
| 258 |
+
type=int,
|
| 259 |
+
default=None,
|
| 260 |
+
help=(
|
| 261 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 262 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 263 |
+
" for more docs"
|
| 264 |
+
),
|
| 265 |
+
)
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
"--resume_from_checkpoint",
|
| 268 |
+
type=str,
|
| 269 |
+
default=None,
|
| 270 |
+
help=(
|
| 271 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 272 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 273 |
+
),
|
| 274 |
+
)
|
| 275 |
+
parser.add_argument(
|
| 276 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
args = parser.parse_args()
|
| 280 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 281 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 282 |
+
args.local_rank = env_local_rank
|
| 283 |
+
|
| 284 |
+
if args.instance_data_dir is None:
|
| 285 |
+
raise ValueError("You must specify a train data directory.")
|
| 286 |
+
|
| 287 |
+
if args.with_prior_preservation:
|
| 288 |
+
if args.class_data_dir is None:
|
| 289 |
+
raise ValueError("You must specify a data directory for class images.")
|
| 290 |
+
if args.class_prompt is None:
|
| 291 |
+
raise ValueError("You must specify prompt for class images.")
|
| 292 |
+
|
| 293 |
+
return args
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class DreamBoothDataset(Dataset):
|
| 297 |
+
"""
|
| 298 |
+
A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
|
| 299 |
+
It pre-processes the images and the tokenizes prompts.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def __init__(
|
| 303 |
+
self,
|
| 304 |
+
instance_data_root,
|
| 305 |
+
instance_prompt,
|
| 306 |
+
tokenizer,
|
| 307 |
+
class_data_root=None,
|
| 308 |
+
class_prompt=None,
|
| 309 |
+
size=512,
|
| 310 |
+
center_crop=False,
|
| 311 |
+
):
|
| 312 |
+
self.size = size
|
| 313 |
+
self.center_crop = center_crop
|
| 314 |
+
self.tokenizer = tokenizer
|
| 315 |
+
|
| 316 |
+
self.instance_data_root = Path(instance_data_root)
|
| 317 |
+
if not self.instance_data_root.exists():
|
| 318 |
+
raise ValueError("Instance images root doesn't exists.")
|
| 319 |
+
|
| 320 |
+
self.instance_images_path = list(Path(instance_data_root).iterdir())
|
| 321 |
+
self.num_instance_images = len(self.instance_images_path)
|
| 322 |
+
self.instance_prompt = instance_prompt
|
| 323 |
+
self._length = self.num_instance_images
|
| 324 |
+
|
| 325 |
+
if class_data_root is not None:
|
| 326 |
+
self.class_data_root = Path(class_data_root)
|
| 327 |
+
self.class_data_root.mkdir(parents=True, exist_ok=True)
|
| 328 |
+
self.class_images_path = list(self.class_data_root.iterdir())
|
| 329 |
+
self.num_class_images = len(self.class_images_path)
|
| 330 |
+
self._length = max(self.num_class_images, self.num_instance_images)
|
| 331 |
+
self.class_prompt = class_prompt
|
| 332 |
+
else:
|
| 333 |
+
self.class_data_root = None
|
| 334 |
+
|
| 335 |
+
self.image_transforms_resize_and_crop = transforms.Compose(
|
| 336 |
+
[
|
| 337 |
+
transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 338 |
+
transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
|
| 339 |
+
]
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
self.image_transforms = transforms.Compose(
|
| 343 |
+
[
|
| 344 |
+
transforms.ToTensor(),
|
| 345 |
+
transforms.Normalize([0.5], [0.5]),
|
| 346 |
+
]
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
def __len__(self):
|
| 350 |
+
return self._length
|
| 351 |
+
|
| 352 |
+
def __getitem__(self, index):
|
| 353 |
+
example = {}
|
| 354 |
+
instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
|
| 355 |
+
if not instance_image.mode == "RGB":
|
| 356 |
+
instance_image = instance_image.convert("RGB")
|
| 357 |
+
instance_image = self.image_transforms_resize_and_crop(instance_image)
|
| 358 |
+
|
| 359 |
+
example["PIL_images"] = instance_image
|
| 360 |
+
example["instance_images"] = self.image_transforms(instance_image)
|
| 361 |
+
|
| 362 |
+
example["instance_prompt_ids"] = self.tokenizer(
|
| 363 |
+
self.instance_prompt,
|
| 364 |
+
padding="do_not_pad",
|
| 365 |
+
truncation=True,
|
| 366 |
+
max_length=self.tokenizer.model_max_length,
|
| 367 |
+
).input_ids
|
| 368 |
+
|
| 369 |
+
if self.class_data_root:
|
| 370 |
+
class_image = Image.open(self.class_images_path[index % self.num_class_images])
|
| 371 |
+
if not class_image.mode == "RGB":
|
| 372 |
+
class_image = class_image.convert("RGB")
|
| 373 |
+
class_image = self.image_transforms_resize_and_crop(class_image)
|
| 374 |
+
example["class_images"] = self.image_transforms(class_image)
|
| 375 |
+
example["class_PIL_images"] = class_image
|
| 376 |
+
example["class_prompt_ids"] = self.tokenizer(
|
| 377 |
+
self.class_prompt,
|
| 378 |
+
padding="do_not_pad",
|
| 379 |
+
truncation=True,
|
| 380 |
+
max_length=self.tokenizer.model_max_length,
|
| 381 |
+
).input_ids
|
| 382 |
+
|
| 383 |
+
return example
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class PromptDataset(Dataset):
|
| 387 |
+
"""A simple dataset to prepare the prompts to generate class images on multiple GPUs."""
|
| 388 |
+
|
| 389 |
+
def __init__(self, prompt, num_samples):
|
| 390 |
+
self.prompt = prompt
|
| 391 |
+
self.num_samples = num_samples
|
| 392 |
+
|
| 393 |
+
def __len__(self):
|
| 394 |
+
return self.num_samples
|
| 395 |
+
|
| 396 |
+
def __getitem__(self, index):
|
| 397 |
+
example = {}
|
| 398 |
+
example["prompt"] = self.prompt
|
| 399 |
+
example["index"] = index
|
| 400 |
+
return example
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def main():
|
| 404 |
+
args = parse_args()
|
| 405 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 406 |
+
|
| 407 |
+
accelerator_project_config = ProjectConfiguration(
|
| 408 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
accelerator = Accelerator(
|
| 412 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 413 |
+
mixed_precision=args.mixed_precision,
|
| 414 |
+
log_with="tensorboard",
|
| 415 |
+
project_config=accelerator_project_config,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
|
| 419 |
+
# This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
|
| 420 |
+
# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
|
| 421 |
+
if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
|
| 422 |
+
raise ValueError(
|
| 423 |
+
"Gradient accumulation is not supported when training the text encoder in distributed training. "
|
| 424 |
+
"Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if args.seed is not None:
|
| 428 |
+
set_seed(args.seed)
|
| 429 |
+
|
| 430 |
+
if args.with_prior_preservation:
|
| 431 |
+
class_images_dir = Path(args.class_data_dir)
|
| 432 |
+
if not class_images_dir.exists():
|
| 433 |
+
class_images_dir.mkdir(parents=True)
|
| 434 |
+
cur_class_images = len(list(class_images_dir.iterdir()))
|
| 435 |
+
|
| 436 |
+
if cur_class_images < args.num_class_images:
|
| 437 |
+
torch_dtype = torch.float16 if accelerator.device.type == "cuda" else torch.float32
|
| 438 |
+
pipeline = StableDiffusionInpaintPipeline.from_pretrained(
|
| 439 |
+
args.pretrained_model_name_or_path, torch_dtype=torch_dtype, safety_checker=None
|
| 440 |
+
)
|
| 441 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 442 |
+
|
| 443 |
+
num_new_images = args.num_class_images - cur_class_images
|
| 444 |
+
logger.info(f"Number of class images to sample: {num_new_images}.")
|
| 445 |
+
|
| 446 |
+
sample_dataset = PromptDataset(args.class_prompt, num_new_images)
|
| 447 |
+
sample_dataloader = torch.utils.data.DataLoader(
|
| 448 |
+
sample_dataset, batch_size=args.sample_batch_size, num_workers=1
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
sample_dataloader = accelerator.prepare(sample_dataloader)
|
| 452 |
+
pipeline.to(accelerator.device)
|
| 453 |
+
transform_to_pil = transforms.ToPILImage()
|
| 454 |
+
for example in tqdm(
|
| 455 |
+
sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
|
| 456 |
+
):
|
| 457 |
+
bsz = len(example["prompt"])
|
| 458 |
+
fake_images = torch.rand((3, args.resolution, args.resolution))
|
| 459 |
+
transform_to_pil = transforms.ToPILImage()
|
| 460 |
+
fake_pil_images = transform_to_pil(fake_images)
|
| 461 |
+
|
| 462 |
+
fake_mask = random_mask((args.resolution, args.resolution), ratio=1, mask_full_image=True)
|
| 463 |
+
|
| 464 |
+
images = pipeline(prompt=example["prompt"], mask_image=fake_mask, image=fake_pil_images).images
|
| 465 |
+
|
| 466 |
+
for i, image in enumerate(images):
|
| 467 |
+
hash_image = insecure_hashlib.sha1(image.tobytes()).hexdigest()
|
| 468 |
+
image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
|
| 469 |
+
image.save(image_filename)
|
| 470 |
+
|
| 471 |
+
del pipeline
|
| 472 |
+
if torch.cuda.is_available():
|
| 473 |
+
torch.cuda.empty_cache()
|
| 474 |
+
|
| 475 |
+
# Handle the repository creation
|
| 476 |
+
if accelerator.is_main_process:
|
| 477 |
+
if args.output_dir is not None:
|
| 478 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 479 |
+
|
| 480 |
+
if args.push_to_hub:
|
| 481 |
+
repo_id = create_repo(
|
| 482 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 483 |
+
).repo_id
|
| 484 |
+
|
| 485 |
+
# Load the tokenizer
|
| 486 |
+
if args.tokenizer_name:
|
| 487 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 488 |
+
elif args.pretrained_model_name_or_path:
|
| 489 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 490 |
+
|
| 491 |
+
# Load models and create wrapper for stable diffusion
|
| 492 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 493 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 494 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 495 |
+
|
| 496 |
+
# We only train the additional adapter LoRA layers
|
| 497 |
+
vae.requires_grad_(False)
|
| 498 |
+
text_encoder.requires_grad_(False)
|
| 499 |
+
unet.requires_grad_(False)
|
| 500 |
+
|
| 501 |
+
weight_dtype = torch.float32
|
| 502 |
+
if args.mixed_precision == "fp16":
|
| 503 |
+
weight_dtype = torch.float16
|
| 504 |
+
elif args.mixed_precision == "bf16":
|
| 505 |
+
weight_dtype = torch.bfloat16
|
| 506 |
+
|
| 507 |
+
# Move text_encode and vae to gpu.
|
| 508 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 509 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 510 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 511 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 512 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 513 |
+
|
| 514 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 515 |
+
if is_xformers_available():
|
| 516 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 517 |
+
else:
|
| 518 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 519 |
+
|
| 520 |
+
# now we will add new LoRA weights to the attention layers
|
| 521 |
+
# It's important to realize here how many attention weights will be added and of which sizes
|
| 522 |
+
# The sizes of the attention layers consist only of two different variables:
|
| 523 |
+
# 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`.
|
| 524 |
+
# 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`.
|
| 525 |
+
|
| 526 |
+
# Let's first see how many attention processors we will have to set.
|
| 527 |
+
# For Stable Diffusion, it should be equal to:
|
| 528 |
+
# - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12
|
| 529 |
+
# - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2
|
| 530 |
+
# - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18
|
| 531 |
+
# => 32 layers
|
| 532 |
+
|
| 533 |
+
# Set correct lora layers
|
| 534 |
+
lora_attn_procs = {}
|
| 535 |
+
for name in unet.attn_processors.keys():
|
| 536 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 537 |
+
if name.startswith("mid_block"):
|
| 538 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 539 |
+
elif name.startswith("up_blocks"):
|
| 540 |
+
block_id = int(name[len("up_blocks.")])
|
| 541 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 542 |
+
elif name.startswith("down_blocks"):
|
| 543 |
+
block_id = int(name[len("down_blocks.")])
|
| 544 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 545 |
+
|
| 546 |
+
lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
|
| 547 |
+
|
| 548 |
+
unet.set_attn_processor(lora_attn_procs)
|
| 549 |
+
lora_layers = AttnProcsLayers(unet.attn_processors)
|
| 550 |
+
|
| 551 |
+
accelerator.register_for_checkpointing(lora_layers)
|
| 552 |
+
|
| 553 |
+
if args.scale_lr:
|
| 554 |
+
args.learning_rate = (
|
| 555 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 559 |
+
if args.use_8bit_adam:
|
| 560 |
+
try:
|
| 561 |
+
import bitsandbytes as bnb
|
| 562 |
+
except ImportError:
|
| 563 |
+
raise ImportError(
|
| 564 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 568 |
+
else:
|
| 569 |
+
optimizer_class = torch.optim.AdamW
|
| 570 |
+
|
| 571 |
+
optimizer = optimizer_class(
|
| 572 |
+
lora_layers.parameters(),
|
| 573 |
+
lr=args.learning_rate,
|
| 574 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 575 |
+
weight_decay=args.adam_weight_decay,
|
| 576 |
+
eps=args.adam_epsilon,
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 580 |
+
|
| 581 |
+
train_dataset = DreamBoothDataset(
|
| 582 |
+
instance_data_root=args.instance_data_dir,
|
| 583 |
+
instance_prompt=args.instance_prompt,
|
| 584 |
+
class_data_root=args.class_data_dir if args.with_prior_preservation else None,
|
| 585 |
+
class_prompt=args.class_prompt,
|
| 586 |
+
tokenizer=tokenizer,
|
| 587 |
+
size=args.resolution,
|
| 588 |
+
center_crop=args.center_crop,
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
def collate_fn(examples):
|
| 592 |
+
input_ids = [example["instance_prompt_ids"] for example in examples]
|
| 593 |
+
pixel_values = [example["instance_images"] for example in examples]
|
| 594 |
+
|
| 595 |
+
# Concat class and instance examples for prior preservation.
|
| 596 |
+
# We do this to avoid doing two forward passes.
|
| 597 |
+
if args.with_prior_preservation:
|
| 598 |
+
input_ids += [example["class_prompt_ids"] for example in examples]
|
| 599 |
+
pixel_values += [example["class_images"] for example in examples]
|
| 600 |
+
pior_pil = [example["class_PIL_images"] for example in examples]
|
| 601 |
+
|
| 602 |
+
masks = []
|
| 603 |
+
masked_images = []
|
| 604 |
+
for example in examples:
|
| 605 |
+
pil_image = example["PIL_images"]
|
| 606 |
+
# generate a random mask
|
| 607 |
+
mask = random_mask(pil_image.size, 1, False)
|
| 608 |
+
# prepare mask and masked image
|
| 609 |
+
mask, masked_image = prepare_mask_and_masked_image(pil_image, mask)
|
| 610 |
+
|
| 611 |
+
masks.append(mask)
|
| 612 |
+
masked_images.append(masked_image)
|
| 613 |
+
|
| 614 |
+
if args.with_prior_preservation:
|
| 615 |
+
for pil_image in pior_pil:
|
| 616 |
+
# generate a random mask
|
| 617 |
+
mask = random_mask(pil_image.size, 1, False)
|
| 618 |
+
# prepare mask and masked image
|
| 619 |
+
mask, masked_image = prepare_mask_and_masked_image(pil_image, mask)
|
| 620 |
+
|
| 621 |
+
masks.append(mask)
|
| 622 |
+
masked_images.append(masked_image)
|
| 623 |
+
|
| 624 |
+
pixel_values = torch.stack(pixel_values)
|
| 625 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 626 |
+
|
| 627 |
+
input_ids = tokenizer.pad({"input_ids": input_ids}, padding=True, return_tensors="pt").input_ids
|
| 628 |
+
masks = torch.stack(masks)
|
| 629 |
+
masked_images = torch.stack(masked_images)
|
| 630 |
+
batch = {"input_ids": input_ids, "pixel_values": pixel_values, "masks": masks, "masked_images": masked_images}
|
| 631 |
+
return batch
|
| 632 |
+
|
| 633 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 634 |
+
train_dataset, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn
|
| 635 |
+
)
|
| 636 |
+
|
| 637 |
+
# Scheduler and math around the number of training steps.
|
| 638 |
+
overrode_max_train_steps = False
|
| 639 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 640 |
+
if args.max_train_steps is None:
|
| 641 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 642 |
+
overrode_max_train_steps = True
|
| 643 |
+
|
| 644 |
+
lr_scheduler = get_scheduler(
|
| 645 |
+
args.lr_scheduler,
|
| 646 |
+
optimizer=optimizer,
|
| 647 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 648 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
# Prepare everything with our `accelerator`.
|
| 652 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 653 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler
|
| 654 |
+
)
|
| 655 |
+
# accelerator.register_for_checkpointing(lr_scheduler)
|
| 656 |
+
|
| 657 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 658 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 659 |
+
if overrode_max_train_steps:
|
| 660 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 661 |
+
# Afterwards we recalculate our number of training epochs
|
| 662 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 663 |
+
|
| 664 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 665 |
+
# The trackers initializes automatically on the main process.
|
| 666 |
+
if accelerator.is_main_process:
|
| 667 |
+
accelerator.init_trackers("dreambooth-inpaint-lora", config=vars(args))
|
| 668 |
+
|
| 669 |
+
# Train!
|
| 670 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 671 |
+
|
| 672 |
+
logger.info("***** Running training *****")
|
| 673 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 674 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 675 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 676 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 677 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 678 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 679 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 680 |
+
global_step = 0
|
| 681 |
+
first_epoch = 0
|
| 682 |
+
|
| 683 |
+
if args.resume_from_checkpoint:
|
| 684 |
+
if args.resume_from_checkpoint != "latest":
|
| 685 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 686 |
+
else:
|
| 687 |
+
# Get the most recent checkpoint
|
| 688 |
+
dirs = os.listdir(args.output_dir)
|
| 689 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 690 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 691 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 692 |
+
|
| 693 |
+
if path is None:
|
| 694 |
+
accelerator.print(
|
| 695 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 696 |
+
)
|
| 697 |
+
args.resume_from_checkpoint = None
|
| 698 |
+
else:
|
| 699 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 700 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 701 |
+
global_step = int(path.split("-")[1])
|
| 702 |
+
|
| 703 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 704 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 705 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 706 |
+
|
| 707 |
+
# Only show the progress bar once on each machine.
|
| 708 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 709 |
+
progress_bar.set_description("Steps")
|
| 710 |
+
|
| 711 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 712 |
+
unet.train()
|
| 713 |
+
for step, batch in enumerate(train_dataloader):
|
| 714 |
+
# Skip steps until we reach the resumed step
|
| 715 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 716 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 717 |
+
progress_bar.update(1)
|
| 718 |
+
continue
|
| 719 |
+
|
| 720 |
+
with accelerator.accumulate(unet):
|
| 721 |
+
# Convert images to latent space
|
| 722 |
+
|
| 723 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 724 |
+
latents = latents * vae.config.scaling_factor
|
| 725 |
+
|
| 726 |
+
# Convert masked images to latent space
|
| 727 |
+
masked_latents = vae.encode(
|
| 728 |
+
batch["masked_images"].reshape(batch["pixel_values"].shape).to(dtype=weight_dtype)
|
| 729 |
+
).latent_dist.sample()
|
| 730 |
+
masked_latents = masked_latents * vae.config.scaling_factor
|
| 731 |
+
|
| 732 |
+
masks = batch["masks"]
|
| 733 |
+
# resize the mask to latents shape as we concatenate the mask to the latents
|
| 734 |
+
mask = torch.stack(
|
| 735 |
+
[
|
| 736 |
+
torch.nn.functional.interpolate(mask, size=(args.resolution // 8, args.resolution // 8))
|
| 737 |
+
for mask in masks
|
| 738 |
+
]
|
| 739 |
+
).to(dtype=weight_dtype)
|
| 740 |
+
mask = mask.reshape(-1, 1, args.resolution // 8, args.resolution // 8)
|
| 741 |
+
|
| 742 |
+
# Sample noise that we'll add to the latents
|
| 743 |
+
noise = torch.randn_like(latents)
|
| 744 |
+
bsz = latents.shape[0]
|
| 745 |
+
# Sample a random timestep for each image
|
| 746 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 747 |
+
timesteps = timesteps.long()
|
| 748 |
+
|
| 749 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 750 |
+
# (this is the forward diffusion process)
|
| 751 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 752 |
+
|
| 753 |
+
# concatenate the noised latents with the mask and the masked latents
|
| 754 |
+
latent_model_input = torch.cat([noisy_latents, mask, masked_latents], dim=1)
|
| 755 |
+
|
| 756 |
+
# Get the text embedding for conditioning
|
| 757 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 758 |
+
|
| 759 |
+
# Predict the noise residual
|
| 760 |
+
noise_pred = unet(latent_model_input, timesteps, encoder_hidden_states).sample
|
| 761 |
+
|
| 762 |
+
# Get the target for loss depending on the prediction type
|
| 763 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 764 |
+
target = noise
|
| 765 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 766 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 767 |
+
else:
|
| 768 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 769 |
+
|
| 770 |
+
if args.with_prior_preservation:
|
| 771 |
+
# Chunk the noise and noise_pred into two parts and compute the loss on each part separately.
|
| 772 |
+
noise_pred, noise_pred_prior = torch.chunk(noise_pred, 2, dim=0)
|
| 773 |
+
target, target_prior = torch.chunk(target, 2, dim=0)
|
| 774 |
+
|
| 775 |
+
# Compute instance loss
|
| 776 |
+
loss = F.mse_loss(noise_pred.float(), target.float(), reduction="none").mean([1, 2, 3]).mean()
|
| 777 |
+
|
| 778 |
+
# Compute prior loss
|
| 779 |
+
prior_loss = F.mse_loss(noise_pred_prior.float(), target_prior.float(), reduction="mean")
|
| 780 |
+
|
| 781 |
+
# Add the prior loss to the instance loss.
|
| 782 |
+
loss = loss + args.prior_loss_weight * prior_loss
|
| 783 |
+
else:
|
| 784 |
+
loss = F.mse_loss(noise_pred.float(), target.float(), reduction="mean")
|
| 785 |
+
|
| 786 |
+
accelerator.backward(loss)
|
| 787 |
+
if accelerator.sync_gradients:
|
| 788 |
+
params_to_clip = lora_layers.parameters()
|
| 789 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 790 |
+
optimizer.step()
|
| 791 |
+
lr_scheduler.step()
|
| 792 |
+
optimizer.zero_grad()
|
| 793 |
+
|
| 794 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 795 |
+
if accelerator.sync_gradients:
|
| 796 |
+
progress_bar.update(1)
|
| 797 |
+
global_step += 1
|
| 798 |
+
|
| 799 |
+
if global_step % args.checkpointing_steps == 0:
|
| 800 |
+
if accelerator.is_main_process:
|
| 801 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 802 |
+
accelerator.save_state(save_path)
|
| 803 |
+
logger.info(f"Saved state to {save_path}")
|
| 804 |
+
|
| 805 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 806 |
+
progress_bar.set_postfix(**logs)
|
| 807 |
+
accelerator.log(logs, step=global_step)
|
| 808 |
+
|
| 809 |
+
if global_step >= args.max_train_steps:
|
| 810 |
+
break
|
| 811 |
+
|
| 812 |
+
accelerator.wait_for_everyone()
|
| 813 |
+
|
| 814 |
+
# Save the lora layers
|
| 815 |
+
if accelerator.is_main_process:
|
| 816 |
+
unet = unet.to(torch.float32)
|
| 817 |
+
unet.save_attn_procs(args.output_dir)
|
| 818 |
+
|
| 819 |
+
if args.push_to_hub:
|
| 820 |
+
upload_folder(
|
| 821 |
+
repo_id=repo_id,
|
| 822 |
+
folder_path=args.output_dir,
|
| 823 |
+
commit_message="End of training",
|
| 824 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
accelerator.end_training()
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
if __name__ == "__main__":
|
| 831 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/README.md
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## LoRA fine-tuning Flux.1 Dev with quantization
|
| 2 |
+
|
| 3 |
+
> [!NOTE]
|
| 4 |
+
> This example is educational in nature and fixes some arguments to keep things simple. It should act as a reference to build things further.
|
| 5 |
+
|
| 6 |
+
This example shows how to fine-tune [Flux.1 Dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) with LoRA and quantization. We show this by using the [`Norod78/Yarn-art-style`](https://huggingface.co/datasets/Norod78/Yarn-art-style) dataset. Steps below summarize the workflow:
|
| 7 |
+
|
| 8 |
+
* We precompute the text embeddings in `compute_embeddings.py` and serialize them into a parquet file.
|
| 9 |
+
* Even though optional, we load the T5-xxl in NF4 to further reduce the memory foot-print.
|
| 10 |
+
* `train_dreambooth_lora_flux_miniature.py` takes care of training:
|
| 11 |
+
* Since we already precomputed the text embeddings, we don't load the text encoders.
|
| 12 |
+
* We load the VAE and use it to precompute the image latents and we then delete it.
|
| 13 |
+
* Load the Flux transformer, quantize it with the [NF4 datatype](https://huggingface.co/papers/2305.14314) through `bitsandbytes`, prepare it for 4bit training.
|
| 14 |
+
* Add LoRA adapter layers to it and then ensure they are kept in FP32 precision.
|
| 15 |
+
* Train!
|
| 16 |
+
|
| 17 |
+
To run training in a memory-optimized manner, we additionally use:
|
| 18 |
+
|
| 19 |
+
* 8Bit Adam
|
| 20 |
+
* Gradient checkpointing
|
| 21 |
+
|
| 22 |
+
We have tested the scripts on a 24GB 4090. It works on a free-tier Colab Notebook, too, but it's extremely slow.
|
| 23 |
+
|
| 24 |
+
## Training
|
| 25 |
+
|
| 26 |
+
Ensure you have installed the required libraries:
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install -U transformers accelerate bitsandbytes peft datasets
|
| 30 |
+
pip install git+https://github.com/huggingface/diffusers -U
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Now, compute the text embeddings:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
python compute_embeddings.py
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
It should create a file named `embeddings.parquet`. We're then ready to launch training. First, authenticate so that you can access the Flux.1 Dev model:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
hf auth login
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Then launch:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
accelerate launch --config_file=accelerate.yaml \
|
| 49 |
+
train_dreambooth_lora_flux_miniature.py \
|
| 50 |
+
--pretrained_model_name_or_path="black-forest-labs/FLUX.1-dev" \
|
| 51 |
+
--data_df_path="embeddings.parquet" \
|
| 52 |
+
--output_dir="yarn_art_lora_flux_nf4" \
|
| 53 |
+
--mixed_precision="fp16" \
|
| 54 |
+
--use_8bit_adam \
|
| 55 |
+
--weighting_scheme="none" \
|
| 56 |
+
--resolution=1024 \
|
| 57 |
+
--train_batch_size=1 \
|
| 58 |
+
--repeats=1 \
|
| 59 |
+
--learning_rate=1e-4 \
|
| 60 |
+
--guidance_scale=1 \
|
| 61 |
+
--report_to="wandb" \
|
| 62 |
+
--gradient_accumulation_steps=4 \
|
| 63 |
+
--gradient_checkpointing \
|
| 64 |
+
--lr_scheduler="constant" \
|
| 65 |
+
--lr_warmup_steps=0 \
|
| 66 |
+
--cache_latents \
|
| 67 |
+
--rank=4 \
|
| 68 |
+
--max_train_steps=700 \
|
| 69 |
+
--seed="0"
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
We can directly pass a quantized checkpoint path, too:
|
| 73 |
+
|
| 74 |
+
```diff
|
| 75 |
+
+ --quantized_model_path="hf-internal-testing/flux.1-dev-nf4-pkg"
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Depending on the machine, training time will vary but for our case, it was 1.5 hours. It maybe possible to speed this up by using `torch.bfloat16`.
|
| 79 |
+
|
| 80 |
+
We support training with the DeepSpeed Zero2 optimizer, too. To use it, first install DeepSpeed:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
pip install -Uq deepspeed
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
And then launch:
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
accelerate launch --config_file=ds2.yaml \
|
| 90 |
+
train_dreambooth_lora_flux_miniature.py \
|
| 91 |
+
--pretrained_model_name_or_path="black-forest-labs/FLUX.1-dev" \
|
| 92 |
+
--data_df_path="embeddings.parquet" \
|
| 93 |
+
--output_dir="yarn_art_lora_flux_nf4" \
|
| 94 |
+
--mixed_precision="no" \
|
| 95 |
+
--use_8bit_adam \
|
| 96 |
+
--weighting_scheme="none" \
|
| 97 |
+
--resolution=1024 \
|
| 98 |
+
--train_batch_size=1 \
|
| 99 |
+
--repeats=1 \
|
| 100 |
+
--learning_rate=1e-4 \
|
| 101 |
+
--guidance_scale=1 \
|
| 102 |
+
--report_to="wandb" \
|
| 103 |
+
--gradient_accumulation_steps=4 \
|
| 104 |
+
--gradient_checkpointing \
|
| 105 |
+
--lr_scheduler="constant" \
|
| 106 |
+
--lr_warmup_steps=0 \
|
| 107 |
+
--cache_latents \
|
| 108 |
+
--rank=4 \
|
| 109 |
+
--max_train_steps=700 \
|
| 110 |
+
--seed="0"
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## Inference
|
| 114 |
+
|
| 115 |
+
When loading the LoRA params (that were obtained on a quantized base model) and merging them into the base model, it is recommended to first dequantize the base model, merge the LoRA params into it, and then quantize the model again. This is because merging into 4bit quantized models can lead to some rounding errors. Below, we provide an end-to-end example:
|
| 116 |
+
|
| 117 |
+
1. First, load the original model and merge the LoRA params into it:
|
| 118 |
+
|
| 119 |
+
```py
|
| 120 |
+
from diffusers import FluxPipeline
|
| 121 |
+
import torch
|
| 122 |
+
|
| 123 |
+
ckpt_id = "black-forest-labs/FLUX.1-dev"
|
| 124 |
+
pipeline = FluxPipeline.from_pretrained(
|
| 125 |
+
ckpt_id, text_encoder=None, text_encoder_2=None, torch_dtype=torch.float16
|
| 126 |
+
)
|
| 127 |
+
pipeline.load_lora_weights("yarn_art_lora_flux_nf4", weight_name="pytorch_lora_weights.safetensors")
|
| 128 |
+
pipeline.fuse_lora()
|
| 129 |
+
pipeline.unload_lora_weights()
|
| 130 |
+
|
| 131 |
+
pipeline.transformer.save_pretrained("fused_transformer")
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
2. Quantize the model and run inference
|
| 135 |
+
|
| 136 |
+
```py
|
| 137 |
+
from diffusers import AutoPipelineForText2Image, FluxTransformer2DModel, BitsAndBytesConfig
|
| 138 |
+
import torch
|
| 139 |
+
|
| 140 |
+
ckpt_id = "black-forest-labs/FLUX.1-dev"
|
| 141 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 142 |
+
nf4_config = BitsAndBytesConfig(
|
| 143 |
+
load_in_4bit=True,
|
| 144 |
+
bnb_4bit_quant_type="nf4",
|
| 145 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 146 |
+
)
|
| 147 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 148 |
+
"fused_transformer",
|
| 149 |
+
quantization_config=nf4_config,
|
| 150 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 151 |
+
)
|
| 152 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 153 |
+
ckpt_id, transformer=transformer, torch_dtype=bnb_4bit_compute_dtype
|
| 154 |
+
)
|
| 155 |
+
pipeline.enable_model_cpu_offload()
|
| 156 |
+
|
| 157 |
+
image = pipeline(
|
| 158 |
+
"a puppy in a pond, yarn art style", num_inference_steps=28, guidance_scale=3.5, height=768
|
| 159 |
+
).images[0]
|
| 160 |
+
image.save("yarn_merged.png")
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
| Dequantize, merge, quantize | Merging directly into quantized model |
|
| 164 |
+
|-------|-------|
|
| 165 |
+
|  |  |
|
| 166 |
+
|
| 167 |
+
As we can notice the first column result follows the style more closely.
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/accelerate.yaml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
distributed_type: NO
|
| 4 |
+
downcast_bf16: 'no'
|
| 5 |
+
enable_cpu_affinity: true
|
| 6 |
+
gpu_ids: all
|
| 7 |
+
machine_rank: 0
|
| 8 |
+
main_training_function: main
|
| 9 |
+
mixed_precision: bf16
|
| 10 |
+
num_machines: 1
|
| 11 |
+
num_processes: 1
|
| 12 |
+
rdzv_backend: static
|
| 13 |
+
same_network: true
|
| 14 |
+
tpu_env: []
|
| 15 |
+
tpu_use_cluster: false
|
| 16 |
+
tpu_use_sudo: false
|
| 17 |
+
use_cpu: false
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/compute_embeddings.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import torch
|
| 21 |
+
from datasets import load_dataset
|
| 22 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 23 |
+
from tqdm.auto import tqdm
|
| 24 |
+
from transformers import T5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers import FluxPipeline
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
MAX_SEQ_LENGTH = 77
|
| 30 |
+
OUTPUT_PATH = "embeddings.parquet"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def generate_image_hash(image):
|
| 34 |
+
return insecure_hashlib.sha256(image.tobytes()).hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_flux_dev_pipeline():
|
| 38 |
+
id = "black-forest-labs/FLUX.1-dev"
|
| 39 |
+
text_encoder = T5EncoderModel.from_pretrained(id, subfolder="text_encoder_2", load_in_8bit=True, device_map="auto")
|
| 40 |
+
pipeline = FluxPipeline.from_pretrained(
|
| 41 |
+
id, text_encoder_2=text_encoder, transformer=None, vae=None, device_map="balanced"
|
| 42 |
+
)
|
| 43 |
+
return pipeline
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@torch.no_grad()
|
| 47 |
+
def compute_embeddings(pipeline, prompts, max_sequence_length):
|
| 48 |
+
all_prompt_embeds = []
|
| 49 |
+
all_pooled_prompt_embeds = []
|
| 50 |
+
all_text_ids = []
|
| 51 |
+
for prompt in tqdm(prompts, desc="Encoding prompts."):
|
| 52 |
+
(
|
| 53 |
+
prompt_embeds,
|
| 54 |
+
pooled_prompt_embeds,
|
| 55 |
+
text_ids,
|
| 56 |
+
) = pipeline.encode_prompt(prompt=prompt, prompt_2=None, max_sequence_length=max_sequence_length)
|
| 57 |
+
all_prompt_embeds.append(prompt_embeds)
|
| 58 |
+
all_pooled_prompt_embeds.append(pooled_prompt_embeds)
|
| 59 |
+
all_text_ids.append(text_ids)
|
| 60 |
+
|
| 61 |
+
max_memory = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024
|
| 62 |
+
print(f"Max memory allocated: {max_memory:.3f} GB")
|
| 63 |
+
return all_prompt_embeds, all_pooled_prompt_embeds, all_text_ids
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def run(args):
|
| 67 |
+
dataset = load_dataset("Norod78/Yarn-art-style", split="train")
|
| 68 |
+
image_prompts = {generate_image_hash(sample["image"]): sample["text"] for sample in dataset}
|
| 69 |
+
all_prompts = list(image_prompts.values())
|
| 70 |
+
print(f"{len(all_prompts)=}")
|
| 71 |
+
|
| 72 |
+
pipeline = load_flux_dev_pipeline()
|
| 73 |
+
all_prompt_embeds, all_pooled_prompt_embeds, all_text_ids = compute_embeddings(
|
| 74 |
+
pipeline, all_prompts, args.max_sequence_length
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
data = []
|
| 78 |
+
for i, (image_hash, _) in enumerate(image_prompts.items()):
|
| 79 |
+
data.append((image_hash, all_prompt_embeds[i], all_pooled_prompt_embeds[i], all_text_ids[i]))
|
| 80 |
+
print(f"{len(data)=}")
|
| 81 |
+
|
| 82 |
+
# Create a DataFrame
|
| 83 |
+
embedding_cols = ["prompt_embeds", "pooled_prompt_embeds", "text_ids"]
|
| 84 |
+
df = pd.DataFrame(data, columns=["image_hash"] + embedding_cols)
|
| 85 |
+
print(f"{len(df)=}")
|
| 86 |
+
|
| 87 |
+
# Convert embedding lists to arrays (for proper storage in parquet)
|
| 88 |
+
for col in embedding_cols:
|
| 89 |
+
df[col] = df[col].apply(lambda x: x.cpu().numpy().flatten().tolist())
|
| 90 |
+
|
| 91 |
+
# Save the dataframe to a parquet file
|
| 92 |
+
df.to_parquet(args.output_path)
|
| 93 |
+
print(f"Data successfully serialized to {args.output_path}")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
if __name__ == "__main__":
|
| 97 |
+
parser = argparse.ArgumentParser()
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--max_sequence_length",
|
| 100 |
+
type=int,
|
| 101 |
+
default=MAX_SEQ_LENGTH,
|
| 102 |
+
help="Maximum sequence length to use for computing the embeddings. The more the higher computational costs.",
|
| 103 |
+
)
|
| 104 |
+
parser.add_argument("--output_path", type=str, default=OUTPUT_PATH, help="Path to serialize the parquet file.")
|
| 105 |
+
args = parser.parse_args()
|
| 106 |
+
|
| 107 |
+
run(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/ds2.yaml
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
deepspeed_config:
|
| 4 |
+
gradient_accumulation_steps: 1
|
| 5 |
+
gradient_clipping: 1.0
|
| 6 |
+
offload_optimizer_device: cpu
|
| 7 |
+
offload_param_device: cpu
|
| 8 |
+
zero3_init_flag: false
|
| 9 |
+
zero_stage: 2
|
| 10 |
+
distributed_type: DEEPSPEED
|
| 11 |
+
downcast_bf16: 'no'
|
| 12 |
+
enable_cpu_affinity: false
|
| 13 |
+
machine_rank: 0
|
| 14 |
+
main_training_function: main
|
| 15 |
+
mixed_precision: 'no'
|
| 16 |
+
num_machines: 1
|
| 17 |
+
num_processes: 1
|
| 18 |
+
rdzv_backend: static
|
| 19 |
+
same_network: true
|
| 20 |
+
tpu_env: []
|
| 21 |
+
tpu_use_cluster: false
|
| 22 |
+
tpu_use_sudo: false
|
| 23 |
+
use_cpu: false
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/flux_lora_quantization/train_dreambooth_lora_flux_miniature.py
ADDED
|
@@ -0,0 +1,1201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import copy
|
| 19 |
+
import logging
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import random
|
| 23 |
+
import shutil
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
import torch
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
import transformers
|
| 31 |
+
from accelerate import Accelerator, DistributedType
|
| 32 |
+
from accelerate.logging import get_logger
|
| 33 |
+
from accelerate.utils import DistributedDataParallelKwargs, ProjectConfiguration, set_seed
|
| 34 |
+
from datasets import load_dataset
|
| 35 |
+
from huggingface_hub import create_repo, upload_folder
|
| 36 |
+
from huggingface_hub.utils import insecure_hashlib
|
| 37 |
+
from peft import LoraConfig, prepare_model_for_kbit_training, set_peft_model_state_dict
|
| 38 |
+
from peft.utils import get_peft_model_state_dict
|
| 39 |
+
from PIL.ImageOps import exif_transpose
|
| 40 |
+
from torch.utils.data import Dataset
|
| 41 |
+
from torchvision import transforms
|
| 42 |
+
from torchvision.transforms.functional import crop
|
| 43 |
+
from tqdm.auto import tqdm
|
| 44 |
+
|
| 45 |
+
import diffusers
|
| 46 |
+
from diffusers import (
|
| 47 |
+
AutoencoderKL,
|
| 48 |
+
BitsAndBytesConfig,
|
| 49 |
+
FlowMatchEulerDiscreteScheduler,
|
| 50 |
+
FluxPipeline,
|
| 51 |
+
FluxTransformer2DModel,
|
| 52 |
+
)
|
| 53 |
+
from diffusers.optimization import get_scheduler
|
| 54 |
+
from diffusers.training_utils import (
|
| 55 |
+
cast_training_params,
|
| 56 |
+
compute_density_for_timestep_sampling,
|
| 57 |
+
compute_loss_weighting_for_sd3,
|
| 58 |
+
free_memory,
|
| 59 |
+
)
|
| 60 |
+
from diffusers.utils import (
|
| 61 |
+
check_min_version,
|
| 62 |
+
convert_unet_state_dict_to_peft,
|
| 63 |
+
is_wandb_available,
|
| 64 |
+
)
|
| 65 |
+
from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
|
| 66 |
+
from diffusers.utils.torch_utils import is_compiled_module
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if is_wandb_available():
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 73 |
+
check_min_version("0.31.0.dev0")
|
| 74 |
+
|
| 75 |
+
logger = get_logger(__name__)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def save_model_card(
|
| 79 |
+
repo_id: str,
|
| 80 |
+
base_model: str = None,
|
| 81 |
+
instance_prompt=None,
|
| 82 |
+
repo_folder=None,
|
| 83 |
+
quantization_config=None,
|
| 84 |
+
):
|
| 85 |
+
widget_dict = []
|
| 86 |
+
|
| 87 |
+
model_description = f"""
|
| 88 |
+
# Flux DreamBooth LoRA - {repo_id}
|
| 89 |
+
|
| 90 |
+
<Gallery />
|
| 91 |
+
|
| 92 |
+
## Model description
|
| 93 |
+
|
| 94 |
+
These are {repo_id} DreamBooth LoRA weights for {base_model}.
|
| 95 |
+
|
| 96 |
+
The weights were trained using [DreamBooth](https://dreambooth.github.io/) with the [Flux diffusers trainer](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_flux.md).
|
| 97 |
+
|
| 98 |
+
Was LoRA for the text encoder enabled? False.
|
| 99 |
+
|
| 100 |
+
Quantization config:
|
| 101 |
+
|
| 102 |
+
```yaml
|
| 103 |
+
{quantization_config}
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
## Trigger words
|
| 107 |
+
|
| 108 |
+
You should use `{instance_prompt}` to trigger the image generation.
|
| 109 |
+
|
| 110 |
+
## Download model
|
| 111 |
+
|
| 112 |
+
[Download the *.safetensors LoRA]({repo_id}/tree/main) in the Files & versions tab.
|
| 113 |
+
|
| 114 |
+
For more details, including weighting, merging and fusing LoRAs, check the [documentation on loading LoRAs in diffusers](https://huggingface.co/docs/diffusers/main/en/using-diffusers/loading_adapters)
|
| 115 |
+
|
| 116 |
+
## Usage
|
| 117 |
+
|
| 118 |
+
TODO
|
| 119 |
+
|
| 120 |
+
## License
|
| 121 |
+
|
| 122 |
+
Please adhere to the licensing terms as described [here](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md).
|
| 123 |
+
"""
|
| 124 |
+
model_card = load_or_create_model_card(
|
| 125 |
+
repo_id_or_path=repo_id,
|
| 126 |
+
from_training=True,
|
| 127 |
+
license="other",
|
| 128 |
+
base_model=base_model,
|
| 129 |
+
prompt=instance_prompt,
|
| 130 |
+
model_description=model_description,
|
| 131 |
+
widget=widget_dict,
|
| 132 |
+
)
|
| 133 |
+
tags = [
|
| 134 |
+
"text-to-image",
|
| 135 |
+
"diffusers-training",
|
| 136 |
+
"diffusers",
|
| 137 |
+
"lora",
|
| 138 |
+
"flux",
|
| 139 |
+
"flux-diffusers",
|
| 140 |
+
"template:sd-lora",
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
model_card = populate_model_card(model_card, tags=tags)
|
| 144 |
+
model_card.save(os.path.join(repo_folder, "README.md"))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def parse_args(input_args=None):
|
| 148 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--pretrained_model_name_or_path",
|
| 151 |
+
type=str,
|
| 152 |
+
default=None,
|
| 153 |
+
required=True,
|
| 154 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 155 |
+
)
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--quantized_model_path",
|
| 158 |
+
type=str,
|
| 159 |
+
default=None,
|
| 160 |
+
help="Path to the quantized model.",
|
| 161 |
+
)
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--revision",
|
| 164 |
+
type=str,
|
| 165 |
+
default=None,
|
| 166 |
+
required=False,
|
| 167 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--variant",
|
| 171 |
+
type=str,
|
| 172 |
+
default=None,
|
| 173 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--data_df_path",
|
| 177 |
+
type=str,
|
| 178 |
+
default=None,
|
| 179 |
+
help=("Path to the parquet file serialized with compute_embeddings.py."),
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--cache_dir",
|
| 184 |
+
type=str,
|
| 185 |
+
default=None,
|
| 186 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument("--repeats", type=int, default=1, help="How many times to repeat the training data.")
|
| 189 |
+
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--max_sequence_length",
|
| 192 |
+
type=int,
|
| 193 |
+
default=77,
|
| 194 |
+
help="Used for reading the embeddings. Needs to be the same as used during `compute_embeddings.py`.",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--rank",
|
| 199 |
+
type=int,
|
| 200 |
+
default=4,
|
| 201 |
+
help=("The dimension of the LoRA update matrices."),
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
parser.add_argument(
|
| 205 |
+
"--output_dir",
|
| 206 |
+
type=str,
|
| 207 |
+
default="flux-dreambooth-lora-nf4",
|
| 208 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 211 |
+
parser.add_argument(
|
| 212 |
+
"--resolution",
|
| 213 |
+
type=int,
|
| 214 |
+
default=512,
|
| 215 |
+
help=(
|
| 216 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 217 |
+
" resolution"
|
| 218 |
+
),
|
| 219 |
+
)
|
| 220 |
+
parser.add_argument(
|
| 221 |
+
"--center_crop",
|
| 222 |
+
default=False,
|
| 223 |
+
action="store_true",
|
| 224 |
+
help=(
|
| 225 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 226 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 227 |
+
),
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--random_flip",
|
| 231 |
+
action="store_true",
|
| 232 |
+
help="whether to randomly flip images horizontally",
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument(
|
| 235 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
|
| 239 |
+
)
|
| 240 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--max_train_steps",
|
| 243 |
+
type=int,
|
| 244 |
+
default=None,
|
| 245 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 246 |
+
)
|
| 247 |
+
parser.add_argument(
|
| 248 |
+
"--checkpointing_steps",
|
| 249 |
+
type=int,
|
| 250 |
+
default=500,
|
| 251 |
+
help=(
|
| 252 |
+
"Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
|
| 253 |
+
" checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
|
| 254 |
+
" training using `--resume_from_checkpoint`."
|
| 255 |
+
),
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument(
|
| 258 |
+
"--checkpoints_total_limit",
|
| 259 |
+
type=int,
|
| 260 |
+
default=None,
|
| 261 |
+
help=("Max number of checkpoints to store."),
|
| 262 |
+
)
|
| 263 |
+
parser.add_argument(
|
| 264 |
+
"--resume_from_checkpoint",
|
| 265 |
+
type=str,
|
| 266 |
+
default=None,
|
| 267 |
+
help=(
|
| 268 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 269 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 270 |
+
),
|
| 271 |
+
)
|
| 272 |
+
parser.add_argument(
|
| 273 |
+
"--gradient_accumulation_steps",
|
| 274 |
+
type=int,
|
| 275 |
+
default=1,
|
| 276 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 277 |
+
)
|
| 278 |
+
parser.add_argument(
|
| 279 |
+
"--gradient_checkpointing",
|
| 280 |
+
action="store_true",
|
| 281 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 282 |
+
)
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--learning_rate",
|
| 285 |
+
type=float,
|
| 286 |
+
default=1e-4,
|
| 287 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
parser.add_argument(
|
| 291 |
+
"--guidance_scale",
|
| 292 |
+
type=float,
|
| 293 |
+
default=3.5,
|
| 294 |
+
help="the FLUX.1 dev variant is a guidance distilled model",
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--scale_lr",
|
| 299 |
+
action="store_true",
|
| 300 |
+
default=False,
|
| 301 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 302 |
+
)
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--lr_scheduler",
|
| 305 |
+
type=str,
|
| 306 |
+
default="constant",
|
| 307 |
+
help=(
|
| 308 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 309 |
+
' "constant", "constant_with_warmup"]'
|
| 310 |
+
),
|
| 311 |
+
)
|
| 312 |
+
parser.add_argument(
|
| 313 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 314 |
+
)
|
| 315 |
+
parser.add_argument(
|
| 316 |
+
"--lr_num_cycles",
|
| 317 |
+
type=int,
|
| 318 |
+
default=1,
|
| 319 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 320 |
+
)
|
| 321 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 322 |
+
parser.add_argument(
|
| 323 |
+
"--dataloader_num_workers",
|
| 324 |
+
type=int,
|
| 325 |
+
default=0,
|
| 326 |
+
help=(
|
| 327 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 328 |
+
),
|
| 329 |
+
)
|
| 330 |
+
parser.add_argument(
|
| 331 |
+
"--weighting_scheme",
|
| 332 |
+
type=str,
|
| 333 |
+
default="none",
|
| 334 |
+
choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
|
| 335 |
+
help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'),
|
| 336 |
+
)
|
| 337 |
+
parser.add_argument(
|
| 338 |
+
"--logit_mean", type=float, default=0.0, help="mean to use when using the `'logit_normal'` weighting scheme."
|
| 339 |
+
)
|
| 340 |
+
parser.add_argument(
|
| 341 |
+
"--logit_std", type=float, default=1.0, help="std to use when using the `'logit_normal'` weighting scheme."
|
| 342 |
+
)
|
| 343 |
+
parser.add_argument(
|
| 344 |
+
"--mode_scale",
|
| 345 |
+
type=float,
|
| 346 |
+
default=1.29,
|
| 347 |
+
help="Scale of mode weighting scheme. Only effective when using the `'mode'` as the `weighting_scheme`.",
|
| 348 |
+
)
|
| 349 |
+
parser.add_argument(
|
| 350 |
+
"--optimizer",
|
| 351 |
+
type=str,
|
| 352 |
+
default="AdamW",
|
| 353 |
+
choices=["AdamW", "Prodigy", "AdEMAMix"],
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
parser.add_argument(
|
| 357 |
+
"--use_8bit_adam",
|
| 358 |
+
action="store_true",
|
| 359 |
+
help="Whether or not to use 8-bit Adam from bitsandbytes. Ignored if optimizer is not set to AdamW",
|
| 360 |
+
)
|
| 361 |
+
parser.add_argument(
|
| 362 |
+
"--use_8bit_ademamix",
|
| 363 |
+
action="store_true",
|
| 364 |
+
help="Whether or not to use 8-bit AdEMAMix from bitsandbytes.",
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
parser.add_argument(
|
| 368 |
+
"--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam and Prodigy optimizers."
|
| 369 |
+
)
|
| 370 |
+
parser.add_argument(
|
| 371 |
+
"--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam and Prodigy optimizers."
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--prodigy_beta3",
|
| 375 |
+
type=float,
|
| 376 |
+
default=None,
|
| 377 |
+
help="coefficients for computing the Prodigy stepsize using running averages. If set to None, "
|
| 378 |
+
"uses the value of square root of beta2. Ignored if optimizer is adamW",
|
| 379 |
+
)
|
| 380 |
+
parser.add_argument("--prodigy_decouple", type=bool, default=True, help="Use AdamW style decoupled weight decay")
|
| 381 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-04, help="Weight decay to use for unet params")
|
| 382 |
+
|
| 383 |
+
parser.add_argument(
|
| 384 |
+
"--adam_epsilon",
|
| 385 |
+
type=float,
|
| 386 |
+
default=1e-08,
|
| 387 |
+
help="Epsilon value for the Adam optimizer and Prodigy optimizers.",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
parser.add_argument(
|
| 391 |
+
"--prodigy_use_bias_correction",
|
| 392 |
+
type=bool,
|
| 393 |
+
default=True,
|
| 394 |
+
help="Turn on Adam's bias correction. True by default. Ignored if optimizer is adamW",
|
| 395 |
+
)
|
| 396 |
+
parser.add_argument(
|
| 397 |
+
"--prodigy_safeguard_warmup",
|
| 398 |
+
type=bool,
|
| 399 |
+
default=True,
|
| 400 |
+
help="Remove lr from the denominator of D estimate to avoid issues during warm-up stage. True by default. "
|
| 401 |
+
"Ignored if optimizer is adamW",
|
| 402 |
+
)
|
| 403 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 404 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 405 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 406 |
+
parser.add_argument(
|
| 407 |
+
"--hub_model_id",
|
| 408 |
+
type=str,
|
| 409 |
+
default=None,
|
| 410 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 411 |
+
)
|
| 412 |
+
parser.add_argument(
|
| 413 |
+
"--logging_dir",
|
| 414 |
+
type=str,
|
| 415 |
+
default="logs",
|
| 416 |
+
help=(
|
| 417 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 418 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 419 |
+
),
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
parser.add_argument(
|
| 423 |
+
"--cache_latents",
|
| 424 |
+
action="store_true",
|
| 425 |
+
default=False,
|
| 426 |
+
help="Cache the VAE latents",
|
| 427 |
+
)
|
| 428 |
+
parser.add_argument(
|
| 429 |
+
"--report_to",
|
| 430 |
+
type=str,
|
| 431 |
+
default="tensorboard",
|
| 432 |
+
help=(
|
| 433 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 434 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 435 |
+
),
|
| 436 |
+
)
|
| 437 |
+
parser.add_argument(
|
| 438 |
+
"--mixed_precision",
|
| 439 |
+
type=str,
|
| 440 |
+
default=None,
|
| 441 |
+
choices=["no", "fp16", "bf16"],
|
| 442 |
+
help=(
|
| 443 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 444 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 445 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 446 |
+
),
|
| 447 |
+
)
|
| 448 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 449 |
+
|
| 450 |
+
if input_args is not None:
|
| 451 |
+
args = parser.parse_args(input_args)
|
| 452 |
+
else:
|
| 453 |
+
args = parser.parse_args()
|
| 454 |
+
|
| 455 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 456 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 457 |
+
args.local_rank = env_local_rank
|
| 458 |
+
|
| 459 |
+
return args
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
class DreamBoothDataset(Dataset):
|
| 463 |
+
def __init__(
|
| 464 |
+
self,
|
| 465 |
+
data_df_path,
|
| 466 |
+
dataset_name,
|
| 467 |
+
size=1024,
|
| 468 |
+
max_sequence_length=77,
|
| 469 |
+
center_crop=False,
|
| 470 |
+
):
|
| 471 |
+
# Logistics
|
| 472 |
+
self.size = size
|
| 473 |
+
self.center_crop = center_crop
|
| 474 |
+
self.max_sequence_length = max_sequence_length
|
| 475 |
+
|
| 476 |
+
self.data_df_path = Path(data_df_path)
|
| 477 |
+
if not self.data_df_path.exists():
|
| 478 |
+
raise ValueError("`data_df_path` doesn't exists.")
|
| 479 |
+
|
| 480 |
+
# Load images.
|
| 481 |
+
dataset = load_dataset(dataset_name, split="train")
|
| 482 |
+
instance_images = [sample["image"] for sample in dataset]
|
| 483 |
+
image_hashes = [self.generate_image_hash(image) for image in instance_images]
|
| 484 |
+
self.instance_images = instance_images
|
| 485 |
+
self.image_hashes = image_hashes
|
| 486 |
+
|
| 487 |
+
# Image transformations
|
| 488 |
+
self.pixel_values = self.apply_image_transformations(
|
| 489 |
+
instance_images=instance_images, size=size, center_crop=center_crop
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
# Map hashes to embeddings.
|
| 493 |
+
self.data_dict = self.map_image_hash_embedding(data_df_path=data_df_path)
|
| 494 |
+
|
| 495 |
+
self.num_instance_images = len(instance_images)
|
| 496 |
+
self._length = self.num_instance_images
|
| 497 |
+
|
| 498 |
+
def __len__(self):
|
| 499 |
+
return self._length
|
| 500 |
+
|
| 501 |
+
def __getitem__(self, index):
|
| 502 |
+
example = {}
|
| 503 |
+
instance_image = self.pixel_values[index % self.num_instance_images]
|
| 504 |
+
image_hash = self.image_hashes[index % self.num_instance_images]
|
| 505 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.data_dict[image_hash]
|
| 506 |
+
example["instance_images"] = instance_image
|
| 507 |
+
example["prompt_embeds"] = prompt_embeds
|
| 508 |
+
example["pooled_prompt_embeds"] = pooled_prompt_embeds
|
| 509 |
+
example["text_ids"] = text_ids
|
| 510 |
+
return example
|
| 511 |
+
|
| 512 |
+
def apply_image_transformations(self, instance_images, size, center_crop):
|
| 513 |
+
pixel_values = []
|
| 514 |
+
|
| 515 |
+
train_resize = transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 516 |
+
train_crop = transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size)
|
| 517 |
+
train_flip = transforms.RandomHorizontalFlip(p=1.0)
|
| 518 |
+
train_transforms = transforms.Compose(
|
| 519 |
+
[
|
| 520 |
+
transforms.ToTensor(),
|
| 521 |
+
transforms.Normalize([0.5], [0.5]),
|
| 522 |
+
]
|
| 523 |
+
)
|
| 524 |
+
for image in instance_images:
|
| 525 |
+
image = exif_transpose(image)
|
| 526 |
+
if not image.mode == "RGB":
|
| 527 |
+
image = image.convert("RGB")
|
| 528 |
+
image = train_resize(image)
|
| 529 |
+
if args.random_flip and random.random() < 0.5:
|
| 530 |
+
# flip
|
| 531 |
+
image = train_flip(image)
|
| 532 |
+
if args.center_crop:
|
| 533 |
+
y1 = max(0, int(round((image.height - args.resolution) / 2.0)))
|
| 534 |
+
x1 = max(0, int(round((image.width - args.resolution) / 2.0)))
|
| 535 |
+
image = train_crop(image)
|
| 536 |
+
else:
|
| 537 |
+
y1, x1, h, w = train_crop.get_params(image, (args.resolution, args.resolution))
|
| 538 |
+
image = crop(image, y1, x1, h, w)
|
| 539 |
+
image = train_transforms(image)
|
| 540 |
+
pixel_values.append(image)
|
| 541 |
+
|
| 542 |
+
return pixel_values
|
| 543 |
+
|
| 544 |
+
def convert_to_torch_tensor(self, embeddings: list):
|
| 545 |
+
prompt_embeds = embeddings[0]
|
| 546 |
+
pooled_prompt_embeds = embeddings[1]
|
| 547 |
+
text_ids = embeddings[2]
|
| 548 |
+
prompt_embeds = np.array(prompt_embeds).reshape(self.max_sequence_length, 4096)
|
| 549 |
+
pooled_prompt_embeds = np.array(pooled_prompt_embeds).reshape(768)
|
| 550 |
+
text_ids = np.array(text_ids).reshape(77, 3)
|
| 551 |
+
return torch.from_numpy(prompt_embeds), torch.from_numpy(pooled_prompt_embeds), torch.from_numpy(text_ids)
|
| 552 |
+
|
| 553 |
+
def map_image_hash_embedding(self, data_df_path):
|
| 554 |
+
hashes_df = pd.read_parquet(data_df_path)
|
| 555 |
+
data_dict = {}
|
| 556 |
+
for i, row in hashes_df.iterrows():
|
| 557 |
+
embeddings = [row["prompt_embeds"], row["pooled_prompt_embeds"], row["text_ids"]]
|
| 558 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = self.convert_to_torch_tensor(embeddings=embeddings)
|
| 559 |
+
data_dict.update({row["image_hash"]: (prompt_embeds, pooled_prompt_embeds, text_ids)})
|
| 560 |
+
return data_dict
|
| 561 |
+
|
| 562 |
+
def generate_image_hash(self, image):
|
| 563 |
+
return insecure_hashlib.sha256(image.tobytes()).hexdigest()
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def collate_fn(examples):
|
| 567 |
+
pixel_values = [example["instance_images"] for example in examples]
|
| 568 |
+
prompt_embeds = [example["prompt_embeds"] for example in examples]
|
| 569 |
+
pooled_prompt_embeds = [example["pooled_prompt_embeds"] for example in examples]
|
| 570 |
+
text_ids = [example["text_ids"] for example in examples]
|
| 571 |
+
|
| 572 |
+
pixel_values = torch.stack(pixel_values)
|
| 573 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 574 |
+
prompt_embeds = torch.stack(prompt_embeds)
|
| 575 |
+
pooled_prompt_embeds = torch.stack(pooled_prompt_embeds)
|
| 576 |
+
text_ids = torch.stack(text_ids)[0] # just 2D tensor
|
| 577 |
+
|
| 578 |
+
batch = {
|
| 579 |
+
"pixel_values": pixel_values,
|
| 580 |
+
"prompt_embeds": prompt_embeds,
|
| 581 |
+
"pooled_prompt_embeds": pooled_prompt_embeds,
|
| 582 |
+
"text_ids": text_ids,
|
| 583 |
+
}
|
| 584 |
+
return batch
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def main(args):
|
| 588 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 589 |
+
raise ValueError(
|
| 590 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 591 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
if torch.backends.mps.is_available() and args.mixed_precision == "bf16":
|
| 595 |
+
# due to pytorch#99272, MPS does not yet support bfloat16.
|
| 596 |
+
raise ValueError(
|
| 597 |
+
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 601 |
+
|
| 602 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 603 |
+
kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
|
| 604 |
+
accelerator = Accelerator(
|
| 605 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 606 |
+
mixed_precision=args.mixed_precision,
|
| 607 |
+
log_with=args.report_to,
|
| 608 |
+
project_config=accelerator_project_config,
|
| 609 |
+
kwargs_handlers=[kwargs],
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
# Disable AMP for MPS.
|
| 613 |
+
if torch.backends.mps.is_available():
|
| 614 |
+
accelerator.native_amp = False
|
| 615 |
+
|
| 616 |
+
if args.report_to == "wandb":
|
| 617 |
+
if not is_wandb_available():
|
| 618 |
+
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
|
| 619 |
+
|
| 620 |
+
# Make one log on every process with the configuration for debugging.
|
| 621 |
+
logging.basicConfig(
|
| 622 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 623 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 624 |
+
level=logging.INFO,
|
| 625 |
+
)
|
| 626 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 627 |
+
if accelerator.is_local_main_process:
|
| 628 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 629 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 630 |
+
else:
|
| 631 |
+
transformers.utils.logging.set_verbosity_error()
|
| 632 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 633 |
+
|
| 634 |
+
# If passed along, set the training seed now.
|
| 635 |
+
if args.seed is not None:
|
| 636 |
+
set_seed(args.seed)
|
| 637 |
+
|
| 638 |
+
# Handle the repository creation
|
| 639 |
+
if accelerator.is_main_process:
|
| 640 |
+
if args.output_dir is not None:
|
| 641 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 642 |
+
|
| 643 |
+
if args.push_to_hub:
|
| 644 |
+
repo_id = create_repo(
|
| 645 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name,
|
| 646 |
+
exist_ok=True,
|
| 647 |
+
).repo_id
|
| 648 |
+
|
| 649 |
+
# Load scheduler and models
|
| 650 |
+
noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
| 651 |
+
args.pretrained_model_name_or_path, subfolder="scheduler"
|
| 652 |
+
)
|
| 653 |
+
noise_scheduler_copy = copy.deepcopy(noise_scheduler)
|
| 654 |
+
vae = AutoencoderKL.from_pretrained(
|
| 655 |
+
args.pretrained_model_name_or_path,
|
| 656 |
+
subfolder="vae",
|
| 657 |
+
revision=args.revision,
|
| 658 |
+
variant=args.variant,
|
| 659 |
+
)
|
| 660 |
+
bnb_4bit_compute_dtype = torch.float32
|
| 661 |
+
if args.mixed_precision == "fp16":
|
| 662 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 663 |
+
elif args.mixed_precision == "bf16":
|
| 664 |
+
bnb_4bit_compute_dtype = torch.bfloat16
|
| 665 |
+
if args.quantized_model_path is not None:
|
| 666 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 667 |
+
args.quantized_model_path,
|
| 668 |
+
subfolder="transformer",
|
| 669 |
+
revision=args.revision,
|
| 670 |
+
variant=args.variant,
|
| 671 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 672 |
+
)
|
| 673 |
+
else:
|
| 674 |
+
nf4_config = BitsAndBytesConfig(
|
| 675 |
+
load_in_4bit=True,
|
| 676 |
+
bnb_4bit_quant_type="nf4",
|
| 677 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 678 |
+
)
|
| 679 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 680 |
+
args.pretrained_model_name_or_path,
|
| 681 |
+
subfolder="transformer",
|
| 682 |
+
revision=args.revision,
|
| 683 |
+
variant=args.variant,
|
| 684 |
+
quantization_config=nf4_config,
|
| 685 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 686 |
+
)
|
| 687 |
+
transformer = prepare_model_for_kbit_training(transformer, use_gradient_checkpointing=False)
|
| 688 |
+
|
| 689 |
+
# We only train the additional adapter LoRA layers
|
| 690 |
+
transformer.requires_grad_(False)
|
| 691 |
+
vae.requires_grad_(False)
|
| 692 |
+
|
| 693 |
+
# For mixed precision training we cast all non-trainable weights (vae, text_encoder and transformer) to half-precision
|
| 694 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 695 |
+
weight_dtype = torch.float32
|
| 696 |
+
if accelerator.mixed_precision == "fp16":
|
| 697 |
+
weight_dtype = torch.float16
|
| 698 |
+
elif accelerator.mixed_precision == "bf16":
|
| 699 |
+
weight_dtype = torch.bfloat16
|
| 700 |
+
|
| 701 |
+
if torch.backends.mps.is_available() and weight_dtype == torch.bfloat16:
|
| 702 |
+
# due to pytorch#99272, MPS does not yet support bfloat16.
|
| 703 |
+
raise ValueError(
|
| 704 |
+
"Mixed precision training with bfloat16 is not supported on MPS. Please use fp16 (recommended) or fp32 instead."
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 708 |
+
if args.gradient_checkpointing:
|
| 709 |
+
transformer.enable_gradient_checkpointing()
|
| 710 |
+
|
| 711 |
+
# now we will add new LoRA weights to the attention layers
|
| 712 |
+
transformer_lora_config = LoraConfig(
|
| 713 |
+
r=args.rank,
|
| 714 |
+
lora_alpha=args.rank,
|
| 715 |
+
init_lora_weights="gaussian",
|
| 716 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 717 |
+
)
|
| 718 |
+
transformer.add_adapter(transformer_lora_config)
|
| 719 |
+
|
| 720 |
+
def unwrap_model(model):
|
| 721 |
+
model = accelerator.unwrap_model(model)
|
| 722 |
+
model = model._orig_mod if is_compiled_module(model) else model
|
| 723 |
+
return model
|
| 724 |
+
|
| 725 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 726 |
+
def save_model_hook(models, weights, output_dir):
|
| 727 |
+
if accelerator.is_main_process:
|
| 728 |
+
transformer_lora_layers_to_save = None
|
| 729 |
+
|
| 730 |
+
for model in models:
|
| 731 |
+
if isinstance(unwrap_model(model), type(unwrap_model(transformer))):
|
| 732 |
+
model = unwrap_model(model)
|
| 733 |
+
transformer_lora_layers_to_save = get_peft_model_state_dict(model)
|
| 734 |
+
else:
|
| 735 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 736 |
+
|
| 737 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 738 |
+
if weights:
|
| 739 |
+
weights.pop()
|
| 740 |
+
|
| 741 |
+
FluxPipeline.save_lora_weights(
|
| 742 |
+
output_dir,
|
| 743 |
+
transformer_lora_layers=transformer_lora_layers_to_save,
|
| 744 |
+
text_encoder_lora_layers=None,
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
def load_model_hook(models, input_dir):
|
| 748 |
+
transformer_ = None
|
| 749 |
+
|
| 750 |
+
if not accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 751 |
+
while len(models) > 0:
|
| 752 |
+
model = models.pop()
|
| 753 |
+
|
| 754 |
+
if isinstance(model, type(unwrap_model(transformer))):
|
| 755 |
+
transformer_ = model
|
| 756 |
+
else:
|
| 757 |
+
raise ValueError(f"unexpected save model: {model.__class__}")
|
| 758 |
+
else:
|
| 759 |
+
if args.quantized_model_path is not None:
|
| 760 |
+
transformer_ = FluxTransformer2DModel.from_pretrained(
|
| 761 |
+
args.quantized_model_path,
|
| 762 |
+
subfolder="transformer",
|
| 763 |
+
revision=args.revision,
|
| 764 |
+
variant=args.variant,
|
| 765 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 766 |
+
)
|
| 767 |
+
else:
|
| 768 |
+
nf4_config = BitsAndBytesConfig(
|
| 769 |
+
load_in_4bit=True,
|
| 770 |
+
bnb_4bit_quant_type="nf4",
|
| 771 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 772 |
+
)
|
| 773 |
+
transformer_ = FluxTransformer2DModel.from_pretrained(
|
| 774 |
+
args.pretrained_model_name_or_path,
|
| 775 |
+
subfolder="transformer",
|
| 776 |
+
revision=args.revision,
|
| 777 |
+
variant=args.variant,
|
| 778 |
+
quantization_config=nf4_config,
|
| 779 |
+
torch_dtype=bnb_4bit_compute_dtype,
|
| 780 |
+
)
|
| 781 |
+
transformer_ = prepare_model_for_kbit_training(transformer_, use_gradient_checkpointing=False)
|
| 782 |
+
transformer_.add_adapter(transformer_lora_config)
|
| 783 |
+
|
| 784 |
+
lora_state_dict = FluxPipeline.lora_state_dict(input_dir)
|
| 785 |
+
|
| 786 |
+
transformer_state_dict = {
|
| 787 |
+
f"{k.replace('transformer.', '')}": v for k, v in lora_state_dict.items() if k.startswith("transformer.")
|
| 788 |
+
}
|
| 789 |
+
transformer_state_dict = convert_unet_state_dict_to_peft(transformer_state_dict)
|
| 790 |
+
incompatible_keys = set_peft_model_state_dict(transformer_, transformer_state_dict, adapter_name="default")
|
| 791 |
+
if incompatible_keys is not None:
|
| 792 |
+
# check only for unexpected keys
|
| 793 |
+
unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
|
| 794 |
+
if unexpected_keys:
|
| 795 |
+
logger.warning(
|
| 796 |
+
f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
|
| 797 |
+
f" {unexpected_keys}. "
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
# Make sure the trainable params are in float32. This is again needed since the base models
|
| 801 |
+
# are in `weight_dtype`. More details:
|
| 802 |
+
# https://github.com/huggingface/diffusers/pull/6514#discussion_r1449796804
|
| 803 |
+
if args.mixed_precision == "fp16":
|
| 804 |
+
models = [transformer_]
|
| 805 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 806 |
+
cast_training_params(models)
|
| 807 |
+
|
| 808 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 809 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 810 |
+
|
| 811 |
+
if args.scale_lr:
|
| 812 |
+
args.learning_rate = (
|
| 813 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
# Make sure the trainable params are in float32.
|
| 817 |
+
if args.mixed_precision == "fp16":
|
| 818 |
+
models = [transformer]
|
| 819 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 820 |
+
cast_training_params(models, dtype=torch.float32)
|
| 821 |
+
|
| 822 |
+
transformer_lora_parameters = list(filter(lambda p: p.requires_grad, transformer.parameters()))
|
| 823 |
+
|
| 824 |
+
# Optimization parameters
|
| 825 |
+
transformer_parameters_with_lr = {"params": transformer_lora_parameters, "lr": args.learning_rate}
|
| 826 |
+
params_to_optimize = [transformer_parameters_with_lr]
|
| 827 |
+
|
| 828 |
+
# Optimizer creation
|
| 829 |
+
if args.use_8bit_adam and not args.optimizer.lower() == "adamw":
|
| 830 |
+
logger.warning(
|
| 831 |
+
f"use_8bit_adam is ignored when optimizer is not set to 'AdamW'. Optimizer was "
|
| 832 |
+
f"set to {args.optimizer.lower()}"
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
if args.use_8bit_ademamix and not args.optimizer.lower() == "ademamix":
|
| 836 |
+
logger.warning(
|
| 837 |
+
f"use_8bit_ademamix is ignored when optimizer is not set to 'AdEMAMix'. Optimizer was "
|
| 838 |
+
f"set to {args.optimizer.lower()}"
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
if args.optimizer.lower() == "adamw":
|
| 842 |
+
if args.use_8bit_adam:
|
| 843 |
+
try:
|
| 844 |
+
import bitsandbytes as bnb
|
| 845 |
+
except ImportError:
|
| 846 |
+
raise ImportError(
|
| 847 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 851 |
+
else:
|
| 852 |
+
optimizer_class = torch.optim.AdamW
|
| 853 |
+
|
| 854 |
+
optimizer = optimizer_class(
|
| 855 |
+
params_to_optimize,
|
| 856 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 857 |
+
weight_decay=args.adam_weight_decay,
|
| 858 |
+
eps=args.adam_epsilon,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
elif args.optimizer.lower() == "ademamix":
|
| 862 |
+
try:
|
| 863 |
+
import bitsandbytes as bnb
|
| 864 |
+
except ImportError:
|
| 865 |
+
raise ImportError(
|
| 866 |
+
"To use AdEMAMix (or its 8bit variant), please install the bitsandbytes library: `pip install -U bitsandbytes`."
|
| 867 |
+
)
|
| 868 |
+
if args.use_8bit_ademamix:
|
| 869 |
+
optimizer_class = bnb.optim.AdEMAMix8bit
|
| 870 |
+
else:
|
| 871 |
+
optimizer_class = bnb.optim.AdEMAMix
|
| 872 |
+
|
| 873 |
+
optimizer = optimizer_class(params_to_optimize)
|
| 874 |
+
|
| 875 |
+
if args.optimizer.lower() == "prodigy":
|
| 876 |
+
try:
|
| 877 |
+
import prodigyopt
|
| 878 |
+
except ImportError:
|
| 879 |
+
raise ImportError("To use Prodigy, please install the prodigyopt library: `pip install prodigyopt`")
|
| 880 |
+
|
| 881 |
+
optimizer_class = prodigyopt.Prodigy
|
| 882 |
+
|
| 883 |
+
if args.learning_rate <= 0.1:
|
| 884 |
+
logger.warning(
|
| 885 |
+
"Learning rate is too low. When using prodigy, it's generally better to set learning rate around 1.0"
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
optimizer = optimizer_class(
|
| 889 |
+
params_to_optimize,
|
| 890 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 891 |
+
beta3=args.prodigy_beta3,
|
| 892 |
+
weight_decay=args.adam_weight_decay,
|
| 893 |
+
eps=args.adam_epsilon,
|
| 894 |
+
decouple=args.prodigy_decouple,
|
| 895 |
+
use_bias_correction=args.prodigy_use_bias_correction,
|
| 896 |
+
safeguard_warmup=args.prodigy_safeguard_warmup,
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
# Dataset and DataLoaders creation:
|
| 900 |
+
train_dataset = DreamBoothDataset(
|
| 901 |
+
data_df_path=args.data_df_path,
|
| 902 |
+
dataset_name="Norod78/Yarn-art-style",
|
| 903 |
+
size=args.resolution,
|
| 904 |
+
max_sequence_length=args.max_sequence_length,
|
| 905 |
+
center_crop=args.center_crop,
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 909 |
+
train_dataset,
|
| 910 |
+
batch_size=args.train_batch_size,
|
| 911 |
+
shuffle=True,
|
| 912 |
+
collate_fn=collate_fn,
|
| 913 |
+
num_workers=args.dataloader_num_workers,
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
vae_config_shift_factor = vae.config.shift_factor
|
| 917 |
+
vae_config_scaling_factor = vae.config.scaling_factor
|
| 918 |
+
vae_config_block_out_channels = vae.config.block_out_channels
|
| 919 |
+
if args.cache_latents:
|
| 920 |
+
latents_cache = []
|
| 921 |
+
for batch in tqdm(train_dataloader, desc="Caching latents"):
|
| 922 |
+
with torch.no_grad():
|
| 923 |
+
batch["pixel_values"] = batch["pixel_values"].to(
|
| 924 |
+
accelerator.device, non_blocking=True, dtype=weight_dtype
|
| 925 |
+
)
|
| 926 |
+
latents_cache.append(vae.encode(batch["pixel_values"]).latent_dist)
|
| 927 |
+
|
| 928 |
+
del vae
|
| 929 |
+
free_memory()
|
| 930 |
+
|
| 931 |
+
# Scheduler and math around the number of training steps.
|
| 932 |
+
overrode_max_train_steps = False
|
| 933 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 934 |
+
if args.max_train_steps is None:
|
| 935 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 936 |
+
overrode_max_train_steps = True
|
| 937 |
+
|
| 938 |
+
lr_scheduler = get_scheduler(
|
| 939 |
+
args.lr_scheduler,
|
| 940 |
+
optimizer=optimizer,
|
| 941 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 942 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 943 |
+
num_cycles=args.lr_num_cycles,
|
| 944 |
+
power=args.lr_power,
|
| 945 |
+
)
|
| 946 |
+
|
| 947 |
+
# Prepare everything with our `accelerator`.
|
| 948 |
+
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 949 |
+
transformer, optimizer, train_dataloader, lr_scheduler
|
| 950 |
+
)
|
| 951 |
+
|
| 952 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 953 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 954 |
+
if overrode_max_train_steps:
|
| 955 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 956 |
+
# Afterwards we recalculate our number of training epochs
|
| 957 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 958 |
+
|
| 959 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 960 |
+
# The trackers initializes automatically on the main process.
|
| 961 |
+
if accelerator.is_main_process:
|
| 962 |
+
tracker_name = "dreambooth-flux-dev-lora-nf4"
|
| 963 |
+
accelerator.init_trackers(tracker_name, config=vars(args))
|
| 964 |
+
|
| 965 |
+
# Train!
|
| 966 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 967 |
+
|
| 968 |
+
logger.info("***** Running training *****")
|
| 969 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 970 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 971 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 972 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 973 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 974 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 975 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 976 |
+
global_step = 0
|
| 977 |
+
first_epoch = 0
|
| 978 |
+
|
| 979 |
+
# Potentially load in the weights and states from a previous save
|
| 980 |
+
if args.resume_from_checkpoint:
|
| 981 |
+
if args.resume_from_checkpoint != "latest":
|
| 982 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 983 |
+
else:
|
| 984 |
+
# Get the mos recent checkpoint
|
| 985 |
+
dirs = os.listdir(args.output_dir)
|
| 986 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 987 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 988 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 989 |
+
|
| 990 |
+
if path is None:
|
| 991 |
+
accelerator.print(
|
| 992 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 993 |
+
)
|
| 994 |
+
args.resume_from_checkpoint = None
|
| 995 |
+
initial_global_step = 0
|
| 996 |
+
else:
|
| 997 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 998 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 999 |
+
global_step = int(path.split("-")[1])
|
| 1000 |
+
|
| 1001 |
+
initial_global_step = global_step
|
| 1002 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 1003 |
+
|
| 1004 |
+
else:
|
| 1005 |
+
initial_global_step = 0
|
| 1006 |
+
|
| 1007 |
+
progress_bar = tqdm(
|
| 1008 |
+
range(0, args.max_train_steps),
|
| 1009 |
+
initial=initial_global_step,
|
| 1010 |
+
desc="Steps",
|
| 1011 |
+
# Only show the progress bar once on each machine.
|
| 1012 |
+
disable=not accelerator.is_local_main_process,
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
|
| 1016 |
+
sigmas = noise_scheduler_copy.sigmas.to(device=accelerator.device, dtype=dtype)
|
| 1017 |
+
schedule_timesteps = noise_scheduler_copy.timesteps.to(accelerator.device)
|
| 1018 |
+
timesteps = timesteps.to(accelerator.device)
|
| 1019 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 1020 |
+
|
| 1021 |
+
sigma = sigmas[step_indices].flatten()
|
| 1022 |
+
while len(sigma.shape) < n_dim:
|
| 1023 |
+
sigma = sigma.unsqueeze(-1)
|
| 1024 |
+
return sigma
|
| 1025 |
+
|
| 1026 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 1027 |
+
transformer.train()
|
| 1028 |
+
|
| 1029 |
+
for step, batch in enumerate(train_dataloader):
|
| 1030 |
+
models_to_accumulate = [transformer]
|
| 1031 |
+
with accelerator.accumulate(models_to_accumulate):
|
| 1032 |
+
# Convert images to latent space
|
| 1033 |
+
if args.cache_latents:
|
| 1034 |
+
model_input = latents_cache[step].sample()
|
| 1035 |
+
else:
|
| 1036 |
+
pixel_values = batch["pixel_values"].to(dtype=vae.dtype)
|
| 1037 |
+
model_input = vae.encode(pixel_values).latent_dist.sample()
|
| 1038 |
+
model_input = (model_input - vae_config_shift_factor) * vae_config_scaling_factor
|
| 1039 |
+
model_input = model_input.to(dtype=weight_dtype)
|
| 1040 |
+
|
| 1041 |
+
vae_scale_factor = 2 ** (len(vae_config_block_out_channels) - 1)
|
| 1042 |
+
|
| 1043 |
+
latent_image_ids = FluxPipeline._prepare_latent_image_ids(
|
| 1044 |
+
model_input.shape[0],
|
| 1045 |
+
model_input.shape[2] // 2,
|
| 1046 |
+
model_input.shape[3] // 2,
|
| 1047 |
+
accelerator.device,
|
| 1048 |
+
weight_dtype,
|
| 1049 |
+
)
|
| 1050 |
+
# Sample noise that we'll add to the latents
|
| 1051 |
+
noise = torch.randn_like(model_input)
|
| 1052 |
+
bsz = model_input.shape[0]
|
| 1053 |
+
|
| 1054 |
+
# Sample a random timestep for each image
|
| 1055 |
+
# for weighting schemes where we sample timesteps non-uniformly
|
| 1056 |
+
u = compute_density_for_timestep_sampling(
|
| 1057 |
+
weighting_scheme=args.weighting_scheme,
|
| 1058 |
+
batch_size=bsz,
|
| 1059 |
+
logit_mean=args.logit_mean,
|
| 1060 |
+
logit_std=args.logit_std,
|
| 1061 |
+
mode_scale=args.mode_scale,
|
| 1062 |
+
)
|
| 1063 |
+
indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
|
| 1064 |
+
timesteps = noise_scheduler_copy.timesteps[indices].to(device=model_input.device)
|
| 1065 |
+
|
| 1066 |
+
# Add noise according to flow matching.
|
| 1067 |
+
# zt = (1 - texp) * x + texp * z1
|
| 1068 |
+
sigmas = get_sigmas(timesteps, n_dim=model_input.ndim, dtype=model_input.dtype)
|
| 1069 |
+
noisy_model_input = (1.0 - sigmas) * model_input + sigmas * noise
|
| 1070 |
+
|
| 1071 |
+
packed_noisy_model_input = FluxPipeline._pack_latents(
|
| 1072 |
+
noisy_model_input,
|
| 1073 |
+
batch_size=model_input.shape[0],
|
| 1074 |
+
num_channels_latents=model_input.shape[1],
|
| 1075 |
+
height=model_input.shape[2],
|
| 1076 |
+
width=model_input.shape[3],
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
# handle guidance
|
| 1080 |
+
if unwrap_model(transformer).config.guidance_embeds:
|
| 1081 |
+
guidance = torch.tensor([args.guidance_scale], device=accelerator.device)
|
| 1082 |
+
guidance = guidance.expand(model_input.shape[0])
|
| 1083 |
+
else:
|
| 1084 |
+
guidance = None
|
| 1085 |
+
|
| 1086 |
+
# Predict the noise
|
| 1087 |
+
prompt_embeds = batch["prompt_embeds"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1088 |
+
pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1089 |
+
text_ids = batch["text_ids"].to(device=accelerator.device, dtype=weight_dtype)
|
| 1090 |
+
model_pred = transformer(
|
| 1091 |
+
hidden_states=packed_noisy_model_input,
|
| 1092 |
+
# YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transformer model (we should not keep it but I want to keep the inputs same for the model for testing)
|
| 1093 |
+
timestep=timesteps / 1000,
|
| 1094 |
+
guidance=guidance,
|
| 1095 |
+
pooled_projections=pooled_prompt_embeds,
|
| 1096 |
+
encoder_hidden_states=prompt_embeds,
|
| 1097 |
+
txt_ids=text_ids,
|
| 1098 |
+
img_ids=latent_image_ids,
|
| 1099 |
+
return_dict=False,
|
| 1100 |
+
)[0]
|
| 1101 |
+
model_pred = FluxPipeline._unpack_latents(
|
| 1102 |
+
model_pred,
|
| 1103 |
+
height=model_input.shape[2] * vae_scale_factor,
|
| 1104 |
+
width=model_input.shape[3] * vae_scale_factor,
|
| 1105 |
+
vae_scale_factor=vae_scale_factor,
|
| 1106 |
+
)
|
| 1107 |
+
|
| 1108 |
+
# these weighting schemes use a uniform timestep sampling
|
| 1109 |
+
# and instead post-weight the loss
|
| 1110 |
+
weighting = compute_loss_weighting_for_sd3(weighting_scheme=args.weighting_scheme, sigmas=sigmas)
|
| 1111 |
+
|
| 1112 |
+
# flow matching loss
|
| 1113 |
+
target = noise - model_input
|
| 1114 |
+
|
| 1115 |
+
# Compute regular loss.
|
| 1116 |
+
loss = torch.mean(
|
| 1117 |
+
(weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
|
| 1118 |
+
1,
|
| 1119 |
+
)
|
| 1120 |
+
loss = loss.mean()
|
| 1121 |
+
accelerator.backward(loss)
|
| 1122 |
+
|
| 1123 |
+
if accelerator.sync_gradients:
|
| 1124 |
+
params_to_clip = transformer.parameters()
|
| 1125 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 1126 |
+
|
| 1127 |
+
optimizer.step()
|
| 1128 |
+
lr_scheduler.step()
|
| 1129 |
+
optimizer.zero_grad()
|
| 1130 |
+
|
| 1131 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1132 |
+
if accelerator.sync_gradients:
|
| 1133 |
+
progress_bar.update(1)
|
| 1134 |
+
global_step += 1
|
| 1135 |
+
|
| 1136 |
+
if accelerator.is_main_process or accelerator.distributed_type == DistributedType.DEEPSPEED:
|
| 1137 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1138 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1139 |
+
if args.checkpoints_total_limit is not None:
|
| 1140 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1141 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1142 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1143 |
+
|
| 1144 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1145 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1146 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1147 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1148 |
+
|
| 1149 |
+
logger.info(
|
| 1150 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1151 |
+
)
|
| 1152 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1153 |
+
|
| 1154 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1155 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1156 |
+
shutil.rmtree(removing_checkpoint)
|
| 1157 |
+
|
| 1158 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1159 |
+
accelerator.save_state(save_path)
|
| 1160 |
+
logger.info(f"Saved state to {save_path}")
|
| 1161 |
+
|
| 1162 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1163 |
+
progress_bar.set_postfix(**logs)
|
| 1164 |
+
accelerator.log(logs, step=global_step)
|
| 1165 |
+
|
| 1166 |
+
if global_step >= args.max_train_steps:
|
| 1167 |
+
break
|
| 1168 |
+
|
| 1169 |
+
# Save the lora layers
|
| 1170 |
+
accelerator.wait_for_everyone()
|
| 1171 |
+
if accelerator.is_main_process:
|
| 1172 |
+
transformer = unwrap_model(transformer)
|
| 1173 |
+
transformer_lora_layers = get_peft_model_state_dict(transformer)
|
| 1174 |
+
|
| 1175 |
+
FluxPipeline.save_lora_weights(
|
| 1176 |
+
save_directory=args.output_dir,
|
| 1177 |
+
transformer_lora_layers=transformer_lora_layers,
|
| 1178 |
+
text_encoder_lora_layers=None,
|
| 1179 |
+
)
|
| 1180 |
+
|
| 1181 |
+
if args.push_to_hub:
|
| 1182 |
+
save_model_card(
|
| 1183 |
+
repo_id,
|
| 1184 |
+
base_model=args.pretrained_model_name_or_path,
|
| 1185 |
+
instance_prompt=None,
|
| 1186 |
+
repo_folder=args.output_dir,
|
| 1187 |
+
quantization_config=transformer.config["quantization_config"],
|
| 1188 |
+
)
|
| 1189 |
+
upload_folder(
|
| 1190 |
+
repo_id=repo_id,
|
| 1191 |
+
folder_path=args.output_dir,
|
| 1192 |
+
commit_message="End of training",
|
| 1193 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1194 |
+
)
|
| 1195 |
+
|
| 1196 |
+
accelerator.end_training()
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
if __name__ == "__main__":
|
| 1200 |
+
args = parse_args()
|
| 1201 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/geodiff/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GeoDiff
|
| 2 |
+
|
| 3 |
+
> [!TIP]
|
| 4 |
+
> This notebook is not actively maintained by the Diffusers team. For any questions or comments, please contact [natolambert](https://twitter.com/natolambert).
|
| 5 |
+
|
| 6 |
+
This is an experimental research notebook demonstrating how to generate stable 3D structures of molecules with [GeoDiff](https://github.com/MinkaiXu/GeoDiff) and Diffusers.
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/geodiff/geodiff_molecule_conformation.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GLIGEN: Open-Set Grounded Text-to-Image Generation
|
| 2 |
+
|
| 3 |
+
These scripts contain the code to prepare the grounding data and train the GLIGEN model on COCO dataset.
|
| 4 |
+
|
| 5 |
+
### Install the requirements
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
conda create -n diffusers python==3.10
|
| 9 |
+
conda activate diffusers
|
| 10 |
+
pip install -r requirements.txt
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
accelerate config
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
Or for a default accelerate configuration without answering questions about your environment
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
accelerate config default
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
Or if your environment doesn't support an interactive shell e.g. a notebook
|
| 26 |
+
|
| 27 |
+
```python
|
| 28 |
+
from accelerate.utils import write_basic_config
|
| 29 |
+
|
| 30 |
+
write_basic_config()
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
### Prepare the training data
|
| 34 |
+
|
| 35 |
+
If you want to make your own grounding data, you need to install the requirements.
|
| 36 |
+
|
| 37 |
+
I used [RAM](https://github.com/xinyu1205/recognize-anything) to tag
|
| 38 |
+
images, [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO/issues?q=refer) to detect objects,
|
| 39 |
+
and [BLIP2](https://huggingface.co/docs/transformers/en/model_doc/blip-2) to caption instances.
|
| 40 |
+
|
| 41 |
+
Only RAM needs to be installed manually:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
pip install git+https://github.com/xinyu1205/recognize-anything.git --no-deps
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Download the pre-trained model:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
hf download --resume-download xinyu1205/recognize_anything_model ram_swin_large_14m.pth
|
| 51 |
+
hf download --resume-download IDEA-Research/grounding-dino-base
|
| 52 |
+
hf download --resume-download Salesforce/blip2-flan-t5-xxl
|
| 53 |
+
hf download --resume-download clip-vit-large-patch14
|
| 54 |
+
hf download --resume-download masterful/gligen-1-4-generation-text-box
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Make the training data on 8 GPUs:
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
torchrun --master_port 17673 --nproc_per_node=8 make_datasets.py \
|
| 61 |
+
--data_root /mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017 \
|
| 62 |
+
--save_root /root/gligen_data \
|
| 63 |
+
--ram_checkpoint /root/.cache/huggingface/hub/models--xinyu1205--recognize_anything_model/snapshots/ebc52dc741e86466202a5ab8ab22eae6e7d48bf1/ram_swin_large_14m.pth
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
You can download the COCO training data from
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
hf download --resume-download Hzzone/GLIGEN_COCO coco_train2017.pth
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
It's in the format of
|
| 73 |
+
|
| 74 |
+
```json
|
| 75 |
+
[
|
| 76 |
+
...
|
| 77 |
+
{
|
| 78 |
+
'file_path': Path,
|
| 79 |
+
'annos': [
|
| 80 |
+
{
|
| 81 |
+
'caption': Instance
|
| 82 |
+
Caption,
|
| 83 |
+
'bbox': bbox
|
| 84 |
+
in
|
| 85 |
+
xyxy,
|
| 86 |
+
'text_embeddings_before_projection': CLIP
|
| 87 |
+
text
|
| 88 |
+
embedding
|
| 89 |
+
before
|
| 90 |
+
linear
|
| 91 |
+
projection
|
| 92 |
+
}
|
| 93 |
+
]
|
| 94 |
+
}
|
| 95 |
+
...
|
| 96 |
+
]
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
### Training commands
|
| 100 |
+
|
| 101 |
+
The training script is heavily based
|
| 102 |
+
on https://github.com/huggingface/diffusers/blob/main/examples/controlnet/train_controlnet.py
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
accelerate launch train_gligen_text.py \
|
| 106 |
+
--data_path /root/data/zhizhonghuang/coco_train2017.pth \
|
| 107 |
+
--image_path /mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017 \
|
| 108 |
+
--train_batch_size 8 \
|
| 109 |
+
--max_train_steps 100000 \
|
| 110 |
+
--checkpointing_steps 1000 \
|
| 111 |
+
--checkpoints_total_limit 10 \
|
| 112 |
+
--learning_rate 5e-5 \
|
| 113 |
+
--dataloader_num_workers 16 \
|
| 114 |
+
--mixed_precision fp16 \
|
| 115 |
+
--report_to wandb \
|
| 116 |
+
--tracker_project_name gligen \
|
| 117 |
+
--output_dir /root/data/zhizhonghuang/ckpt/GLIGEN_Text_Retrain_COCO
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
I trained the model on 8 A100 GPUs for about 11 hours (at least 24GB GPU memory). The generated images will follow the
|
| 121 |
+
layout possibly at 50k iterations.
|
| 122 |
+
|
| 123 |
+
Note that although the pre-trained GLIGEN model has been loaded, the parameters of `fuser` and `position_net` have been reset (see line 420 in `train_gligen_text.py`)
|
| 124 |
+
|
| 125 |
+
The trained model can be downloaded from
|
| 126 |
+
|
| 127 |
+
```bash
|
| 128 |
+
hf download --resume-download Hzzone/GLIGEN_COCO config.json diffusion_pytorch_model.safetensors
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
You can run `demo.ipynb` to visualize the generated images.
|
| 132 |
+
|
| 133 |
+
Example prompts:
|
| 134 |
+
|
| 135 |
+
```python
|
| 136 |
+
prompt = 'A realistic image of landscape scene depicting a green car parking on the left of a blue truck, with a red air balloon and a bird in the sky'
|
| 137 |
+
boxes = [[0.041015625, 0.548828125, 0.453125, 0.859375],
|
| 138 |
+
[0.525390625, 0.552734375, 0.93359375, 0.865234375],
|
| 139 |
+
[0.12890625, 0.015625, 0.412109375, 0.279296875],
|
| 140 |
+
[0.578125, 0.08203125, 0.857421875, 0.27734375]]
|
| 141 |
+
gligen_phrases = ['a green car', 'a blue truck', 'a red air balloon', 'a bird']
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Example images:
|
| 145 |
+

|
| 146 |
+
|
| 147 |
+
### Citation
|
| 148 |
+
|
| 149 |
+
```
|
| 150 |
+
@article{li2023gligen,
|
| 151 |
+
title={GLIGEN: Open-Set Grounded Text-to-Image Generation},
|
| 152 |
+
author={Li, Yuheng and Liu, Haotian and Wu, Qingyang and Mu, Fangzhou and Yang, Jianwei and Gao, Jianfeng and Li, Chunyuan and Lee, Yong Jae},
|
| 153 |
+
journal={CVPR},
|
| 154 |
+
year={2023}
|
| 155 |
+
}
|
| 156 |
+
```
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/dataset.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torchvision.transforms as transforms
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def recalculate_box_and_verify_if_valid(x, y, w, h, image_size, original_image_size, min_box_size):
|
| 10 |
+
scale = image_size / min(original_image_size)
|
| 11 |
+
crop_y = (original_image_size[1] * scale - image_size) // 2
|
| 12 |
+
crop_x = (original_image_size[0] * scale - image_size) // 2
|
| 13 |
+
x0 = max(x * scale - crop_x, 0)
|
| 14 |
+
y0 = max(y * scale - crop_y, 0)
|
| 15 |
+
x1 = min((x + w) * scale - crop_x, image_size)
|
| 16 |
+
y1 = min((y + h) * scale - crop_y, image_size)
|
| 17 |
+
if (x1 - x0) * (y1 - y0) / (image_size * image_size) < min_box_size:
|
| 18 |
+
return False, (None, None, None, None)
|
| 19 |
+
return True, (x0, y0, x1, y1)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class COCODataset(torch.utils.data.Dataset):
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
data_path,
|
| 26 |
+
image_path,
|
| 27 |
+
image_size=512,
|
| 28 |
+
min_box_size=0.01,
|
| 29 |
+
max_boxes_per_data=8,
|
| 30 |
+
tokenizer=None,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.min_box_size = min_box_size
|
| 34 |
+
self.max_boxes_per_data = max_boxes_per_data
|
| 35 |
+
self.image_size = image_size
|
| 36 |
+
self.image_path = image_path
|
| 37 |
+
self.tokenizer = tokenizer
|
| 38 |
+
self.transforms = transforms.Compose(
|
| 39 |
+
[
|
| 40 |
+
transforms.Resize(image_size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 41 |
+
transforms.CenterCrop(image_size),
|
| 42 |
+
transforms.ToTensor(),
|
| 43 |
+
transforms.Normalize([0.5], [0.5]),
|
| 44 |
+
]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.data_list = torch.load(data_path, map_location="cpu")
|
| 48 |
+
|
| 49 |
+
def __getitem__(self, index):
|
| 50 |
+
if self.max_boxes_per_data > 99:
|
| 51 |
+
assert False, "Are you sure setting such large number of boxes per image?"
|
| 52 |
+
|
| 53 |
+
out = {}
|
| 54 |
+
|
| 55 |
+
data = self.data_list[index]
|
| 56 |
+
image = Image.open(os.path.join(self.image_path, data["file_path"])).convert("RGB")
|
| 57 |
+
original_image_size = image.size
|
| 58 |
+
out["pixel_values"] = self.transforms(image)
|
| 59 |
+
|
| 60 |
+
annos = data["annos"]
|
| 61 |
+
|
| 62 |
+
areas, valid_annos = [], []
|
| 63 |
+
for anno in annos:
|
| 64 |
+
# x, y, w, h = anno['bbox']
|
| 65 |
+
x0, y0, x1, y1 = anno["bbox"]
|
| 66 |
+
x, y, w, h = x0, y0, x1 - x0, y1 - y0
|
| 67 |
+
valid, (x0, y0, x1, y1) = recalculate_box_and_verify_if_valid(
|
| 68 |
+
x, y, w, h, self.image_size, original_image_size, self.min_box_size
|
| 69 |
+
)
|
| 70 |
+
if valid:
|
| 71 |
+
anno["bbox"] = [x0, y0, x1, y1]
|
| 72 |
+
areas.append((x1 - x0) * (y1 - y0))
|
| 73 |
+
valid_annos.append(anno)
|
| 74 |
+
|
| 75 |
+
# Sort according to area and choose the largest N objects
|
| 76 |
+
wanted_idxs = torch.tensor(areas).sort(descending=True)[1]
|
| 77 |
+
wanted_idxs = wanted_idxs[: self.max_boxes_per_data]
|
| 78 |
+
valid_annos = [valid_annos[i] for i in wanted_idxs]
|
| 79 |
+
|
| 80 |
+
out["boxes"] = torch.zeros(self.max_boxes_per_data, 4)
|
| 81 |
+
out["masks"] = torch.zeros(self.max_boxes_per_data)
|
| 82 |
+
out["text_embeddings_before_projection"] = torch.zeros(self.max_boxes_per_data, 768)
|
| 83 |
+
|
| 84 |
+
for i, anno in enumerate(valid_annos):
|
| 85 |
+
out["boxes"][i] = torch.tensor(anno["bbox"]) / self.image_size
|
| 86 |
+
out["masks"][i] = 1
|
| 87 |
+
out["text_embeddings_before_projection"][i] = anno["text_embeddings_before_projection"]
|
| 88 |
+
|
| 89 |
+
prob_drop_boxes = 0.1
|
| 90 |
+
if random.random() < prob_drop_boxes:
|
| 91 |
+
out["masks"][:] = 0
|
| 92 |
+
|
| 93 |
+
caption = random.choice(data["captions"])
|
| 94 |
+
|
| 95 |
+
prob_drop_captions = 0.5
|
| 96 |
+
if random.random() < prob_drop_captions:
|
| 97 |
+
caption = ""
|
| 98 |
+
caption = self.tokenizer(
|
| 99 |
+
caption,
|
| 100 |
+
max_length=self.tokenizer.model_max_length,
|
| 101 |
+
padding="max_length",
|
| 102 |
+
truncation=True,
|
| 103 |
+
return_tensors="pt",
|
| 104 |
+
)
|
| 105 |
+
out["caption"] = caption
|
| 106 |
+
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
def __len__(self):
|
| 110 |
+
return len(self.data_list)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/demo.ipynb
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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",
|
| 11 |
+
"text": [
|
| 12 |
+
"The autoreload extension is already loaded. To reload it, use:\n",
|
| 13 |
+
" %reload_ext autoreload\n"
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"name": "stderr",
|
| 18 |
+
"output_type": "stream",
|
| 19 |
+
"text": [
|
| 20 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
| 21 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
| 22 |
+
]
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"source": [
|
| 26 |
+
"%load_ext autoreload\n",
|
| 27 |
+
"%autoreload 2\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"from diffusers import StableDiffusionGLIGENPipeline"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"execution_count": 7,
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"outputs": [],
|
| 37 |
+
"source": [
|
| 38 |
+
"from transformers import CLIPTextModel, CLIPTokenizer\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"import diffusers\n",
|
| 41 |
+
"from diffusers import (\n",
|
| 42 |
+
" AutoencoderKL,\n",
|
| 43 |
+
" DDPMScheduler,\n",
|
| 44 |
+
" EulerDiscreteScheduler,\n",
|
| 45 |
+
" UNet2DConditionModel,\n",
|
| 46 |
+
")\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"# pretrained_model_name_or_path = 'masterful/gligen-1-4-generation-text-box'\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"pretrained_model_name_or_path = \"/root/data/zhizhonghuang/checkpoints/models--masterful--gligen-1-4-generation-text-box/snapshots/d2820dc1e9ba6ca082051ce79cfd3eb468ae2c83\"\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder=\"tokenizer\")\n",
|
| 54 |
+
"noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder=\"scheduler\")\n",
|
| 55 |
+
"text_encoder = CLIPTextModel.from_pretrained(pretrained_model_name_or_path, subfolder=\"text_encoder\")\n",
|
| 56 |
+
"vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder=\"vae\")\n",
|
| 57 |
+
"# unet = UNet2DConditionModel.from_pretrained(\n",
|
| 58 |
+
"# pretrained_model_name_or_path, subfolder=\"unet\"\n",
|
| 59 |
+
"# )\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"noise_scheduler = EulerDiscreteScheduler.from_config(noise_scheduler.config)"
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"execution_count": 8,
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"outputs": [],
|
| 69 |
+
"source": [
|
| 70 |
+
"unet = UNet2DConditionModel.from_pretrained(\"/root/data/zhizhonghuang/ckpt/GLIGEN_Text_Retrain_COCO\")"
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"execution_count": 9,
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"outputs": [
|
| 78 |
+
{
|
| 79 |
+
"name": "stderr",
|
| 80 |
+
"output_type": "stream",
|
| 81 |
+
"text": [
|
| 82 |
+
"You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion_gligen.pipeline_stable_diffusion_gligen.StableDiffusionGLIGENPipeline'> by passing `safety_checker=None`. Ensure that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling it only for use-cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .\n"
|
| 83 |
+
]
|
| 84 |
+
}
|
| 85 |
+
],
|
| 86 |
+
"source": [
|
| 87 |
+
"pipe = StableDiffusionGLIGENPipeline(\n",
|
| 88 |
+
" vae,\n",
|
| 89 |
+
" text_encoder,\n",
|
| 90 |
+
" tokenizer,\n",
|
| 91 |
+
" unet,\n",
|
| 92 |
+
" noise_scheduler,\n",
|
| 93 |
+
" safety_checker=None,\n",
|
| 94 |
+
" feature_extractor=None,\n",
|
| 95 |
+
")\n",
|
| 96 |
+
"pipe = pipe.to(\"cuda\")"
|
| 97 |
+
]
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"execution_count": 10,
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"outputs": [],
|
| 104 |
+
"source": [
|
| 105 |
+
"import numpy as np\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# prompt = 'A realistic image of landscape scene depicting a green car parking on the left of a blue truck, with a red air balloon and a bird in the sky'\n",
|
| 109 |
+
"# gen_boxes = [('a green car', [21, 281, 211, 159]), ('a blue truck', [269, 283, 209, 160]), ('a red air balloon', [66, 8, 145, 135]), ('a bird', [296, 42, 143, 100])]\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"# prompt = 'A realistic top-down view of a wooden table with two apples on it'\n",
|
| 112 |
+
"# gen_boxes = [('a wooden table', [20, 148, 472, 216]), ('an apple', [150, 226, 100, 100]), ('an apple', [280, 226, 100, 100])]\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# prompt = 'A realistic scene of three skiers standing in a line on the snow near a palm tree'\n",
|
| 115 |
+
"# gen_boxes = [('a skier', [5, 152, 139, 168]), ('a skier', [278, 192, 121, 158]), ('a skier', [148, 173, 124, 155]), ('a palm tree', [404, 105, 103, 251])]\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"prompt = \"An oil painting of a pink dolphin jumping on the left of a steam boat on the sea\"\n",
|
| 118 |
+
"gen_boxes = [(\"a steam boat\", [232, 225, 257, 149]), (\"a jumping pink dolphin\", [21, 249, 189, 123])]\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"boxes = np.array([x[1] for x in gen_boxes])\n",
|
| 121 |
+
"boxes = boxes / 512\n",
|
| 122 |
+
"boxes[:, 2] = boxes[:, 0] + boxes[:, 2]\n",
|
| 123 |
+
"boxes[:, 3] = boxes[:, 1] + boxes[:, 3]\n",
|
| 124 |
+
"boxes = boxes.tolist()\n",
|
| 125 |
+
"gligen_phrases = [x[0] for x in gen_boxes]"
|
| 126 |
+
]
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"execution_count": 11,
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"outputs": [
|
| 133 |
+
{
|
| 134 |
+
"name": "stderr",
|
| 135 |
+
"output_type": "stream",
|
| 136 |
+
"text": [
|
| 137 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py:683: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.\n",
|
| 138 |
+
" num_channels_latents = self.unet.in_channels\n",
|
| 139 |
+
"/root/miniconda/envs/densecaption/lib/python3.11/site-packages/diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py:716: FutureWarning: Accessing config attribute `cross_attention_dim` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'cross_attention_dim' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.cross_attention_dim'.\n",
|
| 140 |
+
" max_objs, self.unet.cross_attention_dim, device=device, dtype=self.text_encoder.dtype\n",
|
| 141 |
+
"100%|██████████| 50/50 [01:21<00:00, 1.64s/it]\n"
|
| 142 |
+
]
|
| 143 |
+
}
|
| 144 |
+
],
|
| 145 |
+
"source": [
|
| 146 |
+
"images = pipe(\n",
|
| 147 |
+
" prompt=prompt,\n",
|
| 148 |
+
" gligen_phrases=gligen_phrases,\n",
|
| 149 |
+
" gligen_boxes=boxes,\n",
|
| 150 |
+
" gligen_scheduled_sampling_beta=1.0,\n",
|
| 151 |
+
" output_type=\"pil\",\n",
|
| 152 |
+
" num_inference_steps=50,\n",
|
| 153 |
+
" negative_prompt=\"artifacts, blurry, smooth texture, bad quality, distortions, unrealistic, distorted image, bad proportions, duplicate\",\n",
|
| 154 |
+
" num_images_per_prompt=16,\n",
|
| 155 |
+
").images"
|
| 156 |
+
]
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"execution_count": 12,
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"outputs": [],
|
| 163 |
+
"source": [
|
| 164 |
+
"diffusers.utils.make_image_grid(images, 4, len(images) // 4)"
|
| 165 |
+
]
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"outputs": [],
|
| 172 |
+
"source": []
|
| 173 |
+
}
|
| 174 |
+
],
|
| 175 |
+
"metadata": {
|
| 176 |
+
"kernelspec": {
|
| 177 |
+
"display_name": "Python 3 (ipykernel)",
|
| 178 |
+
"language": "python",
|
| 179 |
+
"name": "python3"
|
| 180 |
+
},
|
| 181 |
+
"language_info": {
|
| 182 |
+
"codemirror_mode": {
|
| 183 |
+
"name": "ipython",
|
| 184 |
+
"version": 3
|
| 185 |
+
},
|
| 186 |
+
"file_extension": ".py",
|
| 187 |
+
"mimetype": "text/x-python",
|
| 188 |
+
"name": "python",
|
| 189 |
+
"nbconvert_exporter": "python",
|
| 190 |
+
"pygments_lexer": "ipython3",
|
| 191 |
+
"version": "3.11.9"
|
| 192 |
+
}
|
| 193 |
+
},
|
| 194 |
+
"nbformat": 4,
|
| 195 |
+
"nbformat_minor": 4
|
| 196 |
+
}
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/generated-images-100000-00.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/make_datasets.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torchvision
|
| 7 |
+
import torchvision.transforms as TS
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from ram import inference_ram
|
| 10 |
+
from ram.models import ram
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from transformers import (
|
| 13 |
+
AutoModelForZeroShotObjectDetection,
|
| 14 |
+
AutoProcessor,
|
| 15 |
+
Blip2ForConditionalGeneration,
|
| 16 |
+
Blip2Processor,
|
| 17 |
+
CLIPTextModel,
|
| 18 |
+
CLIPTokenizer,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
torch.autograd.set_grad_enabled(False)
|
| 23 |
+
|
| 24 |
+
if __name__ == "__main__":
|
| 25 |
+
parser = argparse.ArgumentParser("Caption Generation script", add_help=False)
|
| 26 |
+
parser.add_argument("--data_root", type=str, required=True, help="path to COCO")
|
| 27 |
+
parser.add_argument("--save_root", type=str, required=True, help="path to save")
|
| 28 |
+
parser.add_argument("--ram_checkpoint", type=str, required=True, help="path to save")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
|
| 31 |
+
# ram_checkpoint = '/root/.cache/huggingface/hub/models--xinyu1205--recognize_anything_model/snapshots/ebc52dc741e86466202a5ab8ab22eae6e7d48bf1/ram_swin_large_14m.pth'
|
| 32 |
+
# data_root = '/mnt/workspace/workgroup/zhizhonghuang/dataset/COCO/train2017'
|
| 33 |
+
# save_root = '/root/gligen_data'
|
| 34 |
+
box_threshold = 0.25
|
| 35 |
+
text_threshold = 0.2
|
| 36 |
+
|
| 37 |
+
import torch.distributed as dist
|
| 38 |
+
|
| 39 |
+
dist.init_process_group(backend="nccl", init_method="env://")
|
| 40 |
+
local_rank = torch.distributed.get_rank() % torch.cuda.device_count()
|
| 41 |
+
device = f"cuda:{local_rank}"
|
| 42 |
+
torch.cuda.set_device(local_rank)
|
| 43 |
+
|
| 44 |
+
ram_model = ram(pretrained=args.ram_checkpoint, image_size=384, vit="swin_l").cuda().eval()
|
| 45 |
+
ram_processor = TS.Compose(
|
| 46 |
+
[TS.Resize((384, 384)), TS.ToTensor(), TS.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
grounding_dino_processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-base")
|
| 50 |
+
grounding_dino_model = AutoModelForZeroShotObjectDetection.from_pretrained(
|
| 51 |
+
"IDEA-Research/grounding-dino-base"
|
| 52 |
+
).cuda()
|
| 53 |
+
|
| 54 |
+
blip2_processor = Blip2Processor.from_pretrained("Salesforce/blip2-flan-t5-xxl")
|
| 55 |
+
blip2_model = Blip2ForConditionalGeneration.from_pretrained(
|
| 56 |
+
"Salesforce/blip2-flan-t5-xxl", torch_dtype=torch.float16
|
| 57 |
+
).cuda()
|
| 58 |
+
|
| 59 |
+
clip_text_encoder = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14").cuda()
|
| 60 |
+
clip_tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
|
| 61 |
+
|
| 62 |
+
image_paths = [os.path.join(args.data_root, x) for x in os.listdir(args.data_root)]
|
| 63 |
+
random.shuffle(image_paths)
|
| 64 |
+
|
| 65 |
+
for image_path in tqdm.tqdm(image_paths):
|
| 66 |
+
pth_path = os.path.join(args.save_root, os.path.basename(image_path))
|
| 67 |
+
if os.path.exists(pth_path):
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
sample = {"file_path": os.path.basename(image_path), "annos": []}
|
| 71 |
+
|
| 72 |
+
raw_image = Image.open(image_path).convert("RGB")
|
| 73 |
+
|
| 74 |
+
res = inference_ram(ram_processor(raw_image).unsqueeze(0).cuda(), ram_model)
|
| 75 |
+
|
| 76 |
+
text = res[0].replace(" |", ".")
|
| 77 |
+
|
| 78 |
+
inputs = grounding_dino_processor(images=raw_image, text=text, return_tensors="pt")
|
| 79 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
| 80 |
+
outputs = grounding_dino_model(**inputs)
|
| 81 |
+
|
| 82 |
+
results = grounding_dino_processor.post_process_grounded_object_detection(
|
| 83 |
+
outputs,
|
| 84 |
+
inputs["input_ids"],
|
| 85 |
+
box_threshold=box_threshold,
|
| 86 |
+
text_threshold=text_threshold,
|
| 87 |
+
target_sizes=[raw_image.size[::-1]],
|
| 88 |
+
)
|
| 89 |
+
boxes = results[0]["boxes"]
|
| 90 |
+
labels = results[0]["labels"]
|
| 91 |
+
scores = results[0]["scores"]
|
| 92 |
+
indices = torchvision.ops.nms(boxes, scores, 0.5)
|
| 93 |
+
boxes = boxes[indices]
|
| 94 |
+
category_names = [labels[i] for i in indices]
|
| 95 |
+
|
| 96 |
+
for i, bbox in enumerate(boxes):
|
| 97 |
+
bbox = bbox.tolist()
|
| 98 |
+
inputs = blip2_processor(images=raw_image.crop(bbox), return_tensors="pt")
|
| 99 |
+
inputs = {k: v.cuda().to(torch.float16) for k, v in inputs.items()}
|
| 100 |
+
outputs = blip2_model.generate(**inputs)
|
| 101 |
+
caption = blip2_processor.decode(outputs[0], skip_special_tokens=True)
|
| 102 |
+
inputs = clip_tokenizer(
|
| 103 |
+
caption,
|
| 104 |
+
padding="max_length",
|
| 105 |
+
max_length=clip_tokenizer.model_max_length,
|
| 106 |
+
truncation=True,
|
| 107 |
+
return_tensors="pt",
|
| 108 |
+
)
|
| 109 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
| 110 |
+
text_embeddings_before_projection = clip_text_encoder(**inputs).pooler_output.squeeze(0)
|
| 111 |
+
|
| 112 |
+
sample["annos"].append(
|
| 113 |
+
{
|
| 114 |
+
"caption": caption,
|
| 115 |
+
"bbox": bbox,
|
| 116 |
+
"text_embeddings_before_projection": text_embeddings_before_projection,
|
| 117 |
+
}
|
| 118 |
+
)
|
| 119 |
+
torch.save(sample, pth_path)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/gligen/requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.16.0
|
| 2 |
+
torchvision
|
| 3 |
+
transformers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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from accelerate.utils import write_basic_config
|
| 2 |
+
#
|
| 3 |
+
# write_basic_config()
|
| 4 |
+
import argparse
|
| 5 |
+
import logging
|
| 6 |
+
import math
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import accelerate
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
import torch.utils.checkpoint
|
| 15 |
+
import transformers
|
| 16 |
+
from accelerate import Accelerator
|
| 17 |
+
from accelerate.logging import get_logger
|
| 18 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 19 |
+
from packaging import version
|
| 20 |
+
from tqdm.auto import tqdm
|
| 21 |
+
|
| 22 |
+
import diffusers
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKL,
|
| 25 |
+
DDPMScheduler,
|
| 26 |
+
EulerDiscreteScheduler,
|
| 27 |
+
StableDiffusionGLIGENPipeline,
|
| 28 |
+
UNet2DConditionModel,
|
| 29 |
+
)
|
| 30 |
+
from diffusers.optimization import get_scheduler
|
| 31 |
+
from diffusers.utils import is_wandb_available, make_image_grid
|
| 32 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 33 |
+
from diffusers.utils.torch_utils import is_compiled_module
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if is_wandb_available():
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 40 |
+
# check_min_version("0.28.0.dev0")
|
| 41 |
+
|
| 42 |
+
logger = get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@torch.no_grad()
|
| 46 |
+
def log_validation(vae, text_encoder, tokenizer, unet, noise_scheduler, args, accelerator, step, weight_dtype):
|
| 47 |
+
if accelerator.is_main_process:
|
| 48 |
+
print("generate test images...")
|
| 49 |
+
unet = accelerator.unwrap_model(unet)
|
| 50 |
+
vae.to(accelerator.device, dtype=torch.float32)
|
| 51 |
+
|
| 52 |
+
pipeline = StableDiffusionGLIGENPipeline(
|
| 53 |
+
vae,
|
| 54 |
+
text_encoder,
|
| 55 |
+
tokenizer,
|
| 56 |
+
unet,
|
| 57 |
+
EulerDiscreteScheduler.from_config(noise_scheduler.config),
|
| 58 |
+
safety_checker=None,
|
| 59 |
+
feature_extractor=None,
|
| 60 |
+
)
|
| 61 |
+
pipeline = pipeline.to(accelerator.device)
|
| 62 |
+
pipeline.set_progress_bar_config(disable=not accelerator.is_main_process)
|
| 63 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 64 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 65 |
+
|
| 66 |
+
if args.seed is None:
|
| 67 |
+
generator = None
|
| 68 |
+
else:
|
| 69 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 70 |
+
|
| 71 |
+
prompt = "A realistic image of landscape scene depicting a green car parking on the left of a blue truck, with a red air balloon and a bird in the sky"
|
| 72 |
+
boxes = [
|
| 73 |
+
[0.041015625, 0.548828125, 0.453125, 0.859375],
|
| 74 |
+
[0.525390625, 0.552734375, 0.93359375, 0.865234375],
|
| 75 |
+
[0.12890625, 0.015625, 0.412109375, 0.279296875],
|
| 76 |
+
[0.578125, 0.08203125, 0.857421875, 0.27734375],
|
| 77 |
+
]
|
| 78 |
+
gligen_phrases = ["a green car", "a blue truck", "a red air balloon", "a bird"]
|
| 79 |
+
images = pipeline(
|
| 80 |
+
prompt=prompt,
|
| 81 |
+
gligen_phrases=gligen_phrases,
|
| 82 |
+
gligen_boxes=boxes,
|
| 83 |
+
gligen_scheduled_sampling_beta=1.0,
|
| 84 |
+
output_type="pil",
|
| 85 |
+
num_inference_steps=50,
|
| 86 |
+
negative_prompt="artifacts, blurry, smooth texture, bad quality, distortions, unrealistic, distorted image, bad proportions, duplicate",
|
| 87 |
+
num_images_per_prompt=4,
|
| 88 |
+
generator=generator,
|
| 89 |
+
).images
|
| 90 |
+
os.makedirs(os.path.join(args.output_dir, "images"), exist_ok=True)
|
| 91 |
+
make_image_grid(images, 1, 4).save(
|
| 92 |
+
os.path.join(args.output_dir, "images", f"generated-images-{step:06d}-{accelerator.process_index:02d}.png")
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def parse_args(input_args=None):
|
| 99 |
+
parser = argparse.ArgumentParser(description="Simple example of a ControlNet training script.")
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--data_path",
|
| 102 |
+
type=str,
|
| 103 |
+
default="coco_train2017.pth",
|
| 104 |
+
help="Path to training dataset.",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--image_path",
|
| 108 |
+
type=str,
|
| 109 |
+
default="coco_train2017.pth",
|
| 110 |
+
help="Path to training images.",
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--output_dir",
|
| 114 |
+
type=str,
|
| 115 |
+
default="controlnet-model",
|
| 116 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument("--seed", type=int, default=0, help="A seed for reproducible training.")
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--resolution",
|
| 121 |
+
type=int,
|
| 122 |
+
default=512,
|
| 123 |
+
help=(
|
| 124 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 125 |
+
" resolution"
|
| 126 |
+
),
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument("--num_train_epochs", type=int, default=1)
|
| 132 |
+
parser.add_argument(
|
| 133 |
+
"--max_train_steps",
|
| 134 |
+
type=int,
|
| 135 |
+
default=None,
|
| 136 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--checkpointing_steps",
|
| 140 |
+
type=int,
|
| 141 |
+
default=500,
|
| 142 |
+
help=(
|
| 143 |
+
"Save a checkpoint of the training state every X updates. Checkpoints can be used for resuming training via `--resume_from_checkpoint`. "
|
| 144 |
+
"In the case that the checkpoint is better than the final trained model, the checkpoint can also be used for inference."
|
| 145 |
+
"Using a checkpoint for inference requires separate loading of the original pipeline and the individual checkpointed model components."
|
| 146 |
+
"See https://huggingface.co/docs/diffusers/main/en/training/dreambooth#performing-inference-using-a-saved-checkpoint for step by step"
|
| 147 |
+
"instructions."
|
| 148 |
+
),
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--checkpoints_total_limit",
|
| 152 |
+
type=int,
|
| 153 |
+
default=None,
|
| 154 |
+
help=("Max number of checkpoints to store."),
|
| 155 |
+
)
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--resume_from_checkpoint",
|
| 158 |
+
type=str,
|
| 159 |
+
default=None,
|
| 160 |
+
help=(
|
| 161 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 162 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 163 |
+
),
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--gradient_accumulation_steps",
|
| 167 |
+
type=int,
|
| 168 |
+
default=1,
|
| 169 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 170 |
+
)
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--gradient_checkpointing",
|
| 173 |
+
action="store_true",
|
| 174 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--learning_rate",
|
| 178 |
+
type=float,
|
| 179 |
+
default=5e-6,
|
| 180 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 181 |
+
)
|
| 182 |
+
parser.add_argument(
|
| 183 |
+
"--scale_lr",
|
| 184 |
+
action="store_true",
|
| 185 |
+
default=False,
|
| 186 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--lr_scheduler",
|
| 190 |
+
type=str,
|
| 191 |
+
default="constant",
|
| 192 |
+
help=(
|
| 193 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 194 |
+
' "constant", "constant_with_warmup"]'
|
| 195 |
+
),
|
| 196 |
+
)
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 199 |
+
)
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--lr_num_cycles",
|
| 202 |
+
type=int,
|
| 203 |
+
default=1,
|
| 204 |
+
help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
|
| 205 |
+
)
|
| 206 |
+
parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--dataloader_num_workers",
|
| 209 |
+
type=int,
|
| 210 |
+
default=0,
|
| 211 |
+
help=(
|
| 212 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 213 |
+
),
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 216 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 217 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 218 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 219 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 220 |
+
parser.add_argument(
|
| 221 |
+
"--logging_dir",
|
| 222 |
+
type=str,
|
| 223 |
+
default="logs",
|
| 224 |
+
help=(
|
| 225 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 226 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 227 |
+
),
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--allow_tf32",
|
| 231 |
+
action="store_true",
|
| 232 |
+
help=(
|
| 233 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 234 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
parser.add_argument(
|
| 238 |
+
"--report_to",
|
| 239 |
+
type=str,
|
| 240 |
+
default="tensorboard",
|
| 241 |
+
help=(
|
| 242 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 243 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 244 |
+
),
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--mixed_precision",
|
| 248 |
+
type=str,
|
| 249 |
+
default=None,
|
| 250 |
+
choices=["no", "fp16", "bf16"],
|
| 251 |
+
help=(
|
| 252 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 253 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 254 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 255 |
+
),
|
| 256 |
+
)
|
| 257 |
+
parser.add_argument(
|
| 258 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"--set_grads_to_none",
|
| 262 |
+
action="store_true",
|
| 263 |
+
help=(
|
| 264 |
+
"Save more memory by using setting grads to None instead of zero. Be aware, that this changes certain"
|
| 265 |
+
" behaviors, so disable this argument if it causes any problems. More info:"
|
| 266 |
+
" https://pytorch.org/docs/stable/generated/torch.optim.Optimizer.zero_grad.html"
|
| 267 |
+
),
|
| 268 |
+
)
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--tracker_project_name",
|
| 271 |
+
type=str,
|
| 272 |
+
default="train_controlnet",
|
| 273 |
+
help=(
|
| 274 |
+
"The `project_name` argument passed to Accelerator.init_trackers for"
|
| 275 |
+
" more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
|
| 276 |
+
),
|
| 277 |
+
)
|
| 278 |
+
args = parser.parse_args()
|
| 279 |
+
return args
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def main(args):
|
| 283 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 284 |
+
|
| 285 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 286 |
+
|
| 287 |
+
accelerator = Accelerator(
|
| 288 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 289 |
+
mixed_precision=args.mixed_precision,
|
| 290 |
+
log_with=args.report_to,
|
| 291 |
+
project_config=accelerator_project_config,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
# Disable AMP for MPS.
|
| 295 |
+
if torch.backends.mps.is_available():
|
| 296 |
+
accelerator.native_amp = False
|
| 297 |
+
|
| 298 |
+
# Make one log on every process with the configuration for debugging.
|
| 299 |
+
logging.basicConfig(
|
| 300 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 301 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 302 |
+
level=logging.INFO,
|
| 303 |
+
)
|
| 304 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 305 |
+
if accelerator.is_local_main_process:
|
| 306 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 307 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 308 |
+
else:
|
| 309 |
+
transformers.utils.logging.set_verbosity_error()
|
| 310 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 311 |
+
|
| 312 |
+
# If passed along, set the training seed now.
|
| 313 |
+
if args.seed is not None:
|
| 314 |
+
set_seed(args.seed)
|
| 315 |
+
|
| 316 |
+
# Handle the repository creation
|
| 317 |
+
if accelerator.is_main_process:
|
| 318 |
+
if args.output_dir is not None:
|
| 319 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 320 |
+
|
| 321 |
+
# import correct text encoder class
|
| 322 |
+
# text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
|
| 323 |
+
# Load scheduler and models
|
| 324 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 325 |
+
|
| 326 |
+
pretrained_model_name_or_path = "masterful/gligen-1-4-generation-text-box"
|
| 327 |
+
tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer")
|
| 328 |
+
noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
|
| 329 |
+
text_encoder = CLIPTextModel.from_pretrained(pretrained_model_name_or_path, subfolder="text_encoder")
|
| 330 |
+
|
| 331 |
+
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
|
| 332 |
+
unet = UNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, subfolder="unet")
|
| 333 |
+
|
| 334 |
+
# Taken from [Sayak Paul's Diffusers PR #6511](https://github.com/huggingface/diffusers/pull/6511/files)
|
| 335 |
+
def unwrap_model(model):
|
| 336 |
+
model = accelerator.unwrap_model(model)
|
| 337 |
+
model = model._orig_mod if is_compiled_module(model) else model
|
| 338 |
+
return model
|
| 339 |
+
|
| 340 |
+
# `accelerate` 0.16.0 will have better support for customized saving
|
| 341 |
+
if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
|
| 342 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 343 |
+
def save_model_hook(models, weights, output_dir):
|
| 344 |
+
if accelerator.is_main_process:
|
| 345 |
+
i = len(weights) - 1
|
| 346 |
+
|
| 347 |
+
while len(weights) > 0:
|
| 348 |
+
weights.pop()
|
| 349 |
+
model = models[i]
|
| 350 |
+
|
| 351 |
+
sub_dir = "unet"
|
| 352 |
+
model.save_pretrained(os.path.join(output_dir, sub_dir))
|
| 353 |
+
|
| 354 |
+
i -= 1
|
| 355 |
+
|
| 356 |
+
def load_model_hook(models, input_dir):
|
| 357 |
+
while len(models) > 0:
|
| 358 |
+
# pop models so that they are not loaded again
|
| 359 |
+
model = models.pop()
|
| 360 |
+
|
| 361 |
+
# load diffusers style into model
|
| 362 |
+
load_model = unet.from_pretrained(input_dir, subfolder="unet")
|
| 363 |
+
model.register_to_config(**load_model.config)
|
| 364 |
+
|
| 365 |
+
model.load_state_dict(load_model.state_dict())
|
| 366 |
+
del load_model
|
| 367 |
+
|
| 368 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 369 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 370 |
+
|
| 371 |
+
vae.requires_grad_(False)
|
| 372 |
+
unet.requires_grad_(False)
|
| 373 |
+
text_encoder.requires_grad_(False)
|
| 374 |
+
|
| 375 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 376 |
+
if is_xformers_available():
|
| 377 |
+
import xformers
|
| 378 |
+
|
| 379 |
+
xformers_version = version.parse(xformers.__version__)
|
| 380 |
+
if xformers_version == version.parse("0.0.16"):
|
| 381 |
+
logger.warning(
|
| 382 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 383 |
+
)
|
| 384 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 385 |
+
# controlnet.enable_xformers_memory_efficient_attention()
|
| 386 |
+
else:
|
| 387 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 388 |
+
|
| 389 |
+
# if args.gradient_checkpointing:
|
| 390 |
+
# controlnet.enable_gradient_checkpointing()
|
| 391 |
+
|
| 392 |
+
# Check that all trainable models are in full precision
|
| 393 |
+
low_precision_error_string = (
|
| 394 |
+
" Please make sure to always have all model weights in full float32 precision when starting training - even if"
|
| 395 |
+
" doing mixed precision training, copy of the weights should still be float32."
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
if unwrap_model(unet).dtype != torch.float32:
|
| 399 |
+
raise ValueError(f"Controlnet loaded as datatype {unwrap_model(unet).dtype}. {low_precision_error_string}")
|
| 400 |
+
|
| 401 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 402 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 403 |
+
if args.allow_tf32:
|
| 404 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 405 |
+
|
| 406 |
+
if args.scale_lr:
|
| 407 |
+
args.learning_rate = (
|
| 408 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
optimizer_class = torch.optim.AdamW
|
| 412 |
+
# Optimizer creation
|
| 413 |
+
for n, m in unet.named_modules():
|
| 414 |
+
if ("fuser" in n) or ("position_net" in n):
|
| 415 |
+
import torch.nn as nn
|
| 416 |
+
|
| 417 |
+
if isinstance(m, (nn.Linear, nn.LayerNorm)):
|
| 418 |
+
m.reset_parameters()
|
| 419 |
+
params_to_optimize = []
|
| 420 |
+
for n, p in unet.named_parameters():
|
| 421 |
+
if ("fuser" in n) or ("position_net" in n):
|
| 422 |
+
p.requires_grad = True
|
| 423 |
+
params_to_optimize.append(p)
|
| 424 |
+
optimizer = optimizer_class(
|
| 425 |
+
params_to_optimize,
|
| 426 |
+
lr=args.learning_rate,
|
| 427 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 428 |
+
weight_decay=args.adam_weight_decay,
|
| 429 |
+
eps=args.adam_epsilon,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
from dataset import COCODataset
|
| 433 |
+
|
| 434 |
+
train_dataset = COCODataset(
|
| 435 |
+
data_path=args.data_path,
|
| 436 |
+
image_path=args.image_path,
|
| 437 |
+
tokenizer=tokenizer,
|
| 438 |
+
image_size=args.resolution,
|
| 439 |
+
max_boxes_per_data=30,
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
print("num samples: ", len(train_dataset))
|
| 443 |
+
|
| 444 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 445 |
+
train_dataset,
|
| 446 |
+
shuffle=True,
|
| 447 |
+
# collate_fn=collate_fn,
|
| 448 |
+
batch_size=args.train_batch_size,
|
| 449 |
+
num_workers=args.dataloader_num_workers,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
# Scheduler and math around the number of training steps.
|
| 453 |
+
overrode_max_train_steps = False
|
| 454 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 455 |
+
if args.max_train_steps is None:
|
| 456 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 457 |
+
overrode_max_train_steps = True
|
| 458 |
+
|
| 459 |
+
lr_scheduler = get_scheduler(
|
| 460 |
+
args.lr_scheduler,
|
| 461 |
+
optimizer=optimizer,
|
| 462 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 463 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 464 |
+
num_cycles=args.lr_num_cycles,
|
| 465 |
+
power=args.lr_power,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
# Prepare everything with our `accelerator`.
|
| 469 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 470 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 474 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 475 |
+
weight_dtype = torch.float32
|
| 476 |
+
if accelerator.mixed_precision == "fp16":
|
| 477 |
+
weight_dtype = torch.float16
|
| 478 |
+
elif accelerator.mixed_precision == "bf16":
|
| 479 |
+
weight_dtype = torch.bfloat16
|
| 480 |
+
|
| 481 |
+
# Move vae, unet and text_encoder to device and cast to weight_dtype
|
| 482 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 483 |
+
# unet.to(accelerator.device, dtype=weight_dtype)
|
| 484 |
+
unet.to(accelerator.device, dtype=torch.float32)
|
| 485 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 486 |
+
|
| 487 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 488 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 489 |
+
if overrode_max_train_steps:
|
| 490 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 491 |
+
# Afterwards we recalculate our number of training epochs
|
| 492 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 493 |
+
|
| 494 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 495 |
+
# The trackers initializes automatically on the main process.
|
| 496 |
+
if accelerator.is_main_process:
|
| 497 |
+
tracker_config = dict(vars(args))
|
| 498 |
+
|
| 499 |
+
# tensorboard cannot handle list types for config
|
| 500 |
+
# tracker_config.pop("validation_prompt")
|
| 501 |
+
# tracker_config.pop("validation_image")
|
| 502 |
+
|
| 503 |
+
accelerator.init_trackers(args.tracker_project_name, config=tracker_config)
|
| 504 |
+
|
| 505 |
+
# Train!
|
| 506 |
+
# total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 507 |
+
|
| 508 |
+
# logger.info("***** Running training *****")
|
| 509 |
+
# logger.info(f" Num examples = {len(train_dataset)}")
|
| 510 |
+
# logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 511 |
+
# logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 512 |
+
# logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 513 |
+
# logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 514 |
+
# logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 515 |
+
# logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 516 |
+
global_step = 0
|
| 517 |
+
first_epoch = 0
|
| 518 |
+
|
| 519 |
+
# Potentially load in the weights and states from a previous save
|
| 520 |
+
if args.resume_from_checkpoint:
|
| 521 |
+
if args.resume_from_checkpoint != "latest":
|
| 522 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 523 |
+
else:
|
| 524 |
+
# Get the most recent checkpoint
|
| 525 |
+
dirs = os.listdir(args.output_dir)
|
| 526 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 527 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 528 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 529 |
+
|
| 530 |
+
if path is None:
|
| 531 |
+
accelerator.print(
|
| 532 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 533 |
+
)
|
| 534 |
+
args.resume_from_checkpoint = None
|
| 535 |
+
initial_global_step = 0
|
| 536 |
+
else:
|
| 537 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 538 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 539 |
+
global_step = int(path.split("-")[1])
|
| 540 |
+
|
| 541 |
+
initial_global_step = global_step
|
| 542 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 543 |
+
else:
|
| 544 |
+
initial_global_step = 0
|
| 545 |
+
|
| 546 |
+
progress_bar = tqdm(
|
| 547 |
+
range(0, args.max_train_steps),
|
| 548 |
+
initial=initial_global_step,
|
| 549 |
+
desc="Steps",
|
| 550 |
+
# Only show the progress bar once on each machine.
|
| 551 |
+
disable=not accelerator.is_local_main_process,
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
log_validation(
|
| 555 |
+
vae,
|
| 556 |
+
text_encoder,
|
| 557 |
+
tokenizer,
|
| 558 |
+
unet,
|
| 559 |
+
noise_scheduler,
|
| 560 |
+
args,
|
| 561 |
+
accelerator,
|
| 562 |
+
global_step,
|
| 563 |
+
weight_dtype,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# image_logs = None
|
| 567 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 568 |
+
for step, batch in enumerate(train_dataloader):
|
| 569 |
+
with accelerator.accumulate(unet):
|
| 570 |
+
# Convert images to latent space
|
| 571 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 572 |
+
latents = latents * vae.config.scaling_factor
|
| 573 |
+
|
| 574 |
+
# Sample noise that we'll add to the latents
|
| 575 |
+
noise = torch.randn_like(latents)
|
| 576 |
+
bsz = latents.shape[0]
|
| 577 |
+
# Sample a random timestep for each image
|
| 578 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 579 |
+
timesteps = timesteps.long()
|
| 580 |
+
|
| 581 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 582 |
+
# (this is the forward diffusion process)
|
| 583 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 584 |
+
|
| 585 |
+
with torch.no_grad():
|
| 586 |
+
# Get the text embedding for conditioning
|
| 587 |
+
encoder_hidden_states = text_encoder(
|
| 588 |
+
batch["caption"]["input_ids"].squeeze(1),
|
| 589 |
+
# batch['caption']['attention_mask'].squeeze(1),
|
| 590 |
+
return_dict=False,
|
| 591 |
+
)[0]
|
| 592 |
+
|
| 593 |
+
cross_attention_kwargs = {}
|
| 594 |
+
cross_attention_kwargs["gligen"] = {
|
| 595 |
+
"boxes": batch["boxes"],
|
| 596 |
+
"positive_embeddings": batch["text_embeddings_before_projection"],
|
| 597 |
+
"masks": batch["masks"],
|
| 598 |
+
}
|
| 599 |
+
# Predict the noise residual
|
| 600 |
+
model_pred = unet(
|
| 601 |
+
noisy_latents,
|
| 602 |
+
timesteps,
|
| 603 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 604 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
| 605 |
+
return_dict=False,
|
| 606 |
+
)[0]
|
| 607 |
+
|
| 608 |
+
# Get the target for loss depending on the prediction type
|
| 609 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 610 |
+
target = noise
|
| 611 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 612 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 613 |
+
else:
|
| 614 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 615 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 616 |
+
|
| 617 |
+
accelerator.backward(loss)
|
| 618 |
+
if accelerator.sync_gradients:
|
| 619 |
+
accelerator.clip_grad_norm_(params_to_optimize, args.max_grad_norm)
|
| 620 |
+
optimizer.step()
|
| 621 |
+
lr_scheduler.step()
|
| 622 |
+
optimizer.zero_grad(set_to_none=args.set_grads_to_none)
|
| 623 |
+
|
| 624 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 625 |
+
if accelerator.sync_gradients:
|
| 626 |
+
progress_bar.update(1)
|
| 627 |
+
global_step += 1
|
| 628 |
+
|
| 629 |
+
if global_step % args.checkpointing_steps == 0:
|
| 630 |
+
if accelerator.is_main_process:
|
| 631 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 632 |
+
if args.checkpoints_total_limit is not None:
|
| 633 |
+
checkpoints = os.listdir(args.output_dir)
|
| 634 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 635 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 636 |
+
|
| 637 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 638 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 639 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 640 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 641 |
+
|
| 642 |
+
logger.info(
|
| 643 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 644 |
+
)
|
| 645 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 646 |
+
|
| 647 |
+
for removing_checkpoint in removing_checkpoints:
|
| 648 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 649 |
+
shutil.rmtree(removing_checkpoint)
|
| 650 |
+
|
| 651 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step:06d}")
|
| 652 |
+
accelerator.save_state(save_path)
|
| 653 |
+
logger.info(f"Saved state to {save_path}")
|
| 654 |
+
|
| 655 |
+
# if args.validation_prompt is not None and global_step % args.validation_steps == 0:
|
| 656 |
+
log_validation(
|
| 657 |
+
vae,
|
| 658 |
+
text_encoder,
|
| 659 |
+
tokenizer,
|
| 660 |
+
unet,
|
| 661 |
+
noise_scheduler,
|
| 662 |
+
args,
|
| 663 |
+
accelerator,
|
| 664 |
+
global_step,
|
| 665 |
+
weight_dtype,
|
| 666 |
+
)
|
| 667 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 668 |
+
progress_bar.set_postfix(**logs)
|
| 669 |
+
accelerator.log(logs, step=global_step)
|
| 670 |
+
|
| 671 |
+
if global_step >= args.max_train_steps:
|
| 672 |
+
break
|
| 673 |
+
|
| 674 |
+
# Create the pipeline using using the trained modules and save it.
|
| 675 |
+
accelerator.wait_for_everyone()
|
| 676 |
+
if accelerator.is_main_process:
|
| 677 |
+
unet = unwrap_model(unet)
|
| 678 |
+
unet.save_pretrained(args.output_dir)
|
| 679 |
+
#
|
| 680 |
+
# # Run a final round of validation.
|
| 681 |
+
# image_logs = None
|
| 682 |
+
# if args.validation_prompt is not None:
|
| 683 |
+
# image_logs = log_validation(
|
| 684 |
+
# vae=vae,
|
| 685 |
+
# text_encoder=text_encoder,
|
| 686 |
+
# tokenizer=tokenizer,
|
| 687 |
+
# unet=unet,
|
| 688 |
+
# controlnet=None,
|
| 689 |
+
# args=args,
|
| 690 |
+
# accelerator=accelerator,
|
| 691 |
+
# weight_dtype=weight_dtype,
|
| 692 |
+
# step=global_step,
|
| 693 |
+
# is_final_validation=True,
|
| 694 |
+
# )
|
| 695 |
+
#
|
| 696 |
+
# if args.push_to_hub:
|
| 697 |
+
# save_model_card(
|
| 698 |
+
# repo_id,
|
| 699 |
+
# image_logs=image_logs,
|
| 700 |
+
# base_model=args.pretrained_model_name_or_path,
|
| 701 |
+
# repo_folder=args.output_dir,
|
| 702 |
+
# )
|
| 703 |
+
# upload_folder(
|
| 704 |
+
# repo_id=repo_id,
|
| 705 |
+
# folder_path=args.output_dir,
|
| 706 |
+
# commit_message="End of training",
|
| 707 |
+
# ignore_patterns=["step_*", "epoch_*"],
|
| 708 |
+
# )
|
| 709 |
+
|
| 710 |
+
accelerator.end_training()
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
if __name__ == "__main__":
|
| 714 |
+
args = parse_args()
|
| 715 |
+
main(args)
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/instructpix2pix_lora/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# InstructPix2Pix text-to-edit-image fine-tuning
|
| 2 |
+
This extended LoRA training script was authored by [Aiden-Frost](https://github.com/Aiden-Frost).
|
| 3 |
+
This is an experimental LoRA extension of [this example](https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix.py). This script provides further support add LoRA layers for unet model.
|
| 4 |
+
|
| 5 |
+
## Running locally with PyTorch
|
| 6 |
+
### Installing the dependencies
|
| 7 |
+
|
| 8 |
+
Before running the scripts, make sure to install the library's training dependencies:
|
| 9 |
+
|
| 10 |
+
**Important**
|
| 11 |
+
|
| 12 |
+
To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
|
| 13 |
+
```bash
|
| 14 |
+
git clone https://github.com/huggingface/diffusers
|
| 15 |
+
cd diffusers
|
| 16 |
+
pip install .
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
Then cd in the example folder and run
|
| 20 |
+
```bash
|
| 21 |
+
pip install -r requirements.txt
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
accelerate config
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Note also that we use PEFT library as backend for LoRA training, make sure to have `peft>=0.6.0` installed in your environment.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
## Training script example
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
export MODEL_ID="timbrooks/instruct-pix2pix"
|
| 37 |
+
export DATASET_ID="instruction-tuning-sd/cartoonization"
|
| 38 |
+
export OUTPUT_DIR="instructPix2Pix-cartoonization"
|
| 39 |
+
|
| 40 |
+
accelerate launch train_instruct_pix2pix_lora.py \
|
| 41 |
+
--pretrained_model_name_or_path=$MODEL_ID \
|
| 42 |
+
--dataset_name=$DATASET_ID \
|
| 43 |
+
--enable_xformers_memory_efficient_attention \
|
| 44 |
+
--resolution=256 --random_flip \
|
| 45 |
+
--train_batch_size=2 --gradient_accumulation_steps=4 --gradient_checkpointing \
|
| 46 |
+
--max_train_steps=15000 \
|
| 47 |
+
--checkpointing_steps=5000 --checkpoints_total_limit=1 \
|
| 48 |
+
--learning_rate=5e-05 --lr_warmup_steps=0 \
|
| 49 |
+
--val_image_url="https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png" \
|
| 50 |
+
--validation_prompt="Generate a cartoonized version of the natural image" \
|
| 51 |
+
--seed=42 \
|
| 52 |
+
--rank=4 \
|
| 53 |
+
--output_dir=$OUTPUT_DIR \
|
| 54 |
+
--report_to=wandb \
|
| 55 |
+
--push_to_hub \
|
| 56 |
+
--original_image_column="original_image" \
|
| 57 |
+
--edited_image_column="cartoonized_image" \
|
| 58 |
+
--edit_prompt_column="edit_prompt"
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Inference
|
| 62 |
+
After training the model and the lora weight of the model is stored in the ```$OUTPUT_DIR```.
|
| 63 |
+
|
| 64 |
+
```py
|
| 65 |
+
# load the base model pipeline
|
| 66 |
+
pipe_lora = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix")
|
| 67 |
+
|
| 68 |
+
# Load LoRA weights from the provided path
|
| 69 |
+
output_dir = "path/to/lora_weight_directory"
|
| 70 |
+
pipe_lora.unet.load_attn_procs(output_dir)
|
| 71 |
+
|
| 72 |
+
input_image_path = "/path/to/input_image"
|
| 73 |
+
input_image = Image.open(input_image_path)
|
| 74 |
+
edited_images = pipe_lora(num_images_per_prompt=1, prompt=args.edit_prompt, image=input_image, num_inference_steps=1000).images
|
| 75 |
+
edited_images[0].show()
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
## Results
|
| 79 |
+
|
| 80 |
+
Here is an example of using the script to train a instructpix2pix model.
|
| 81 |
+
Trained on google colab T4 GPU
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
MODEL_ID="timbrooks/instruct-pix2pix"
|
| 85 |
+
DATASET_ID="instruction-tuning-sd/cartoonization"
|
| 86 |
+
TRAIN_EPOCHS=100
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Below are few examples for given the input image, edit_prompt and the edited_image (output of the model)
|
| 90 |
+
|
| 91 |
+
<p align="center">
|
| 92 |
+
<img src="https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-/blob/main/diffusers_result_assets/edited_image_results.png?raw=true" alt="instructpix2pix-inputs" width=600/>
|
| 93 |
+
</p>
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
Here are some rough statistics about the training model using this script
|
| 97 |
+
|
| 98 |
+
<p align="center">
|
| 99 |
+
<img src="https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-/blob/main/diffusers_result_assets/results.png?raw=true" alt="instructpix2pix-inputs" width=600/>
|
| 100 |
+
</p>
|
| 101 |
+
|
| 102 |
+
## References
|
| 103 |
+
|
| 104 |
+
* InstructPix2Pix - https://github.com/timothybrooks/instruct-pix2pix
|
| 105 |
+
* Dataset and example training script - https://huggingface.co/blog/instruction-tuning-sd
|
| 106 |
+
* For more information about the project - https://github.com/Aiden-Frost/Efficiently-teaching-counting-and-cartoonization-to-InstructPix2Pix.-
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/instructpix2pix_lora/train_instruct_pix2pix_lora.py
ADDED
|
@@ -0,0 +1,1171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding=utf-8
|
| 3 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Script to fine-tune Stable Diffusion for LORA InstructPix2Pix.
|
| 19 |
+
Base code referred from: https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix.py
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import logging
|
| 24 |
+
import math
|
| 25 |
+
import os
|
| 26 |
+
import shutil
|
| 27 |
+
from contextlib import nullcontext
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import accelerate
|
| 31 |
+
import datasets
|
| 32 |
+
import numpy as np
|
| 33 |
+
import PIL
|
| 34 |
+
import requests
|
| 35 |
+
import torch
|
| 36 |
+
import torch.nn as nn
|
| 37 |
+
import torch.nn.functional as F
|
| 38 |
+
import torch.utils.checkpoint
|
| 39 |
+
import transformers
|
| 40 |
+
from accelerate import Accelerator
|
| 41 |
+
from accelerate.logging import get_logger
|
| 42 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 43 |
+
from datasets import load_dataset
|
| 44 |
+
from huggingface_hub import create_repo, upload_folder
|
| 45 |
+
from packaging import version
|
| 46 |
+
from peft import LoraConfig
|
| 47 |
+
from peft.utils import get_peft_model_state_dict
|
| 48 |
+
from torchvision import transforms
|
| 49 |
+
from tqdm.auto import tqdm
|
| 50 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 51 |
+
|
| 52 |
+
import diffusers
|
| 53 |
+
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionInstructPix2PixPipeline, UNet2DConditionModel
|
| 54 |
+
from diffusers.optimization import get_scheduler
|
| 55 |
+
from diffusers.training_utils import EMAModel, cast_training_params
|
| 56 |
+
from diffusers.utils import check_min_version, convert_state_dict_to_diffusers, deprecate, is_wandb_available
|
| 57 |
+
from diffusers.utils.constants import DIFFUSERS_REQUEST_TIMEOUT
|
| 58 |
+
from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
|
| 59 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 60 |
+
from diffusers.utils.torch_utils import is_compiled_module
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if is_wandb_available():
|
| 64 |
+
import wandb
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 68 |
+
check_min_version("0.32.0.dev0")
|
| 69 |
+
|
| 70 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 71 |
+
|
| 72 |
+
DATASET_NAME_MAPPING = {
|
| 73 |
+
"fusing/instructpix2pix-1000-samples": ("input_image", "edit_prompt", "edited_image"),
|
| 74 |
+
}
|
| 75 |
+
WANDB_TABLE_COL_NAMES = ["original_image", "edited_image", "edit_prompt"]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def save_model_card(
|
| 79 |
+
repo_id: str,
|
| 80 |
+
images: list = None,
|
| 81 |
+
base_model: str = None,
|
| 82 |
+
dataset_name: str = None,
|
| 83 |
+
repo_folder: str = None,
|
| 84 |
+
):
|
| 85 |
+
img_str = ""
|
| 86 |
+
if images is not None:
|
| 87 |
+
for i, image in enumerate(images):
|
| 88 |
+
image.save(os.path.join(repo_folder, f"image_{i}.png"))
|
| 89 |
+
img_str += f"\n"
|
| 90 |
+
|
| 91 |
+
model_description = f"""
|
| 92 |
+
# LoRA text2image fine-tuning - {repo_id}
|
| 93 |
+
These are LoRA adaption weights for {base_model}. The weights were fine-tuned on the {dataset_name} dataset. You can find some example images in the following. \n
|
| 94 |
+
{img_str}
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
model_card = load_or_create_model_card(
|
| 98 |
+
repo_id_or_path=repo_id,
|
| 99 |
+
from_training=True,
|
| 100 |
+
license="creativeml-openrail-m",
|
| 101 |
+
base_model=base_model,
|
| 102 |
+
model_description=model_description,
|
| 103 |
+
inference=True,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
tags = [
|
| 107 |
+
"stable-diffusion",
|
| 108 |
+
"stable-diffusion-diffusers",
|
| 109 |
+
"text-to-image",
|
| 110 |
+
"instruct-pix2pix",
|
| 111 |
+
"diffusers",
|
| 112 |
+
"diffusers-training",
|
| 113 |
+
"lora",
|
| 114 |
+
]
|
| 115 |
+
model_card = populate_model_card(model_card, tags=tags)
|
| 116 |
+
|
| 117 |
+
model_card.save(os.path.join(repo_folder, "README.md"))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def log_validation(
|
| 121 |
+
pipeline,
|
| 122 |
+
args,
|
| 123 |
+
accelerator,
|
| 124 |
+
generator,
|
| 125 |
+
):
|
| 126 |
+
logger.info(
|
| 127 |
+
f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
|
| 128 |
+
f" {args.validation_prompt}."
|
| 129 |
+
)
|
| 130 |
+
pipeline = pipeline.to(accelerator.device)
|
| 131 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 132 |
+
|
| 133 |
+
# run inference
|
| 134 |
+
original_image = download_image(args.val_image_url)
|
| 135 |
+
edited_images = []
|
| 136 |
+
if torch.backends.mps.is_available():
|
| 137 |
+
autocast_ctx = nullcontext()
|
| 138 |
+
else:
|
| 139 |
+
autocast_ctx = torch.autocast(accelerator.device.type)
|
| 140 |
+
|
| 141 |
+
with autocast_ctx:
|
| 142 |
+
for _ in range(args.num_validation_images):
|
| 143 |
+
edited_images.append(
|
| 144 |
+
pipeline(
|
| 145 |
+
args.validation_prompt,
|
| 146 |
+
image=original_image,
|
| 147 |
+
num_inference_steps=20,
|
| 148 |
+
image_guidance_scale=1.5,
|
| 149 |
+
guidance_scale=7,
|
| 150 |
+
generator=generator,
|
| 151 |
+
).images[0]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
for tracker in accelerator.trackers:
|
| 155 |
+
if tracker.name == "wandb":
|
| 156 |
+
wandb_table = wandb.Table(columns=WANDB_TABLE_COL_NAMES)
|
| 157 |
+
for edited_image in edited_images:
|
| 158 |
+
wandb_table.add_data(wandb.Image(original_image), wandb.Image(edited_image), args.validation_prompt)
|
| 159 |
+
tracker.log({"validation": wandb_table})
|
| 160 |
+
|
| 161 |
+
return edited_images
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_args():
|
| 165 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script for InstructPix2Pix.")
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
"--pretrained_model_name_or_path",
|
| 168 |
+
type=str,
|
| 169 |
+
default=None,
|
| 170 |
+
required=True,
|
| 171 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument(
|
| 174 |
+
"--revision",
|
| 175 |
+
type=str,
|
| 176 |
+
default=None,
|
| 177 |
+
required=False,
|
| 178 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--variant",
|
| 182 |
+
type=str,
|
| 183 |
+
default=None,
|
| 184 |
+
help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--dataset_name",
|
| 188 |
+
type=str,
|
| 189 |
+
default=None,
|
| 190 |
+
help=(
|
| 191 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 192 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 193 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 194 |
+
),
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--dataset_config_name",
|
| 198 |
+
type=str,
|
| 199 |
+
default=None,
|
| 200 |
+
help="The config of the Dataset, leave as None if there's only one config.",
|
| 201 |
+
)
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--train_data_dir",
|
| 204 |
+
type=str,
|
| 205 |
+
default=None,
|
| 206 |
+
help=(
|
| 207 |
+
"A folder containing the training data. Folder contents must follow the structure described in"
|
| 208 |
+
" https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
|
| 209 |
+
" must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
|
| 210 |
+
),
|
| 211 |
+
)
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--original_image_column",
|
| 214 |
+
type=str,
|
| 215 |
+
default="input_image",
|
| 216 |
+
help="The column of the dataset containing the original image on which edits where made.",
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--edited_image_column",
|
| 220 |
+
type=str,
|
| 221 |
+
default="edited_image",
|
| 222 |
+
help="The column of the dataset containing the edited image.",
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--edit_prompt_column",
|
| 226 |
+
type=str,
|
| 227 |
+
default="edit_prompt",
|
| 228 |
+
help="The column of the dataset containing the edit instruction.",
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--val_image_url",
|
| 232 |
+
type=str,
|
| 233 |
+
default=None,
|
| 234 |
+
help="URL to the original image that you would like to edit (used during inference for debugging purposes).",
|
| 235 |
+
)
|
| 236 |
+
parser.add_argument(
|
| 237 |
+
"--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--num_validation_images",
|
| 241 |
+
type=int,
|
| 242 |
+
default=4,
|
| 243 |
+
help="Number of images that should be generated during validation with `validation_prompt`.",
|
| 244 |
+
)
|
| 245 |
+
parser.add_argument(
|
| 246 |
+
"--validation_epochs",
|
| 247 |
+
type=int,
|
| 248 |
+
default=1,
|
| 249 |
+
help=(
|
| 250 |
+
"Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
|
| 251 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`."
|
| 252 |
+
),
|
| 253 |
+
)
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--max_train_samples",
|
| 256 |
+
type=int,
|
| 257 |
+
default=None,
|
| 258 |
+
help=(
|
| 259 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 260 |
+
"value if set."
|
| 261 |
+
),
|
| 262 |
+
)
|
| 263 |
+
parser.add_argument(
|
| 264 |
+
"--output_dir",
|
| 265 |
+
type=str,
|
| 266 |
+
default="instruct-pix2pix-model",
|
| 267 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 268 |
+
)
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--cache_dir",
|
| 271 |
+
type=str,
|
| 272 |
+
default=None,
|
| 273 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 274 |
+
)
|
| 275 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 276 |
+
parser.add_argument(
|
| 277 |
+
"--resolution",
|
| 278 |
+
type=int,
|
| 279 |
+
default=256,
|
| 280 |
+
help=(
|
| 281 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 282 |
+
" resolution"
|
| 283 |
+
),
|
| 284 |
+
)
|
| 285 |
+
parser.add_argument(
|
| 286 |
+
"--center_crop",
|
| 287 |
+
default=False,
|
| 288 |
+
action="store_true",
|
| 289 |
+
help=(
|
| 290 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 291 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 292 |
+
),
|
| 293 |
+
)
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--random_flip",
|
| 296 |
+
action="store_true",
|
| 297 |
+
help="whether to randomly flip images horizontally",
|
| 298 |
+
)
|
| 299 |
+
parser.add_argument(
|
| 300 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 301 |
+
)
|
| 302 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--max_train_steps",
|
| 305 |
+
type=int,
|
| 306 |
+
default=None,
|
| 307 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 308 |
+
)
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"--gradient_accumulation_steps",
|
| 311 |
+
type=int,
|
| 312 |
+
default=1,
|
| 313 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 314 |
+
)
|
| 315 |
+
parser.add_argument(
|
| 316 |
+
"--gradient_checkpointing",
|
| 317 |
+
action="store_true",
|
| 318 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 319 |
+
)
|
| 320 |
+
parser.add_argument(
|
| 321 |
+
"--learning_rate",
|
| 322 |
+
type=float,
|
| 323 |
+
default=1e-4,
|
| 324 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 325 |
+
)
|
| 326 |
+
parser.add_argument(
|
| 327 |
+
"--scale_lr",
|
| 328 |
+
action="store_true",
|
| 329 |
+
default=False,
|
| 330 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 331 |
+
)
|
| 332 |
+
parser.add_argument(
|
| 333 |
+
"--lr_scheduler",
|
| 334 |
+
type=str,
|
| 335 |
+
default="constant",
|
| 336 |
+
help=(
|
| 337 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 338 |
+
' "constant", "constant_with_warmup"]'
|
| 339 |
+
),
|
| 340 |
+
)
|
| 341 |
+
parser.add_argument(
|
| 342 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 343 |
+
)
|
| 344 |
+
parser.add_argument(
|
| 345 |
+
"--conditioning_dropout_prob",
|
| 346 |
+
type=float,
|
| 347 |
+
default=None,
|
| 348 |
+
help="Conditioning dropout probability. Drops out the conditionings (image and edit prompt) used in training InstructPix2Pix. See section 3.2.1 in the paper: https://huggingface.co/papers/2211.09800.",
|
| 349 |
+
)
|
| 350 |
+
parser.add_argument(
|
| 351 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 352 |
+
)
|
| 353 |
+
parser.add_argument(
|
| 354 |
+
"--allow_tf32",
|
| 355 |
+
action="store_true",
|
| 356 |
+
help=(
|
| 357 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 358 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 359 |
+
),
|
| 360 |
+
)
|
| 361 |
+
parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--non_ema_revision",
|
| 364 |
+
type=str,
|
| 365 |
+
default=None,
|
| 366 |
+
required=False,
|
| 367 |
+
help=(
|
| 368 |
+
"Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
|
| 369 |
+
" remote repository specified with --pretrained_model_name_or_path."
|
| 370 |
+
),
|
| 371 |
+
)
|
| 372 |
+
parser.add_argument(
|
| 373 |
+
"--dataloader_num_workers",
|
| 374 |
+
type=int,
|
| 375 |
+
default=0,
|
| 376 |
+
help=(
|
| 377 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 378 |
+
),
|
| 379 |
+
)
|
| 380 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 381 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 382 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 383 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 384 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 385 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 386 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 387 |
+
parser.add_argument(
|
| 388 |
+
"--hub_model_id",
|
| 389 |
+
type=str,
|
| 390 |
+
default=None,
|
| 391 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 392 |
+
)
|
| 393 |
+
parser.add_argument(
|
| 394 |
+
"--logging_dir",
|
| 395 |
+
type=str,
|
| 396 |
+
default="logs",
|
| 397 |
+
help=(
|
| 398 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 399 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 400 |
+
),
|
| 401 |
+
)
|
| 402 |
+
parser.add_argument(
|
| 403 |
+
"--mixed_precision",
|
| 404 |
+
type=str,
|
| 405 |
+
default=None,
|
| 406 |
+
choices=["no", "fp16", "bf16"],
|
| 407 |
+
help=(
|
| 408 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 409 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 410 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 411 |
+
),
|
| 412 |
+
)
|
| 413 |
+
parser.add_argument(
|
| 414 |
+
"--report_to",
|
| 415 |
+
type=str,
|
| 416 |
+
default="tensorboard",
|
| 417 |
+
help=(
|
| 418 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 419 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 420 |
+
),
|
| 421 |
+
)
|
| 422 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 423 |
+
parser.add_argument(
|
| 424 |
+
"--checkpointing_steps",
|
| 425 |
+
type=int,
|
| 426 |
+
default=500,
|
| 427 |
+
help=(
|
| 428 |
+
"Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
|
| 429 |
+
" training using `--resume_from_checkpoint`."
|
| 430 |
+
),
|
| 431 |
+
)
|
| 432 |
+
parser.add_argument(
|
| 433 |
+
"--checkpoints_total_limit",
|
| 434 |
+
type=int,
|
| 435 |
+
default=None,
|
| 436 |
+
help=("Max number of checkpoints to store."),
|
| 437 |
+
)
|
| 438 |
+
parser.add_argument(
|
| 439 |
+
"--resume_from_checkpoint",
|
| 440 |
+
type=str,
|
| 441 |
+
default=None,
|
| 442 |
+
help=(
|
| 443 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 444 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 445 |
+
),
|
| 446 |
+
)
|
| 447 |
+
parser.add_argument(
|
| 448 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 449 |
+
)
|
| 450 |
+
parser.add_argument(
|
| 451 |
+
"--rank",
|
| 452 |
+
type=int,
|
| 453 |
+
default=4,
|
| 454 |
+
help=("The dimension of the LoRA update matrices."),
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
args = parser.parse_args()
|
| 458 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 459 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 460 |
+
args.local_rank = env_local_rank
|
| 461 |
+
|
| 462 |
+
# Sanity checks
|
| 463 |
+
if args.dataset_name is None and args.train_data_dir is None:
|
| 464 |
+
raise ValueError("Need either a dataset name or a training folder.")
|
| 465 |
+
|
| 466 |
+
# default to using the same revision for the non-ema model if not specified
|
| 467 |
+
if args.non_ema_revision is None:
|
| 468 |
+
args.non_ema_revision = args.revision
|
| 469 |
+
|
| 470 |
+
return args
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def convert_to_np(image, resolution):
|
| 474 |
+
image = image.convert("RGB").resize((resolution, resolution))
|
| 475 |
+
return np.array(image).transpose(2, 0, 1)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def download_image(url):
|
| 479 |
+
image = PIL.Image.open(requests.get(url, stream=True, timeout=DIFFUSERS_REQUEST_TIMEOUT).raw)
|
| 480 |
+
image = PIL.ImageOps.exif_transpose(image)
|
| 481 |
+
image = image.convert("RGB")
|
| 482 |
+
return image
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def main():
|
| 486 |
+
args = parse_args()
|
| 487 |
+
|
| 488 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 489 |
+
raise ValueError(
|
| 490 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 491 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
if args.non_ema_revision is not None:
|
| 495 |
+
deprecate(
|
| 496 |
+
"non_ema_revision!=None",
|
| 497 |
+
"0.15.0",
|
| 498 |
+
message=(
|
| 499 |
+
"Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
|
| 500 |
+
" use `--variant=non_ema` instead."
|
| 501 |
+
),
|
| 502 |
+
)
|
| 503 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 504 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 505 |
+
accelerator = Accelerator(
|
| 506 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 507 |
+
mixed_precision=args.mixed_precision,
|
| 508 |
+
log_with=args.report_to,
|
| 509 |
+
project_config=accelerator_project_config,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
# Disable AMP for MPS.
|
| 513 |
+
if torch.backends.mps.is_available():
|
| 514 |
+
accelerator.native_amp = False
|
| 515 |
+
|
| 516 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 517 |
+
|
| 518 |
+
# Make one log on every process with the configuration for debugging.
|
| 519 |
+
logging.basicConfig(
|
| 520 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 521 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 522 |
+
level=logging.INFO,
|
| 523 |
+
)
|
| 524 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 525 |
+
if accelerator.is_local_main_process:
|
| 526 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 527 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 528 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 529 |
+
else:
|
| 530 |
+
datasets.utils.logging.set_verbosity_error()
|
| 531 |
+
transformers.utils.logging.set_verbosity_error()
|
| 532 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 533 |
+
|
| 534 |
+
# If passed along, set the training seed now.
|
| 535 |
+
if args.seed is not None:
|
| 536 |
+
set_seed(args.seed)
|
| 537 |
+
|
| 538 |
+
# Handle the repository creation
|
| 539 |
+
if accelerator.is_main_process:
|
| 540 |
+
if args.output_dir is not None:
|
| 541 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 542 |
+
|
| 543 |
+
if args.push_to_hub:
|
| 544 |
+
repo_id = create_repo(
|
| 545 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 546 |
+
).repo_id
|
| 547 |
+
|
| 548 |
+
# Load scheduler, tokenizer and models.
|
| 549 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 550 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 551 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
|
| 552 |
+
)
|
| 553 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 554 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 555 |
+
)
|
| 556 |
+
vae = AutoencoderKL.from_pretrained(
|
| 557 |
+
args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision, variant=args.variant
|
| 558 |
+
)
|
| 559 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 560 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.non_ema_revision
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
# InstructPix2Pix uses an additional image for conditioning. To accommodate that,
|
| 564 |
+
# it uses 8 channels (instead of 4) in the first (conv) layer of the UNet. This UNet is
|
| 565 |
+
# then fine-tuned on the custom InstructPix2Pix dataset. This modified UNet is initialized
|
| 566 |
+
# from the pre-trained checkpoints. For the extra channels added to the first layer, they are
|
| 567 |
+
# initialized to zero.
|
| 568 |
+
logger.info("Initializing the InstructPix2Pix UNet from the pretrained UNet.")
|
| 569 |
+
in_channels = 8
|
| 570 |
+
out_channels = unet.conv_in.out_channels
|
| 571 |
+
unet.register_to_config(in_channels=in_channels)
|
| 572 |
+
|
| 573 |
+
with torch.no_grad():
|
| 574 |
+
new_conv_in = nn.Conv2d(
|
| 575 |
+
in_channels, out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding
|
| 576 |
+
)
|
| 577 |
+
new_conv_in.weight.zero_()
|
| 578 |
+
new_conv_in.weight[:, :in_channels, :, :].copy_(unet.conv_in.weight)
|
| 579 |
+
unet.conv_in = new_conv_in
|
| 580 |
+
|
| 581 |
+
# Freeze vae, text_encoder and unet
|
| 582 |
+
vae.requires_grad_(False)
|
| 583 |
+
text_encoder.requires_grad_(False)
|
| 584 |
+
unet.requires_grad_(False)
|
| 585 |
+
|
| 586 |
+
# referred to https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py
|
| 587 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 588 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 589 |
+
weight_dtype = torch.float32
|
| 590 |
+
if accelerator.mixed_precision == "fp16":
|
| 591 |
+
weight_dtype = torch.float16
|
| 592 |
+
elif accelerator.mixed_precision == "bf16":
|
| 593 |
+
weight_dtype = torch.bfloat16
|
| 594 |
+
|
| 595 |
+
# Freeze the unet parameters before adding adapters
|
| 596 |
+
unet.requires_grad_(False)
|
| 597 |
+
|
| 598 |
+
unet_lora_config = LoraConfig(
|
| 599 |
+
r=args.rank,
|
| 600 |
+
lora_alpha=args.rank,
|
| 601 |
+
init_lora_weights="gaussian",
|
| 602 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 606 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 607 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 608 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 609 |
+
|
| 610 |
+
# Add adapter and make sure the trainable params are in float32.
|
| 611 |
+
unet.add_adapter(unet_lora_config)
|
| 612 |
+
if args.mixed_precision == "fp16":
|
| 613 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 614 |
+
cast_training_params(unet, dtype=torch.float32)
|
| 615 |
+
|
| 616 |
+
# Create EMA for the unet.
|
| 617 |
+
if args.use_ema:
|
| 618 |
+
ema_unet = EMAModel(unet.parameters(), model_cls=UNet2DConditionModel, model_config=unet.config)
|
| 619 |
+
|
| 620 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 621 |
+
if is_xformers_available():
|
| 622 |
+
import xformers
|
| 623 |
+
|
| 624 |
+
xformers_version = version.parse(xformers.__version__)
|
| 625 |
+
if xformers_version == version.parse("0.0.16"):
|
| 626 |
+
logger.warning(
|
| 627 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 628 |
+
)
|
| 629 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 630 |
+
else:
|
| 631 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 632 |
+
|
| 633 |
+
trainable_params = filter(lambda p: p.requires_grad, unet.parameters())
|
| 634 |
+
|
| 635 |
+
def unwrap_model(model):
|
| 636 |
+
model = accelerator.unwrap_model(model)
|
| 637 |
+
model = model._orig_mod if is_compiled_module(model) else model
|
| 638 |
+
return model
|
| 639 |
+
|
| 640 |
+
# `accelerate` 0.16.0 will have better support for customized saving
|
| 641 |
+
if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
|
| 642 |
+
# create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
|
| 643 |
+
def save_model_hook(models, weights, output_dir):
|
| 644 |
+
if accelerator.is_main_process:
|
| 645 |
+
if args.use_ema:
|
| 646 |
+
ema_unet.save_pretrained(os.path.join(output_dir, "unet_ema"))
|
| 647 |
+
|
| 648 |
+
for i, model in enumerate(models):
|
| 649 |
+
model.save_pretrained(os.path.join(output_dir, "unet"))
|
| 650 |
+
|
| 651 |
+
# make sure to pop weight so that corresponding model is not saved again
|
| 652 |
+
if weights:
|
| 653 |
+
weights.pop()
|
| 654 |
+
|
| 655 |
+
def load_model_hook(models, input_dir):
|
| 656 |
+
if args.use_ema:
|
| 657 |
+
load_model = EMAModel.from_pretrained(os.path.join(input_dir, "unet_ema"), UNet2DConditionModel)
|
| 658 |
+
ema_unet.load_state_dict(load_model.state_dict())
|
| 659 |
+
ema_unet.to(accelerator.device)
|
| 660 |
+
del load_model
|
| 661 |
+
|
| 662 |
+
for i in range(len(models)):
|
| 663 |
+
# pop models so that they are not loaded again
|
| 664 |
+
model = models.pop()
|
| 665 |
+
|
| 666 |
+
# load diffusers style into model
|
| 667 |
+
load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
|
| 668 |
+
model.register_to_config(**load_model.config)
|
| 669 |
+
|
| 670 |
+
model.load_state_dict(load_model.state_dict())
|
| 671 |
+
del load_model
|
| 672 |
+
|
| 673 |
+
accelerator.register_save_state_pre_hook(save_model_hook)
|
| 674 |
+
accelerator.register_load_state_pre_hook(load_model_hook)
|
| 675 |
+
|
| 676 |
+
if args.gradient_checkpointing:
|
| 677 |
+
unet.enable_gradient_checkpointing()
|
| 678 |
+
|
| 679 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 680 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 681 |
+
if args.allow_tf32:
|
| 682 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 683 |
+
|
| 684 |
+
if args.scale_lr:
|
| 685 |
+
args.learning_rate = (
|
| 686 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
# Initialize the optimizer
|
| 690 |
+
if args.use_8bit_adam:
|
| 691 |
+
try:
|
| 692 |
+
import bitsandbytes as bnb
|
| 693 |
+
except ImportError:
|
| 694 |
+
raise ImportError(
|
| 695 |
+
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
optimizer_cls = bnb.optim.AdamW8bit
|
| 699 |
+
else:
|
| 700 |
+
optimizer_cls = torch.optim.AdamW
|
| 701 |
+
|
| 702 |
+
# train on only lora_layers
|
| 703 |
+
optimizer = optimizer_cls(
|
| 704 |
+
trainable_params,
|
| 705 |
+
lr=args.learning_rate,
|
| 706 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 707 |
+
weight_decay=args.adam_weight_decay,
|
| 708 |
+
eps=args.adam_epsilon,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Get the datasets: you can either provide your own training and evaluation files (see below)
|
| 712 |
+
# or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
|
| 713 |
+
|
| 714 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
| 715 |
+
# download the dataset.
|
| 716 |
+
if args.dataset_name is not None:
|
| 717 |
+
# Downloading and loading a dataset from the hub.
|
| 718 |
+
dataset = load_dataset(
|
| 719 |
+
args.dataset_name,
|
| 720 |
+
args.dataset_config_name,
|
| 721 |
+
cache_dir=args.cache_dir,
|
| 722 |
+
)
|
| 723 |
+
else:
|
| 724 |
+
data_files = {}
|
| 725 |
+
if args.train_data_dir is not None:
|
| 726 |
+
data_files["train"] = os.path.join(args.train_data_dir, "**")
|
| 727 |
+
dataset = load_dataset(
|
| 728 |
+
"imagefolder",
|
| 729 |
+
data_files=data_files,
|
| 730 |
+
cache_dir=args.cache_dir,
|
| 731 |
+
)
|
| 732 |
+
# See more about loading custom images at
|
| 733 |
+
# https://huggingface.co/docs/datasets/main/en/image_load#imagefolder
|
| 734 |
+
|
| 735 |
+
# Preprocessing the datasets.
|
| 736 |
+
# We need to tokenize inputs and targets.
|
| 737 |
+
column_names = dataset["train"].column_names
|
| 738 |
+
|
| 739 |
+
# 6. Get the column names for input/target.
|
| 740 |
+
dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
|
| 741 |
+
if args.original_image_column is None:
|
| 742 |
+
original_image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
|
| 743 |
+
else:
|
| 744 |
+
original_image_column = args.original_image_column
|
| 745 |
+
if original_image_column not in column_names:
|
| 746 |
+
raise ValueError(
|
| 747 |
+
f"--original_image_column' value '{args.original_image_column}' needs to be one of: {', '.join(column_names)}"
|
| 748 |
+
)
|
| 749 |
+
if args.edit_prompt_column is None:
|
| 750 |
+
edit_prompt_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
|
| 751 |
+
else:
|
| 752 |
+
edit_prompt_column = args.edit_prompt_column
|
| 753 |
+
if edit_prompt_column not in column_names:
|
| 754 |
+
raise ValueError(
|
| 755 |
+
f"--edit_prompt_column' value '{args.edit_prompt_column}' needs to be one of: {', '.join(column_names)}"
|
| 756 |
+
)
|
| 757 |
+
if args.edited_image_column is None:
|
| 758 |
+
edited_image_column = dataset_columns[2] if dataset_columns is not None else column_names[2]
|
| 759 |
+
else:
|
| 760 |
+
edited_image_column = args.edited_image_column
|
| 761 |
+
if edited_image_column not in column_names:
|
| 762 |
+
raise ValueError(
|
| 763 |
+
f"--edited_image_column' value '{args.edited_image_column}' needs to be one of: {', '.join(column_names)}"
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
# Preprocessing the datasets.
|
| 767 |
+
# We need to tokenize input captions and transform the images.
|
| 768 |
+
def tokenize_captions(captions):
|
| 769 |
+
inputs = tokenizer(
|
| 770 |
+
captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
|
| 771 |
+
)
|
| 772 |
+
return inputs.input_ids
|
| 773 |
+
|
| 774 |
+
# Preprocessing the datasets.
|
| 775 |
+
train_transforms = transforms.Compose(
|
| 776 |
+
[
|
| 777 |
+
transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
|
| 778 |
+
transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
|
| 779 |
+
]
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
def preprocess_images(examples):
|
| 783 |
+
original_images = np.concatenate(
|
| 784 |
+
[convert_to_np(image, args.resolution) for image in examples[original_image_column]]
|
| 785 |
+
)
|
| 786 |
+
edited_images = np.concatenate(
|
| 787 |
+
[convert_to_np(image, args.resolution) for image in examples[edited_image_column]]
|
| 788 |
+
)
|
| 789 |
+
# We need to ensure that the original and the edited images undergo the same
|
| 790 |
+
# augmentation transforms.
|
| 791 |
+
images = np.concatenate([original_images, edited_images])
|
| 792 |
+
images = torch.tensor(images)
|
| 793 |
+
images = 2 * (images / 255) - 1
|
| 794 |
+
return train_transforms(images)
|
| 795 |
+
|
| 796 |
+
def preprocess_train(examples):
|
| 797 |
+
# Preprocess images.
|
| 798 |
+
preprocessed_images = preprocess_images(examples)
|
| 799 |
+
# Since the original and edited images were concatenated before
|
| 800 |
+
# applying the transformations, we need to separate them and reshape
|
| 801 |
+
# them accordingly.
|
| 802 |
+
original_images, edited_images = preprocessed_images.chunk(2)
|
| 803 |
+
original_images = original_images.reshape(-1, 3, args.resolution, args.resolution)
|
| 804 |
+
edited_images = edited_images.reshape(-1, 3, args.resolution, args.resolution)
|
| 805 |
+
|
| 806 |
+
# Collate the preprocessed images into the `examples`.
|
| 807 |
+
examples["original_pixel_values"] = original_images
|
| 808 |
+
examples["edited_pixel_values"] = edited_images
|
| 809 |
+
|
| 810 |
+
# Preprocess the captions.
|
| 811 |
+
captions = list(examples[edit_prompt_column])
|
| 812 |
+
examples["input_ids"] = tokenize_captions(captions)
|
| 813 |
+
return examples
|
| 814 |
+
|
| 815 |
+
with accelerator.main_process_first():
|
| 816 |
+
if args.max_train_samples is not None:
|
| 817 |
+
dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 818 |
+
# Set the training transforms
|
| 819 |
+
train_dataset = dataset["train"].with_transform(preprocess_train)
|
| 820 |
+
|
| 821 |
+
def collate_fn(examples):
|
| 822 |
+
original_pixel_values = torch.stack([example["original_pixel_values"] for example in examples])
|
| 823 |
+
original_pixel_values = original_pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 824 |
+
edited_pixel_values = torch.stack([example["edited_pixel_values"] for example in examples])
|
| 825 |
+
edited_pixel_values = edited_pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 826 |
+
input_ids = torch.stack([example["input_ids"] for example in examples])
|
| 827 |
+
return {
|
| 828 |
+
"original_pixel_values": original_pixel_values,
|
| 829 |
+
"edited_pixel_values": edited_pixel_values,
|
| 830 |
+
"input_ids": input_ids,
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
# DataLoaders creation:
|
| 834 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 835 |
+
train_dataset,
|
| 836 |
+
shuffle=True,
|
| 837 |
+
collate_fn=collate_fn,
|
| 838 |
+
batch_size=args.train_batch_size,
|
| 839 |
+
num_workers=args.dataloader_num_workers,
|
| 840 |
+
)
|
| 841 |
+
|
| 842 |
+
# Scheduler and math around the number of training steps.
|
| 843 |
+
# Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
|
| 844 |
+
num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
|
| 845 |
+
if args.max_train_steps is None:
|
| 846 |
+
len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
|
| 847 |
+
num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
|
| 848 |
+
num_training_steps_for_scheduler = (
|
| 849 |
+
args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
|
| 850 |
+
)
|
| 851 |
+
else:
|
| 852 |
+
num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
|
| 853 |
+
|
| 854 |
+
lr_scheduler = get_scheduler(
|
| 855 |
+
args.lr_scheduler,
|
| 856 |
+
optimizer=optimizer,
|
| 857 |
+
num_warmup_steps=num_warmup_steps_for_scheduler,
|
| 858 |
+
num_training_steps=num_training_steps_for_scheduler,
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
# Prepare everything with our `accelerator`.
|
| 862 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 863 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
if args.use_ema:
|
| 867 |
+
ema_unet.to(accelerator.device)
|
| 868 |
+
|
| 869 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 870 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 871 |
+
weight_dtype = torch.float32
|
| 872 |
+
if accelerator.mixed_precision == "fp16":
|
| 873 |
+
weight_dtype = torch.float16
|
| 874 |
+
elif accelerator.mixed_precision == "bf16":
|
| 875 |
+
weight_dtype = torch.bfloat16
|
| 876 |
+
|
| 877 |
+
# Move text_encode and vae to gpu and cast to weight_dtype
|
| 878 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 879 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 880 |
+
|
| 881 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 882 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 883 |
+
if args.max_train_steps is None:
|
| 884 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 885 |
+
if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
|
| 886 |
+
logger.warning(
|
| 887 |
+
f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
|
| 888 |
+
f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
|
| 889 |
+
f"This inconsistency may result in the learning rate scheduler not functioning properly."
|
| 890 |
+
)
|
| 891 |
+
# Afterwards we recalculate our number of training epochs
|
| 892 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 893 |
+
|
| 894 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 895 |
+
# The trackers initializes automatically on the main process.
|
| 896 |
+
if accelerator.is_main_process:
|
| 897 |
+
accelerator.init_trackers("instruct-pix2pix", config=vars(args))
|
| 898 |
+
|
| 899 |
+
# Train!
|
| 900 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 901 |
+
|
| 902 |
+
logger.info("***** Running training *****")
|
| 903 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 904 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 905 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 906 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 907 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 908 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 909 |
+
global_step = 0
|
| 910 |
+
first_epoch = 0
|
| 911 |
+
|
| 912 |
+
# Potentially load in the weights and states from a previous save
|
| 913 |
+
if args.resume_from_checkpoint:
|
| 914 |
+
if args.resume_from_checkpoint != "latest":
|
| 915 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 916 |
+
else:
|
| 917 |
+
# Get the most recent checkpoint
|
| 918 |
+
dirs = os.listdir(args.output_dir)
|
| 919 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 920 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 921 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 922 |
+
|
| 923 |
+
if path is None:
|
| 924 |
+
accelerator.print(
|
| 925 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 926 |
+
)
|
| 927 |
+
args.resume_from_checkpoint = None
|
| 928 |
+
else:
|
| 929 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 930 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 931 |
+
global_step = int(path.split("-")[1])
|
| 932 |
+
|
| 933 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 934 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 935 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 936 |
+
|
| 937 |
+
# Only show the progress bar once on each machine.
|
| 938 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 939 |
+
progress_bar.set_description("Steps")
|
| 940 |
+
|
| 941 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 942 |
+
unet.train()
|
| 943 |
+
train_loss = 0.0
|
| 944 |
+
for step, batch in enumerate(train_dataloader):
|
| 945 |
+
# Skip steps until we reach the resumed step
|
| 946 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 947 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 948 |
+
progress_bar.update(1)
|
| 949 |
+
continue
|
| 950 |
+
|
| 951 |
+
with accelerator.accumulate(unet):
|
| 952 |
+
# We want to learn the denoising process w.r.t the edited images which
|
| 953 |
+
# are conditioned on the original image (which was edited) and the edit instruction.
|
| 954 |
+
# So, first, convert images to latent space.
|
| 955 |
+
latents = vae.encode(batch["edited_pixel_values"].to(weight_dtype)).latent_dist.sample()
|
| 956 |
+
latents = latents * vae.config.scaling_factor
|
| 957 |
+
|
| 958 |
+
# Sample noise that we'll add to the latents
|
| 959 |
+
noise = torch.randn_like(latents)
|
| 960 |
+
bsz = latents.shape[0]
|
| 961 |
+
# Sample a random timestep for each image
|
| 962 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 963 |
+
timesteps = timesteps.long()
|
| 964 |
+
|
| 965 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 966 |
+
# (this is the forward diffusion process)
|
| 967 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 968 |
+
|
| 969 |
+
# Get the text embedding for conditioning.
|
| 970 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 971 |
+
|
| 972 |
+
# Get the additional image embedding for conditioning.
|
| 973 |
+
# Instead of getting a diagonal Gaussian here, we simply take the mode.
|
| 974 |
+
original_image_embeds = vae.encode(batch["original_pixel_values"].to(weight_dtype)).latent_dist.mode()
|
| 975 |
+
|
| 976 |
+
# Conditioning dropout to support classifier-free guidance during inference. For more details
|
| 977 |
+
# check out the section 3.2.1 of the original paper https://huggingface.co/papers/2211.09800.
|
| 978 |
+
if args.conditioning_dropout_prob is not None:
|
| 979 |
+
random_p = torch.rand(bsz, device=latents.device, generator=generator)
|
| 980 |
+
# Sample masks for the edit prompts.
|
| 981 |
+
prompt_mask = random_p < 2 * args.conditioning_dropout_prob
|
| 982 |
+
prompt_mask = prompt_mask.reshape(bsz, 1, 1)
|
| 983 |
+
# Final text conditioning.
|
| 984 |
+
null_conditioning = text_encoder(tokenize_captions([""]).to(accelerator.device))[0]
|
| 985 |
+
encoder_hidden_states = torch.where(prompt_mask, null_conditioning, encoder_hidden_states)
|
| 986 |
+
|
| 987 |
+
# Sample masks for the original images.
|
| 988 |
+
image_mask_dtype = original_image_embeds.dtype
|
| 989 |
+
image_mask = 1 - (
|
| 990 |
+
(random_p >= args.conditioning_dropout_prob).to(image_mask_dtype)
|
| 991 |
+
* (random_p < 3 * args.conditioning_dropout_prob).to(image_mask_dtype)
|
| 992 |
+
)
|
| 993 |
+
image_mask = image_mask.reshape(bsz, 1, 1, 1)
|
| 994 |
+
# Final image conditioning.
|
| 995 |
+
original_image_embeds = image_mask * original_image_embeds
|
| 996 |
+
|
| 997 |
+
# Concatenate the `original_image_embeds` with the `noisy_latents`.
|
| 998 |
+
concatenated_noisy_latents = torch.cat([noisy_latents, original_image_embeds], dim=1)
|
| 999 |
+
|
| 1000 |
+
# Get the target for loss depending on the prediction type
|
| 1001 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 1002 |
+
target = noise
|
| 1003 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 1004 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 1005 |
+
else:
|
| 1006 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 1007 |
+
|
| 1008 |
+
# Predict the noise residual and compute loss
|
| 1009 |
+
model_pred = unet(concatenated_noisy_latents, timesteps, encoder_hidden_states, return_dict=False)[0]
|
| 1010 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 1011 |
+
|
| 1012 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 1013 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
|
| 1014 |
+
train_loss += avg_loss.item() / args.gradient_accumulation_steps
|
| 1015 |
+
|
| 1016 |
+
# Backpropagate
|
| 1017 |
+
accelerator.backward(loss)
|
| 1018 |
+
if accelerator.sync_gradients:
|
| 1019 |
+
accelerator.clip_grad_norm_(trainable_params, args.max_grad_norm)
|
| 1020 |
+
optimizer.step()
|
| 1021 |
+
lr_scheduler.step()
|
| 1022 |
+
optimizer.zero_grad()
|
| 1023 |
+
|
| 1024 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 1025 |
+
if accelerator.sync_gradients:
|
| 1026 |
+
if args.use_ema:
|
| 1027 |
+
ema_unet.step(trainable_params)
|
| 1028 |
+
progress_bar.update(1)
|
| 1029 |
+
global_step += 1
|
| 1030 |
+
accelerator.log({"train_loss": train_loss}, step=global_step)
|
| 1031 |
+
train_loss = 0.0
|
| 1032 |
+
|
| 1033 |
+
if global_step % args.checkpointing_steps == 0:
|
| 1034 |
+
if accelerator.is_main_process:
|
| 1035 |
+
# _before_ saving state, check if this save would set us over the `checkpoints_total_limit`
|
| 1036 |
+
if args.checkpoints_total_limit is not None:
|
| 1037 |
+
checkpoints = os.listdir(args.output_dir)
|
| 1038 |
+
checkpoints = [d for d in checkpoints if d.startswith("checkpoint")]
|
| 1039 |
+
checkpoints = sorted(checkpoints, key=lambda x: int(x.split("-")[1]))
|
| 1040 |
+
|
| 1041 |
+
# before we save the new checkpoint, we need to have at _most_ `checkpoints_total_limit - 1` checkpoints
|
| 1042 |
+
if len(checkpoints) >= args.checkpoints_total_limit:
|
| 1043 |
+
num_to_remove = len(checkpoints) - args.checkpoints_total_limit + 1
|
| 1044 |
+
removing_checkpoints = checkpoints[0:num_to_remove]
|
| 1045 |
+
|
| 1046 |
+
logger.info(
|
| 1047 |
+
f"{len(checkpoints)} checkpoints already exist, removing {len(removing_checkpoints)} checkpoints"
|
| 1048 |
+
)
|
| 1049 |
+
logger.info(f"removing checkpoints: {', '.join(removing_checkpoints)}")
|
| 1050 |
+
|
| 1051 |
+
for removing_checkpoint in removing_checkpoints:
|
| 1052 |
+
removing_checkpoint = os.path.join(args.output_dir, removing_checkpoint)
|
| 1053 |
+
shutil.rmtree(removing_checkpoint)
|
| 1054 |
+
|
| 1055 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 1056 |
+
accelerator.save_state(save_path)
|
| 1057 |
+
unwrapped_unet = unwrap_model(unet)
|
| 1058 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(
|
| 1059 |
+
get_peft_model_state_dict(unwrapped_unet)
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
StableDiffusionInstructPix2PixPipeline.save_lora_weights(
|
| 1063 |
+
save_directory=save_path,
|
| 1064 |
+
unet_lora_layers=unet_lora_state_dict,
|
| 1065 |
+
safe_serialization=True,
|
| 1066 |
+
)
|
| 1067 |
+
logger.info(f"Saved state to {save_path}")
|
| 1068 |
+
|
| 1069 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 1070 |
+
progress_bar.set_postfix(**logs)
|
| 1071 |
+
|
| 1072 |
+
if global_step >= args.max_train_steps:
|
| 1073 |
+
break
|
| 1074 |
+
|
| 1075 |
+
if accelerator.is_main_process:
|
| 1076 |
+
if (
|
| 1077 |
+
(args.val_image_url is not None)
|
| 1078 |
+
and (args.validation_prompt is not None)
|
| 1079 |
+
and (epoch % args.validation_epochs == 0)
|
| 1080 |
+
):
|
| 1081 |
+
logger.info(
|
| 1082 |
+
f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
|
| 1083 |
+
f" {args.validation_prompt}."
|
| 1084 |
+
)
|
| 1085 |
+
# create pipeline
|
| 1086 |
+
if args.use_ema:
|
| 1087 |
+
# Store the UNet parameters temporarily and load the EMA parameters to perform inference.
|
| 1088 |
+
ema_unet.store(unet.parameters())
|
| 1089 |
+
ema_unet.copy_to(unet.parameters())
|
| 1090 |
+
# The models need unwrapping because for compatibility in distributed training mode.
|
| 1091 |
+
pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
|
| 1092 |
+
args.pretrained_model_name_or_path,
|
| 1093 |
+
unet=unwrap_model(unet),
|
| 1094 |
+
text_encoder=unwrap_model(text_encoder),
|
| 1095 |
+
vae=unwrap_model(vae),
|
| 1096 |
+
revision=args.revision,
|
| 1097 |
+
variant=args.variant,
|
| 1098 |
+
torch_dtype=weight_dtype,
|
| 1099 |
+
)
|
| 1100 |
+
|
| 1101 |
+
# run inference
|
| 1102 |
+
log_validation(
|
| 1103 |
+
pipeline,
|
| 1104 |
+
args,
|
| 1105 |
+
accelerator,
|
| 1106 |
+
generator,
|
| 1107 |
+
)
|
| 1108 |
+
|
| 1109 |
+
if args.use_ema:
|
| 1110 |
+
# Switch back to the original UNet parameters.
|
| 1111 |
+
ema_unet.restore(unet.parameters())
|
| 1112 |
+
|
| 1113 |
+
del pipeline
|
| 1114 |
+
torch.cuda.empty_cache()
|
| 1115 |
+
|
| 1116 |
+
# Create the pipeline using the trained modules and save it.
|
| 1117 |
+
accelerator.wait_for_everyone()
|
| 1118 |
+
if accelerator.is_main_process:
|
| 1119 |
+
if args.use_ema:
|
| 1120 |
+
ema_unet.copy_to(unet.parameters())
|
| 1121 |
+
|
| 1122 |
+
# store only LORA layers
|
| 1123 |
+
unet = unet.to(torch.float32)
|
| 1124 |
+
|
| 1125 |
+
unwrapped_unet = unwrap_model(unet)
|
| 1126 |
+
unet_lora_state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(unwrapped_unet))
|
| 1127 |
+
StableDiffusionInstructPix2PixPipeline.save_lora_weights(
|
| 1128 |
+
save_directory=args.output_dir,
|
| 1129 |
+
unet_lora_layers=unet_lora_state_dict,
|
| 1130 |
+
safe_serialization=True,
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
|
| 1134 |
+
args.pretrained_model_name_or_path,
|
| 1135 |
+
text_encoder=unwrap_model(text_encoder),
|
| 1136 |
+
vae=unwrap_model(vae),
|
| 1137 |
+
unet=unwrap_model(unet),
|
| 1138 |
+
revision=args.revision,
|
| 1139 |
+
variant=args.variant,
|
| 1140 |
+
)
|
| 1141 |
+
pipeline.load_lora_weights(args.output_dir)
|
| 1142 |
+
|
| 1143 |
+
images = None
|
| 1144 |
+
if (args.val_image_url is not None) and (args.validation_prompt is not None):
|
| 1145 |
+
images = log_validation(
|
| 1146 |
+
pipeline,
|
| 1147 |
+
args,
|
| 1148 |
+
accelerator,
|
| 1149 |
+
generator,
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
if args.push_to_hub:
|
| 1153 |
+
save_model_card(
|
| 1154 |
+
repo_id,
|
| 1155 |
+
images=images,
|
| 1156 |
+
base_model=args.pretrained_model_name_or_path,
|
| 1157 |
+
dataset_name=args.dataset_name,
|
| 1158 |
+
repo_folder=args.output_dir,
|
| 1159 |
+
)
|
| 1160 |
+
upload_folder(
|
| 1161 |
+
repo_id=repo_id,
|
| 1162 |
+
folder_path=args.output_dir,
|
| 1163 |
+
commit_message="End of training",
|
| 1164 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
accelerator.end_training()
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
if __name__ == "__main__":
|
| 1171 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/README.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Diffusers examples with Intel optimizations
|
| 2 |
+
|
| 3 |
+
**This research project is not actively maintained by the diffusers team. For any questions or comments, please make sure to tag @hshen14 .**
|
| 4 |
+
|
| 5 |
+
This aims to provide diffusers examples with Intel optimizations such as Bfloat16 for training/fine-tuning acceleration and 8-bit integer (INT8) for inference acceleration on Intel platforms.
|
| 6 |
+
|
| 7 |
+
## Accelerating the fine-tuning for textual inversion
|
| 8 |
+
|
| 9 |
+
We accelerate the fine-tuning for textual inversion with Intel Extension for PyTorch. The [examples](textual_inversion) enable both single node and multi-node distributed training with Bfloat16 support on Intel Xeon Scalable Processor.
|
| 10 |
+
|
| 11 |
+
## Accelerating the inference for Stable Diffusion using Bfloat16
|
| 12 |
+
|
| 13 |
+
We start the inference acceleration with Bfloat16 using Intel Extension for PyTorch. The [script](inference_bf16.py) is generally designed to support standard Stable Diffusion models with Bfloat16 support.
|
| 14 |
+
```bash
|
| 15 |
+
pip install diffusers transformers accelerate scipy safetensors
|
| 16 |
+
|
| 17 |
+
export KMP_BLOCKTIME=1
|
| 18 |
+
export KMP_SETTINGS=1
|
| 19 |
+
export KMP_AFFINITY=granularity=fine,compact,1,0
|
| 20 |
+
|
| 21 |
+
# Intel OpenMP
|
| 22 |
+
export OMP_NUM_THREADS=< Cores to use >
|
| 23 |
+
export LD_PRELOAD=${LD_PRELOAD}:/path/to/lib/libiomp5.so
|
| 24 |
+
# Jemalloc is a recommended malloc implementation that emphasizes fragmentation avoidance and scalable concurrency support.
|
| 25 |
+
export LD_PRELOAD=${LD_PRELOAD}:/path/to/lib/libjemalloc.so
|
| 26 |
+
export MALLOC_CONF="oversize_threshold:1,background_thread:true,metadata_thp:auto,dirty_decay_ms:-1,muzzy_decay_ms:9000000000"
|
| 27 |
+
|
| 28 |
+
# Launch with default DDIM
|
| 29 |
+
numactl --membind <node N> -C <cpu list> python python inference_bf16.py
|
| 30 |
+
# Launch with DPMSolverMultistepScheduler
|
| 31 |
+
numactl --membind <node N> -C <cpu list> python python inference_bf16.py --dpm
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
## Accelerating the inference for Stable Diffusion using INT8
|
| 35 |
+
|
| 36 |
+
Coming soon ...
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/inference_bf16.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
|
| 3 |
+
import intel_extension_for_pytorch as ipex
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
parser = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False)
|
| 10 |
+
parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not")
|
| 11 |
+
parser.add_argument("--steps", default=None, type=int, help="Num inference steps")
|
| 12 |
+
args = parser.parse_args()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
device = "cpu"
|
| 16 |
+
prompt = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brightly buildings"
|
| 17 |
+
|
| 18 |
+
model_id = "path-to-your-trained-model"
|
| 19 |
+
pipe = StableDiffusionPipeline.from_pretrained(model_id)
|
| 20 |
+
if args.dpm:
|
| 21 |
+
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
| 22 |
+
pipe = pipe.to(device)
|
| 23 |
+
|
| 24 |
+
# to channels last
|
| 25 |
+
pipe.unet = pipe.unet.to(memory_format=torch.channels_last)
|
| 26 |
+
pipe.vae = pipe.vae.to(memory_format=torch.channels_last)
|
| 27 |
+
pipe.text_encoder = pipe.text_encoder.to(memory_format=torch.channels_last)
|
| 28 |
+
if pipe.requires_safety_checker:
|
| 29 |
+
pipe.safety_checker = pipe.safety_checker.to(memory_format=torch.channels_last)
|
| 30 |
+
|
| 31 |
+
# optimize with ipex
|
| 32 |
+
sample = torch.randn(2, 4, 64, 64)
|
| 33 |
+
timestep = torch.rand(1) * 999
|
| 34 |
+
encoder_hidden_status = torch.randn(2, 77, 768)
|
| 35 |
+
input_example = (sample, timestep, encoder_hidden_status)
|
| 36 |
+
try:
|
| 37 |
+
pipe.unet = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloat16, inplace=True, sample_input=input_example)
|
| 38 |
+
except Exception:
|
| 39 |
+
pipe.unet = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloat16, inplace=True)
|
| 40 |
+
pipe.vae = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloat16, inplace=True)
|
| 41 |
+
pipe.text_encoder = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)
|
| 42 |
+
if pipe.requires_safety_checker:
|
| 43 |
+
pipe.safety_checker = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloat16, inplace=True)
|
| 44 |
+
|
| 45 |
+
# compute
|
| 46 |
+
seed = 666
|
| 47 |
+
generator = torch.Generator(device).manual_seed(seed)
|
| 48 |
+
generate_kwargs = {"generator": generator}
|
| 49 |
+
if args.steps is not None:
|
| 50 |
+
generate_kwargs["num_inference_steps"] = args.steps
|
| 51 |
+
|
| 52 |
+
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
|
| 53 |
+
image = pipe(prompt, **generate_kwargs).images[0]
|
| 54 |
+
|
| 55 |
+
# save image
|
| 56 |
+
image.save("generated.png")
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/README.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Textual Inversion fine-tuning example
|
| 2 |
+
|
| 3 |
+
[Textual inversion](https://huggingface.co/papers/2208.01618) is a method to personalize text2image models like stable diffusion on your own images using just 3-5 examples.
|
| 4 |
+
The `textual_inversion.py` script shows how to implement the training procedure and adapt it for stable diffusion.
|
| 5 |
+
|
| 6 |
+
## Training with Intel Extension for PyTorch
|
| 7 |
+
|
| 8 |
+
Intel Extension for PyTorch provides the optimizations for faster training and inference on CPUs. You can leverage the training example "textual_inversion.py". Follow the [instructions](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion) to get the model and [dataset](https://huggingface.co/sd-concepts-library/dicoo2) before running the script.
|
| 9 |
+
|
| 10 |
+
The example supports both single node and multi-node distributed training:
|
| 11 |
+
|
| 12 |
+
### Single node training
|
| 13 |
+
|
| 14 |
+
```bash
|
| 15 |
+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
|
| 16 |
+
export DATA_DIR="path-to-dir-containing-dicoo-images"
|
| 17 |
+
|
| 18 |
+
python textual_inversion.py \
|
| 19 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 20 |
+
--train_data_dir=$DATA_DIR \
|
| 21 |
+
--learnable_property="object" \
|
| 22 |
+
--placeholder_token="<dicoo>" --initializer_token="toy" \
|
| 23 |
+
--seed=7 \
|
| 24 |
+
--resolution=512 \
|
| 25 |
+
--train_batch_size=1 \
|
| 26 |
+
--gradient_accumulation_steps=1 \
|
| 27 |
+
--max_train_steps=3000 \
|
| 28 |
+
--learning_rate=2.5e-03 --scale_lr \
|
| 29 |
+
--output_dir="textual_inversion_dicoo"
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Note: Bfloat16 is available on Intel Xeon Scalable Processors Cooper Lake or Sapphire Rapids. You may not get performance speedup without Bfloat16 support.
|
| 33 |
+
|
| 34 |
+
### Multi-node distributed training
|
| 35 |
+
|
| 36 |
+
Before running the scripts, make sure to install the library's training dependencies successfully:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python -m pip install oneccl_bind_pt==1.13 -f https://developer.intel.com/ipex-whl-stable-cpu
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
|
| 44 |
+
export DATA_DIR="path-to-dir-containing-dicoo-images"
|
| 45 |
+
|
| 46 |
+
oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
|
| 47 |
+
source $oneccl_bindings_for_pytorch_path/env/setvars.sh
|
| 48 |
+
|
| 49 |
+
python -m intel_extension_for_pytorch.cpu.launch --distributed \
|
| 50 |
+
--hostfile hostfile --nnodes 2 --nproc_per_node 2 textual_inversion.py \
|
| 51 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 52 |
+
--train_data_dir=$DATA_DIR \
|
| 53 |
+
--learnable_property="object" \
|
| 54 |
+
--placeholder_token="<dicoo>" --initializer_token="toy" \
|
| 55 |
+
--seed=7 \
|
| 56 |
+
--resolution=512 \
|
| 57 |
+
--train_batch_size=1 \
|
| 58 |
+
--gradient_accumulation_steps=1 \
|
| 59 |
+
--max_train_steps=750 \
|
| 60 |
+
--learning_rate=2.5e-03 --scale_lr \
|
| 61 |
+
--output_dir="textual_inversion_dicoo"
|
| 62 |
+
```
|
| 63 |
+
The above is a simple distributed training usage on 2 nodes with 2 processes on each node. Add the right hostname or ip address in the "hostfile" and make sure these 2 nodes are reachable from each other. For more details, please refer to the [user guide](https://github.com/intel/torch-ccl).
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
### Reference
|
| 67 |
+
|
| 68 |
+
We publish a [Medium blog](https://medium.com/intel-analytics-software/personalized-stable-diffusion-with-few-shot-fine-tuning-on-a-single-cpu-f01a3316b13) on how to create your own Stable Diffusion model on CPUs using textual inversion. Try it out now, if you have interests.
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.16.0
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.21.0
|
| 4 |
+
ftfy
|
| 5 |
+
tensorboard
|
| 6 |
+
Jinja2
|
| 7 |
+
intel_extension_for_pytorch>=1.13
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion/textual_inversion_bf16.py
ADDED
|
@@ -0,0 +1,646 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import intel_extension_for_pytorch as ipex
|
| 9 |
+
import numpy as np
|
| 10 |
+
import PIL
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import torch.utils.checkpoint
|
| 14 |
+
from accelerate import Accelerator
|
| 15 |
+
from accelerate.logging import get_logger
|
| 16 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 17 |
+
from huggingface_hub import create_repo, upload_folder
|
| 18 |
+
|
| 19 |
+
# TODO: remove and import from diffusers.utils when the new version of diffusers is released
|
| 20 |
+
from packaging import version
|
| 21 |
+
from PIL import Image
|
| 22 |
+
from torch.utils.data import Dataset
|
| 23 |
+
from torchvision import transforms
|
| 24 |
+
from tqdm.auto import tqdm
|
| 25 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
|
| 26 |
+
|
| 27 |
+
from diffusers import AutoencoderKL, DDPMScheduler, PNDMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
| 28 |
+
from diffusers.optimization import get_scheduler
|
| 29 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
|
| 30 |
+
from diffusers.utils import check_min_version
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
|
| 34 |
+
PIL_INTERPOLATION = {
|
| 35 |
+
"linear": PIL.Image.Resampling.BILINEAR,
|
| 36 |
+
"bilinear": PIL.Image.Resampling.BILINEAR,
|
| 37 |
+
"bicubic": PIL.Image.Resampling.BICUBIC,
|
| 38 |
+
"lanczos": PIL.Image.Resampling.LANCZOS,
|
| 39 |
+
"nearest": PIL.Image.Resampling.NEAREST,
|
| 40 |
+
}
|
| 41 |
+
else:
|
| 42 |
+
PIL_INTERPOLATION = {
|
| 43 |
+
"linear": PIL.Image.LINEAR,
|
| 44 |
+
"bilinear": PIL.Image.BILINEAR,
|
| 45 |
+
"bicubic": PIL.Image.BICUBIC,
|
| 46 |
+
"lanczos": PIL.Image.LANCZOS,
|
| 47 |
+
"nearest": PIL.Image.NEAREST,
|
| 48 |
+
}
|
| 49 |
+
# ------------------------------------------------------------------------------
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 53 |
+
check_min_version("0.13.0.dev0")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path):
|
| 60 |
+
logger.info("Saving embeddings")
|
| 61 |
+
learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]
|
| 62 |
+
learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
|
| 63 |
+
torch.save(learned_embeds_dict, save_path)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def parse_args():
|
| 67 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--save_steps",
|
| 70 |
+
type=int,
|
| 71 |
+
default=500,
|
| 72 |
+
help="Save learned_embeds.bin every X updates steps.",
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--only_save_embeds",
|
| 76 |
+
action="store_true",
|
| 77 |
+
default=False,
|
| 78 |
+
help="Save only the embeddings for the new concept.",
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--pretrained_model_name_or_path",
|
| 82 |
+
type=str,
|
| 83 |
+
default=None,
|
| 84 |
+
required=True,
|
| 85 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--revision",
|
| 89 |
+
type=str,
|
| 90 |
+
default=None,
|
| 91 |
+
required=False,
|
| 92 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--tokenizer_name",
|
| 96 |
+
type=str,
|
| 97 |
+
default=None,
|
| 98 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--placeholder_token",
|
| 105 |
+
type=str,
|
| 106 |
+
default=None,
|
| 107 |
+
required=True,
|
| 108 |
+
help="A token to use as a placeholder for the concept.",
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument(
|
| 111 |
+
"--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
|
| 114 |
+
parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
|
| 115 |
+
parser.add_argument(
|
| 116 |
+
"--output_dir",
|
| 117 |
+
type=str,
|
| 118 |
+
default="text-inversion-model",
|
| 119 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--resolution",
|
| 124 |
+
type=int,
|
| 125 |
+
default=512,
|
| 126 |
+
help=(
|
| 127 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 128 |
+
" resolution"
|
| 129 |
+
),
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument(
|
| 132 |
+
"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution."
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--max_train_steps",
|
| 140 |
+
type=int,
|
| 141 |
+
default=5000,
|
| 142 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 143 |
+
)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--gradient_accumulation_steps",
|
| 146 |
+
type=int,
|
| 147 |
+
default=1,
|
| 148 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--learning_rate",
|
| 152 |
+
type=float,
|
| 153 |
+
default=1e-4,
|
| 154 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 155 |
+
)
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--scale_lr",
|
| 158 |
+
action="store_true",
|
| 159 |
+
default=True,
|
| 160 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 161 |
+
)
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--lr_scheduler",
|
| 164 |
+
type=str,
|
| 165 |
+
default="constant",
|
| 166 |
+
help=(
|
| 167 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 168 |
+
' "constant", "constant_with_warmup"]'
|
| 169 |
+
),
|
| 170 |
+
)
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 175 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 176 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 177 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 178 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 179 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--hub_model_id",
|
| 182 |
+
type=str,
|
| 183 |
+
default=None,
|
| 184 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--logging_dir",
|
| 188 |
+
type=str,
|
| 189 |
+
default="logs",
|
| 190 |
+
help=(
|
| 191 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 192 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 193 |
+
),
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--mixed_precision",
|
| 197 |
+
type=str,
|
| 198 |
+
default="no",
|
| 199 |
+
choices=["no", "fp16", "bf16"],
|
| 200 |
+
help=(
|
| 201 |
+
"Whether to use mixed precision. Choose"
|
| 202 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 203 |
+
"and an Nvidia Ampere GPU."
|
| 204 |
+
),
|
| 205 |
+
)
|
| 206 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 207 |
+
|
| 208 |
+
args = parser.parse_args()
|
| 209 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 210 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 211 |
+
args.local_rank = env_local_rank
|
| 212 |
+
|
| 213 |
+
if args.train_data_dir is None:
|
| 214 |
+
raise ValueError("You must specify a train data directory.")
|
| 215 |
+
|
| 216 |
+
return args
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
imagenet_templates_small = [
|
| 220 |
+
"a photo of a {}",
|
| 221 |
+
"a rendering of a {}",
|
| 222 |
+
"a cropped photo of the {}",
|
| 223 |
+
"the photo of a {}",
|
| 224 |
+
"a photo of a clean {}",
|
| 225 |
+
"a photo of a dirty {}",
|
| 226 |
+
"a dark photo of the {}",
|
| 227 |
+
"a photo of my {}",
|
| 228 |
+
"a photo of the cool {}",
|
| 229 |
+
"a close-up photo of a {}",
|
| 230 |
+
"a bright photo of the {}",
|
| 231 |
+
"a cropped photo of a {}",
|
| 232 |
+
"a photo of the {}",
|
| 233 |
+
"a good photo of the {}",
|
| 234 |
+
"a photo of one {}",
|
| 235 |
+
"a close-up photo of the {}",
|
| 236 |
+
"a rendition of the {}",
|
| 237 |
+
"a photo of the clean {}",
|
| 238 |
+
"a rendition of a {}",
|
| 239 |
+
"a photo of a nice {}",
|
| 240 |
+
"a good photo of a {}",
|
| 241 |
+
"a photo of the nice {}",
|
| 242 |
+
"a photo of the small {}",
|
| 243 |
+
"a photo of the weird {}",
|
| 244 |
+
"a photo of the large {}",
|
| 245 |
+
"a photo of a cool {}",
|
| 246 |
+
"a photo of a small {}",
|
| 247 |
+
]
|
| 248 |
+
|
| 249 |
+
imagenet_style_templates_small = [
|
| 250 |
+
"a painting in the style of {}",
|
| 251 |
+
"a rendering in the style of {}",
|
| 252 |
+
"a cropped painting in the style of {}",
|
| 253 |
+
"the painting in the style of {}",
|
| 254 |
+
"a clean painting in the style of {}",
|
| 255 |
+
"a dirty painting in the style of {}",
|
| 256 |
+
"a dark painting in the style of {}",
|
| 257 |
+
"a picture in the style of {}",
|
| 258 |
+
"a cool painting in the style of {}",
|
| 259 |
+
"a close-up painting in the style of {}",
|
| 260 |
+
"a bright painting in the style of {}",
|
| 261 |
+
"a cropped painting in the style of {}",
|
| 262 |
+
"a good painting in the style of {}",
|
| 263 |
+
"a close-up painting in the style of {}",
|
| 264 |
+
"a rendition in the style of {}",
|
| 265 |
+
"a nice painting in the style of {}",
|
| 266 |
+
"a small painting in the style of {}",
|
| 267 |
+
"a weird painting in the style of {}",
|
| 268 |
+
"a large painting in the style of {}",
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class TextualInversionDataset(Dataset):
|
| 273 |
+
def __init__(
|
| 274 |
+
self,
|
| 275 |
+
data_root,
|
| 276 |
+
tokenizer,
|
| 277 |
+
learnable_property="object", # [object, style]
|
| 278 |
+
size=512,
|
| 279 |
+
repeats=100,
|
| 280 |
+
interpolation="bicubic",
|
| 281 |
+
flip_p=0.5,
|
| 282 |
+
set="train",
|
| 283 |
+
placeholder_token="*",
|
| 284 |
+
center_crop=False,
|
| 285 |
+
):
|
| 286 |
+
self.data_root = data_root
|
| 287 |
+
self.tokenizer = tokenizer
|
| 288 |
+
self.learnable_property = learnable_property
|
| 289 |
+
self.size = size
|
| 290 |
+
self.placeholder_token = placeholder_token
|
| 291 |
+
self.center_crop = center_crop
|
| 292 |
+
self.flip_p = flip_p
|
| 293 |
+
|
| 294 |
+
self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
|
| 295 |
+
|
| 296 |
+
self.num_images = len(self.image_paths)
|
| 297 |
+
self._length = self.num_images
|
| 298 |
+
|
| 299 |
+
if set == "train":
|
| 300 |
+
self._length = self.num_images * repeats
|
| 301 |
+
|
| 302 |
+
self.interpolation = {
|
| 303 |
+
"linear": PIL_INTERPOLATION["linear"],
|
| 304 |
+
"bilinear": PIL_INTERPOLATION["bilinear"],
|
| 305 |
+
"bicubic": PIL_INTERPOLATION["bicubic"],
|
| 306 |
+
"lanczos": PIL_INTERPOLATION["lanczos"],
|
| 307 |
+
}[interpolation]
|
| 308 |
+
|
| 309 |
+
self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
|
| 310 |
+
self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
|
| 311 |
+
|
| 312 |
+
def __len__(self):
|
| 313 |
+
return self._length
|
| 314 |
+
|
| 315 |
+
def __getitem__(self, i):
|
| 316 |
+
example = {}
|
| 317 |
+
image = Image.open(self.image_paths[i % self.num_images])
|
| 318 |
+
|
| 319 |
+
if not image.mode == "RGB":
|
| 320 |
+
image = image.convert("RGB")
|
| 321 |
+
|
| 322 |
+
placeholder_string = self.placeholder_token
|
| 323 |
+
text = random.choice(self.templates).format(placeholder_string)
|
| 324 |
+
|
| 325 |
+
example["input_ids"] = self.tokenizer(
|
| 326 |
+
text,
|
| 327 |
+
padding="max_length",
|
| 328 |
+
truncation=True,
|
| 329 |
+
max_length=self.tokenizer.model_max_length,
|
| 330 |
+
return_tensors="pt",
|
| 331 |
+
).input_ids[0]
|
| 332 |
+
|
| 333 |
+
# default to score-sde preprocessing
|
| 334 |
+
img = np.array(image).astype(np.uint8)
|
| 335 |
+
|
| 336 |
+
if self.center_crop:
|
| 337 |
+
crop = min(img.shape[0], img.shape[1])
|
| 338 |
+
(
|
| 339 |
+
h,
|
| 340 |
+
w,
|
| 341 |
+
) = (
|
| 342 |
+
img.shape[0],
|
| 343 |
+
img.shape[1],
|
| 344 |
+
)
|
| 345 |
+
img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
|
| 346 |
+
|
| 347 |
+
image = Image.fromarray(img)
|
| 348 |
+
image = image.resize((self.size, self.size), resample=self.interpolation)
|
| 349 |
+
|
| 350 |
+
image = self.flip_transform(image)
|
| 351 |
+
image = np.array(image).astype(np.uint8)
|
| 352 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
| 353 |
+
|
| 354 |
+
example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
|
| 355 |
+
return example
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def freeze_params(params):
|
| 359 |
+
for param in params:
|
| 360 |
+
param.requires_grad = False
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def main():
|
| 364 |
+
args = parse_args()
|
| 365 |
+
|
| 366 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 369 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 373 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 374 |
+
accelerator = Accelerator(
|
| 375 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 376 |
+
mixed_precision=args.mixed_precision,
|
| 377 |
+
log_with=args.report_to,
|
| 378 |
+
project_config=accelerator_project_config,
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Disable AMP for MPS.
|
| 382 |
+
if torch.backends.mps.is_available():
|
| 383 |
+
accelerator.native_amp = False
|
| 384 |
+
|
| 385 |
+
# If passed along, set the training seed now.
|
| 386 |
+
if args.seed is not None:
|
| 387 |
+
set_seed(args.seed)
|
| 388 |
+
|
| 389 |
+
# Handle the repository creation
|
| 390 |
+
if accelerator.is_main_process:
|
| 391 |
+
if args.output_dir is not None:
|
| 392 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 393 |
+
|
| 394 |
+
if args.push_to_hub:
|
| 395 |
+
repo_id = create_repo(
|
| 396 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 397 |
+
).repo_id
|
| 398 |
+
|
| 399 |
+
# Load the tokenizer and add the placeholder token as a additional special token
|
| 400 |
+
if args.tokenizer_name:
|
| 401 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 402 |
+
elif args.pretrained_model_name_or_path:
|
| 403 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 404 |
+
|
| 405 |
+
# Add the placeholder token in tokenizer
|
| 406 |
+
num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
|
| 407 |
+
if num_added_tokens == 0:
|
| 408 |
+
raise ValueError(
|
| 409 |
+
f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
|
| 410 |
+
" `placeholder_token` that is not already in the tokenizer."
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
# Convert the initializer_token, placeholder_token to ids
|
| 414 |
+
token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
|
| 415 |
+
# Check if initializer_token is a single token or a sequence of tokens
|
| 416 |
+
if len(token_ids) > 1:
|
| 417 |
+
raise ValueError("The initializer token must be a single token.")
|
| 418 |
+
|
| 419 |
+
initializer_token_id = token_ids[0]
|
| 420 |
+
placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
|
| 421 |
+
|
| 422 |
+
# Load models and create wrapper for stable diffusion
|
| 423 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 424 |
+
args.pretrained_model_name_or_path,
|
| 425 |
+
subfolder="text_encoder",
|
| 426 |
+
revision=args.revision,
|
| 427 |
+
)
|
| 428 |
+
vae = AutoencoderKL.from_pretrained(
|
| 429 |
+
args.pretrained_model_name_or_path,
|
| 430 |
+
subfolder="vae",
|
| 431 |
+
revision=args.revision,
|
| 432 |
+
)
|
| 433 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 434 |
+
args.pretrained_model_name_or_path,
|
| 435 |
+
subfolder="unet",
|
| 436 |
+
revision=args.revision,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
# Resize the token embeddings as we are adding new special tokens to the tokenizer
|
| 440 |
+
text_encoder.resize_token_embeddings(len(tokenizer))
|
| 441 |
+
|
| 442 |
+
# Initialise the newly added placeholder token with the embeddings of the initializer token
|
| 443 |
+
token_embeds = text_encoder.get_input_embeddings().weight.data
|
| 444 |
+
token_embeds[placeholder_token_id] = token_embeds[initializer_token_id]
|
| 445 |
+
|
| 446 |
+
# Freeze vae and unet
|
| 447 |
+
freeze_params(vae.parameters())
|
| 448 |
+
freeze_params(unet.parameters())
|
| 449 |
+
# Freeze all parameters except for the token embeddings in text encoder
|
| 450 |
+
params_to_freeze = itertools.chain(
|
| 451 |
+
text_encoder.text_model.encoder.parameters(),
|
| 452 |
+
text_encoder.text_model.final_layer_norm.parameters(),
|
| 453 |
+
text_encoder.text_model.embeddings.position_embedding.parameters(),
|
| 454 |
+
)
|
| 455 |
+
freeze_params(params_to_freeze)
|
| 456 |
+
|
| 457 |
+
if args.scale_lr:
|
| 458 |
+
args.learning_rate = (
|
| 459 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Initialize the optimizer
|
| 463 |
+
optimizer = torch.optim.AdamW(
|
| 464 |
+
text_encoder.get_input_embeddings().parameters(), # only optimize the embeddings
|
| 465 |
+
lr=args.learning_rate,
|
| 466 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 467 |
+
weight_decay=args.adam_weight_decay,
|
| 468 |
+
eps=args.adam_epsilon,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 472 |
+
|
| 473 |
+
train_dataset = TextualInversionDataset(
|
| 474 |
+
data_root=args.train_data_dir,
|
| 475 |
+
tokenizer=tokenizer,
|
| 476 |
+
size=args.resolution,
|
| 477 |
+
placeholder_token=args.placeholder_token,
|
| 478 |
+
repeats=args.repeats,
|
| 479 |
+
learnable_property=args.learnable_property,
|
| 480 |
+
center_crop=args.center_crop,
|
| 481 |
+
set="train",
|
| 482 |
+
)
|
| 483 |
+
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True)
|
| 484 |
+
|
| 485 |
+
# Scheduler and math around the number of training steps.
|
| 486 |
+
overrode_max_train_steps = False
|
| 487 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 488 |
+
if args.max_train_steps is None:
|
| 489 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 490 |
+
overrode_max_train_steps = True
|
| 491 |
+
|
| 492 |
+
lr_scheduler = get_scheduler(
|
| 493 |
+
args.lr_scheduler,
|
| 494 |
+
optimizer=optimizer,
|
| 495 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 496 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 500 |
+
text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
# Move vae and unet to device
|
| 504 |
+
vae.to(accelerator.device)
|
| 505 |
+
unet.to(accelerator.device)
|
| 506 |
+
|
| 507 |
+
# Keep vae and unet in eval model as we don't train these
|
| 508 |
+
vae.eval()
|
| 509 |
+
unet.eval()
|
| 510 |
+
|
| 511 |
+
unet = ipex.optimize(unet, dtype=torch.bfloat16, inplace=True)
|
| 512 |
+
vae = ipex.optimize(vae, dtype=torch.bfloat16, inplace=True)
|
| 513 |
+
|
| 514 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 515 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 516 |
+
if overrode_max_train_steps:
|
| 517 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 518 |
+
# Afterwards we recalculate our number of training epochs
|
| 519 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 520 |
+
|
| 521 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 522 |
+
# The trackers initializes automatically on the main process.
|
| 523 |
+
if accelerator.is_main_process:
|
| 524 |
+
accelerator.init_trackers("textual_inversion", config=vars(args))
|
| 525 |
+
|
| 526 |
+
# Train!
|
| 527 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 528 |
+
|
| 529 |
+
logger.info("***** Running training *****")
|
| 530 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 531 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 532 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 533 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 534 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 535 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 536 |
+
# Only show the progress bar once on each machine.
|
| 537 |
+
progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 538 |
+
progress_bar.set_description("Steps")
|
| 539 |
+
global_step = 0
|
| 540 |
+
|
| 541 |
+
text_encoder.train()
|
| 542 |
+
text_encoder, optimizer = ipex.optimize(text_encoder, optimizer=optimizer, dtype=torch.bfloat16)
|
| 543 |
+
|
| 544 |
+
for epoch in range(args.num_train_epochs):
|
| 545 |
+
for step, batch in enumerate(train_dataloader):
|
| 546 |
+
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
|
| 547 |
+
with accelerator.accumulate(text_encoder):
|
| 548 |
+
# Convert images to latent space
|
| 549 |
+
latents = vae.encode(batch["pixel_values"]).latent_dist.sample().detach()
|
| 550 |
+
latents = latents * vae.config.scaling_factor
|
| 551 |
+
|
| 552 |
+
# Sample noise that we'll add to the latents
|
| 553 |
+
noise = torch.randn(latents.shape).to(latents.device)
|
| 554 |
+
bsz = latents.shape[0]
|
| 555 |
+
# Sample a random timestep for each image
|
| 556 |
+
timesteps = torch.randint(
|
| 557 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
|
| 558 |
+
).long()
|
| 559 |
+
|
| 560 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 561 |
+
# (this is the forward diffusion process)
|
| 562 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 563 |
+
|
| 564 |
+
# Get the text embedding for conditioning
|
| 565 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 566 |
+
|
| 567 |
+
# Predict the noise residual
|
| 568 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 569 |
+
|
| 570 |
+
# Get the target for loss depending on the prediction type
|
| 571 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 572 |
+
target = noise
|
| 573 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 574 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 575 |
+
else:
|
| 576 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 577 |
+
|
| 578 |
+
loss = F.mse_loss(model_pred, target, reduction="none").mean([1, 2, 3]).mean()
|
| 579 |
+
accelerator.backward(loss)
|
| 580 |
+
|
| 581 |
+
# Zero out the gradients for all token embeddings except the newly added
|
| 582 |
+
# embeddings for the concept, as we only want to optimize the concept embeddings
|
| 583 |
+
if accelerator.num_processes > 1:
|
| 584 |
+
grads = text_encoder.module.get_input_embeddings().weight.grad
|
| 585 |
+
else:
|
| 586 |
+
grads = text_encoder.get_input_embeddings().weight.grad
|
| 587 |
+
# Get the index for tokens that we want to zero the grads for
|
| 588 |
+
index_grads_to_zero = torch.arange(len(tokenizer)) != placeholder_token_id
|
| 589 |
+
grads.data[index_grads_to_zero, :] = grads.data[index_grads_to_zero, :].fill_(0)
|
| 590 |
+
|
| 591 |
+
optimizer.step()
|
| 592 |
+
lr_scheduler.step()
|
| 593 |
+
optimizer.zero_grad()
|
| 594 |
+
|
| 595 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 596 |
+
if accelerator.sync_gradients:
|
| 597 |
+
progress_bar.update(1)
|
| 598 |
+
global_step += 1
|
| 599 |
+
if global_step % args.save_steps == 0:
|
| 600 |
+
save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
|
| 601 |
+
save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
|
| 602 |
+
|
| 603 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 604 |
+
progress_bar.set_postfix(**logs)
|
| 605 |
+
accelerator.log(logs, step=global_step)
|
| 606 |
+
|
| 607 |
+
if global_step >= args.max_train_steps:
|
| 608 |
+
break
|
| 609 |
+
|
| 610 |
+
accelerator.wait_for_everyone()
|
| 611 |
+
|
| 612 |
+
# Create the pipeline using using the trained modules and save it.
|
| 613 |
+
if accelerator.is_main_process:
|
| 614 |
+
if args.push_to_hub and args.only_save_embeds:
|
| 615 |
+
logger.warning("Enabling full model saving because --push_to_hub=True was specified.")
|
| 616 |
+
save_full_model = True
|
| 617 |
+
else:
|
| 618 |
+
save_full_model = not args.only_save_embeds
|
| 619 |
+
if save_full_model:
|
| 620 |
+
pipeline = StableDiffusionPipeline(
|
| 621 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 622 |
+
vae=vae,
|
| 623 |
+
unet=unet,
|
| 624 |
+
tokenizer=tokenizer,
|
| 625 |
+
scheduler=PNDMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler"),
|
| 626 |
+
safety_checker=StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker"),
|
| 627 |
+
feature_extractor=CLIPImageProcessor.from_pretrained("openai/clip-vit-base-patch32"),
|
| 628 |
+
)
|
| 629 |
+
pipeline.save_pretrained(args.output_dir)
|
| 630 |
+
# Save the newly trained embeddings
|
| 631 |
+
save_path = os.path.join(args.output_dir, "learned_embeds.bin")
|
| 632 |
+
save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
|
| 633 |
+
|
| 634 |
+
if args.push_to_hub:
|
| 635 |
+
upload_folder(
|
| 636 |
+
repo_id=repo_id,
|
| 637 |
+
folder_path=args.output_dir,
|
| 638 |
+
commit_message="End of training",
|
| 639 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
accelerator.end_training()
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
if __name__ == "__main__":
|
| 646 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Distillation for quantization on Textual Inversion models to personalize text2image
|
| 2 |
+
|
| 3 |
+
[Textual inversion](https://huggingface.co/papers/2208.01618) is a method to personalize text2image models like stable diffusion on your own images._By using just 3-5 images new concepts can be taught to Stable Diffusion and the model personalized on your own images_
|
| 4 |
+
The `textual_inversion.py` script shows how to implement the training procedure and adapt it for stable diffusion.
|
| 5 |
+
We have enabled distillation for quantization in `textual_inversion.py` to do quantization aware training as well as distillation on the model generated by Textual Inversion method.
|
| 6 |
+
|
| 7 |
+
## Installing the dependencies
|
| 8 |
+
|
| 9 |
+
Before running the scripts, make sure to install the library's training dependencies:
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
pip install -r requirements.txt
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## Prepare Datasets
|
| 16 |
+
|
| 17 |
+
One picture which is from the huggingface datasets [sd-concepts-library/dicoo2](https://huggingface.co/sd-concepts-library/dicoo2) is needed, and save it to the `./dicoo` directory. The picture is shown below:
|
| 18 |
+
|
| 19 |
+
<a href="https://huggingface.co/sd-concepts-library/dicoo2/blob/main/concept_images/1.jpeg">
|
| 20 |
+
<img src="https://huggingface.co/sd-concepts-library/dicoo2/resolve/main/concept_images/1.jpeg" width = "300" height="300">
|
| 21 |
+
</a>
|
| 22 |
+
|
| 23 |
+
## Get a FP32 Textual Inversion model
|
| 24 |
+
|
| 25 |
+
Use the following command to fine-tune the Stable Diffusion model on the above dataset to obtain the FP32 Textual Inversion model.
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
|
| 29 |
+
export DATA_DIR="./dicoo"
|
| 30 |
+
|
| 31 |
+
accelerate launch textual_inversion.py \
|
| 32 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 33 |
+
--train_data_dir=$DATA_DIR \
|
| 34 |
+
--learnable_property="object" \
|
| 35 |
+
--placeholder_token="<dicoo>" --initializer_token="toy" \
|
| 36 |
+
--resolution=512 \
|
| 37 |
+
--train_batch_size=1 \
|
| 38 |
+
--gradient_accumulation_steps=4 \
|
| 39 |
+
--max_train_steps=3000 \
|
| 40 |
+
--learning_rate=5.0e-04 --scale_lr \
|
| 41 |
+
--lr_scheduler="constant" \
|
| 42 |
+
--lr_warmup_steps=0 \
|
| 43 |
+
--output_dir="dicoo_model"
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## Do distillation for quantization
|
| 47 |
+
|
| 48 |
+
Distillation for quantization is a method that combines [intermediate layer knowledge distillation](https://github.com/intel/neural-compressor/blob/master/docs/source/distillation.md#intermediate-layer-knowledge-distillation) and [quantization aware training](https://github.com/intel/neural-compressor/blob/master/docs/source/quantization.md#quantization-aware-training) in the same training process to improve the performance of the quantized model. Provided a FP32 model, the distillation for quantization approach will take this model itself as the teacher model and transfer the knowledges of the specified layers to the student model, i.e. quantized version of the FP32 model, during the quantization aware training process.
|
| 49 |
+
|
| 50 |
+
Once you have the FP32 Textual Inversion model, the following command will take the FP32 Textual Inversion model as input to do distillation for quantization and generate the INT8 Textual Inversion model.
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
export FP32_MODEL_NAME="./dicoo_model"
|
| 54 |
+
export DATA_DIR="./dicoo"
|
| 55 |
+
|
| 56 |
+
accelerate launch textual_inversion.py \
|
| 57 |
+
--pretrained_model_name_or_path=$FP32_MODEL_NAME \
|
| 58 |
+
--train_data_dir=$DATA_DIR \
|
| 59 |
+
--use_ema --learnable_property="object" \
|
| 60 |
+
--placeholder_token="<dicoo>" --initializer_token="toy" \
|
| 61 |
+
--resolution=512 \
|
| 62 |
+
--train_batch_size=1 \
|
| 63 |
+
--gradient_accumulation_steps=4 \
|
| 64 |
+
--max_train_steps=300 \
|
| 65 |
+
--learning_rate=5.0e-04 --max_grad_norm=3 \
|
| 66 |
+
--lr_scheduler="constant" \
|
| 67 |
+
--lr_warmup_steps=0 \
|
| 68 |
+
--output_dir="int8_model" \
|
| 69 |
+
--do_quantization --do_distillation --verify_loading
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
After the distillation for quantization process, the quantized UNet would be 4 times smaller (3279MB -> 827MB).
|
| 73 |
+
|
| 74 |
+
## Inference
|
| 75 |
+
|
| 76 |
+
Once you have trained a INT8 model with the above command, the inference can be done simply using the `text2images.py` script. Make sure to include the `placeholder_token` in your prompt.
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
export INT8_MODEL_NAME="./int8_model"
|
| 80 |
+
|
| 81 |
+
python text2images.py \
|
| 82 |
+
--pretrained_model_name_or_path=$INT8_MODEL_NAME \
|
| 83 |
+
--caption "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brightly buildings." \
|
| 84 |
+
--images_num 4
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
Here is the comparison of images generated by the FP32 model (left) and INT8 model (right) respectively:
|
| 88 |
+
|
| 89 |
+
<p float="left">
|
| 90 |
+
<img src="https://huggingface.co/datasets/Intel/textual_inversion_dicoo_dfq/resolve/main/FP32.png" width = "300" height = "300" alt="FP32" align=center />
|
| 91 |
+
<img src="https://huggingface.co/datasets/Intel/textual_inversion_dicoo_dfq/resolve/main/INT8.png" width = "300" height = "300" alt="INT8" align=center />
|
| 92 |
+
</p>
|
| 93 |
+
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.25.0
|
| 4 |
+
ftfy
|
| 5 |
+
tensorboard
|
| 6 |
+
modelcards
|
| 7 |
+
neural-compressor
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/text2images.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from neural_compressor.utils.pytorch import load
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 9 |
+
|
| 10 |
+
from diffusers import AutoencoderKL, StableDiffusionPipeline, UNet2DConditionModel
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args():
|
| 14 |
+
parser = argparse.ArgumentParser()
|
| 15 |
+
parser.add_argument(
|
| 16 |
+
"-m",
|
| 17 |
+
"--pretrained_model_name_or_path",
|
| 18 |
+
type=str,
|
| 19 |
+
default=None,
|
| 20 |
+
required=True,
|
| 21 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"-c",
|
| 25 |
+
"--caption",
|
| 26 |
+
type=str,
|
| 27 |
+
default="robotic cat with wings",
|
| 28 |
+
help="Text used to generate images.",
|
| 29 |
+
)
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"-n",
|
| 32 |
+
"--images_num",
|
| 33 |
+
type=int,
|
| 34 |
+
default=4,
|
| 35 |
+
help="How much images to generate.",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"-s",
|
| 39 |
+
"--seed",
|
| 40 |
+
type=int,
|
| 41 |
+
default=42,
|
| 42 |
+
help="Seed for random process.",
|
| 43 |
+
)
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"-ci",
|
| 46 |
+
"--cuda_id",
|
| 47 |
+
type=int,
|
| 48 |
+
default=0,
|
| 49 |
+
help="cuda_id.",
|
| 50 |
+
)
|
| 51 |
+
args = parser.parse_args()
|
| 52 |
+
return args
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def image_grid(imgs, rows, cols):
|
| 56 |
+
if not len(imgs) == rows * cols:
|
| 57 |
+
raise ValueError("The specified number of rows and columns are not correct.")
|
| 58 |
+
|
| 59 |
+
w, h = imgs[0].size
|
| 60 |
+
grid = Image.new("RGB", size=(cols * w, rows * h))
|
| 61 |
+
grid_w, grid_h = grid.size
|
| 62 |
+
|
| 63 |
+
for i, img in enumerate(imgs):
|
| 64 |
+
grid.paste(img, box=(i % cols * w, i // cols * h))
|
| 65 |
+
return grid
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def generate_images(
|
| 69 |
+
pipeline,
|
| 70 |
+
prompt="robotic cat with wings",
|
| 71 |
+
guidance_scale=7.5,
|
| 72 |
+
num_inference_steps=50,
|
| 73 |
+
num_images_per_prompt=1,
|
| 74 |
+
seed=42,
|
| 75 |
+
):
|
| 76 |
+
generator = torch.Generator(pipeline.device).manual_seed(seed)
|
| 77 |
+
images = pipeline(
|
| 78 |
+
prompt,
|
| 79 |
+
guidance_scale=guidance_scale,
|
| 80 |
+
num_inference_steps=num_inference_steps,
|
| 81 |
+
generator=generator,
|
| 82 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 83 |
+
).images
|
| 84 |
+
_rows = int(math.sqrt(num_images_per_prompt))
|
| 85 |
+
grid = image_grid(images, rows=_rows, cols=num_images_per_prompt // _rows)
|
| 86 |
+
return grid, images
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
args = parse_args()
|
| 90 |
+
# Load models and create wrapper for stable diffusion
|
| 91 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 92 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 93 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 94 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 95 |
+
|
| 96 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 97 |
+
args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
|
| 98 |
+
)
|
| 99 |
+
pipeline.safety_checker = lambda images, clip_input: (images, False)
|
| 100 |
+
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, "best_model.pt")):
|
| 101 |
+
unet = load(args.pretrained_model_name_or_path, model=unet)
|
| 102 |
+
unet.eval()
|
| 103 |
+
setattr(pipeline, "unet", unet)
|
| 104 |
+
else:
|
| 105 |
+
unet = unet.to(torch.device("cuda", args.cuda_id))
|
| 106 |
+
pipeline = pipeline.to(unet.device)
|
| 107 |
+
grid, images = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
|
| 108 |
+
grid.save(os.path.join(args.pretrained_model_name_or_path, "{}.png".format("_".join(args.caption.split()))))
|
| 109 |
+
dirname = os.path.join(args.pretrained_model_name_or_path, "_".join(args.caption.split()))
|
| 110 |
+
os.makedirs(dirname, exist_ok=True)
|
| 111 |
+
for idx, image in enumerate(images):
|
| 112 |
+
image.save(os.path.join(dirname, "{}.png".format(idx + 1)))
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/intel_opts/textual_inversion_dfq/textual_inversion.py
ADDED
|
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Iterable
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import PIL
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import torch.utils.checkpoint
|
| 14 |
+
from accelerate import Accelerator
|
| 15 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 16 |
+
from huggingface_hub import create_repo, upload_folder
|
| 17 |
+
from neural_compressor.utils import logger
|
| 18 |
+
from packaging import version
|
| 19 |
+
from PIL import Image
|
| 20 |
+
from torch.utils.data import Dataset
|
| 21 |
+
from torchvision import transforms
|
| 22 |
+
from tqdm.auto import tqdm
|
| 23 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 24 |
+
|
| 25 |
+
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
|
| 26 |
+
from diffusers.optimization import get_scheduler
|
| 27 |
+
from diffusers.utils import make_image_grid
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
|
| 31 |
+
PIL_INTERPOLATION = {
|
| 32 |
+
"linear": PIL.Image.Resampling.BILINEAR,
|
| 33 |
+
"bilinear": PIL.Image.Resampling.BILINEAR,
|
| 34 |
+
"bicubic": PIL.Image.Resampling.BICUBIC,
|
| 35 |
+
"lanczos": PIL.Image.Resampling.LANCZOS,
|
| 36 |
+
"nearest": PIL.Image.Resampling.NEAREST,
|
| 37 |
+
}
|
| 38 |
+
else:
|
| 39 |
+
PIL_INTERPOLATION = {
|
| 40 |
+
"linear": PIL.Image.LINEAR,
|
| 41 |
+
"bilinear": PIL.Image.BILINEAR,
|
| 42 |
+
"bicubic": PIL.Image.BICUBIC,
|
| 43 |
+
"lanczos": PIL.Image.LANCZOS,
|
| 44 |
+
"nearest": PIL.Image.NEAREST,
|
| 45 |
+
}
|
| 46 |
+
# ------------------------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path):
|
| 50 |
+
logger.info("Saving embeddings")
|
| 51 |
+
learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]
|
| 52 |
+
learned_embeds_dict = {args.placeholder_token: learned_embeds.detach().cpu()}
|
| 53 |
+
torch.save(learned_embeds_dict, save_path)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def parse_args():
|
| 57 |
+
parser = argparse.ArgumentParser(description="Example of distillation for quantization on Textual Inversion.")
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--save_steps",
|
| 60 |
+
type=int,
|
| 61 |
+
default=500,
|
| 62 |
+
help="Save learned_embeds.bin every X updates steps.",
|
| 63 |
+
)
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--pretrained_model_name_or_path",
|
| 66 |
+
type=str,
|
| 67 |
+
default=None,
|
| 68 |
+
required=True,
|
| 69 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 70 |
+
)
|
| 71 |
+
parser.add_argument(
|
| 72 |
+
"--revision",
|
| 73 |
+
type=str,
|
| 74 |
+
default=None,
|
| 75 |
+
required=False,
|
| 76 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 77 |
+
)
|
| 78 |
+
parser.add_argument(
|
| 79 |
+
"--tokenizer_name",
|
| 80 |
+
type=str,
|
| 81 |
+
default=None,
|
| 82 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 83 |
+
)
|
| 84 |
+
parser.add_argument(
|
| 85 |
+
"--train_data_dir", type=str, default=None, required=True, help="A folder containing the training data."
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--placeholder_token",
|
| 89 |
+
type=str,
|
| 90 |
+
default=None,
|
| 91 |
+
required=True,
|
| 92 |
+
help="A token to use as a placeholder for the concept.",
|
| 93 |
+
)
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--initializer_token", type=str, default=None, required=True, help="A token to use as initializer word."
|
| 96 |
+
)
|
| 97 |
+
parser.add_argument("--learnable_property", type=str, default="object", help="Choose between 'object' and 'style'")
|
| 98 |
+
parser.add_argument("--repeats", type=int, default=100, help="How many times to repeat the training data.")
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--output_dir",
|
| 101 |
+
type=str,
|
| 102 |
+
default="text-inversion-model",
|
| 103 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--cache_dir",
|
| 107 |
+
type=str,
|
| 108 |
+
default=None,
|
| 109 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument("--seed", type=int, default=42, help="A seed for reproducible training.")
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--resolution",
|
| 114 |
+
type=int,
|
| 115 |
+
default=512,
|
| 116 |
+
help=(
|
| 117 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 118 |
+
" resolution"
|
| 119 |
+
),
|
| 120 |
+
)
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
|
| 123 |
+
)
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 126 |
+
)
|
| 127 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--max_train_steps",
|
| 130 |
+
type=int,
|
| 131 |
+
default=5000,
|
| 132 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--gradient_accumulation_steps",
|
| 136 |
+
type=int,
|
| 137 |
+
default=1,
|
| 138 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 139 |
+
)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--learning_rate",
|
| 142 |
+
type=float,
|
| 143 |
+
default=1e-4,
|
| 144 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--scale_lr",
|
| 148 |
+
action="store_true",
|
| 149 |
+
default=False,
|
| 150 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--lr_scheduler",
|
| 154 |
+
type=str,
|
| 155 |
+
default="constant",
|
| 156 |
+
help=(
|
| 157 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 158 |
+
' "constant", "constant_with_warmup"]'
|
| 159 |
+
),
|
| 160 |
+
)
|
| 161 |
+
parser.add_argument(
|
| 162 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 165 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 166 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 167 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 168 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 169 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--hub_model_id",
|
| 172 |
+
type=str,
|
| 173 |
+
default=None,
|
| 174 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument(
|
| 177 |
+
"--logging_dir",
|
| 178 |
+
type=str,
|
| 179 |
+
default="logs",
|
| 180 |
+
help=(
|
| 181 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 182 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 183 |
+
),
|
| 184 |
+
)
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--mixed_precision",
|
| 187 |
+
type=str,
|
| 188 |
+
default="no",
|
| 189 |
+
choices=["no", "fp16", "bf16"],
|
| 190 |
+
help=(
|
| 191 |
+
"Whether to use mixed precision. Choose"
|
| 192 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 193 |
+
"and an Nvidia Ampere GPU."
|
| 194 |
+
),
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
|
| 197 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 198 |
+
parser.add_argument("--do_quantization", action="store_true", help="Whether or not to do quantization.")
|
| 199 |
+
parser.add_argument("--do_distillation", action="store_true", help="Whether or not to do distillation.")
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--verify_loading", action="store_true", help="Whether or not to verify the loading of the quantized model."
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 204 |
+
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 207 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 208 |
+
args.local_rank = env_local_rank
|
| 209 |
+
|
| 210 |
+
if args.train_data_dir is None:
|
| 211 |
+
raise ValueError("You must specify a train data directory.")
|
| 212 |
+
|
| 213 |
+
return args
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
imagenet_templates_small = [
|
| 217 |
+
"a photo of a {}",
|
| 218 |
+
"a rendering of a {}",
|
| 219 |
+
"a cropped photo of the {}",
|
| 220 |
+
"the photo of a {}",
|
| 221 |
+
"a photo of a clean {}",
|
| 222 |
+
"a photo of a dirty {}",
|
| 223 |
+
"a dark photo of the {}",
|
| 224 |
+
"a photo of my {}",
|
| 225 |
+
"a photo of the cool {}",
|
| 226 |
+
"a close-up photo of a {}",
|
| 227 |
+
"a bright photo of the {}",
|
| 228 |
+
"a cropped photo of a {}",
|
| 229 |
+
"a photo of the {}",
|
| 230 |
+
"a good photo of the {}",
|
| 231 |
+
"a photo of one {}",
|
| 232 |
+
"a close-up photo of the {}",
|
| 233 |
+
"a rendition of the {}",
|
| 234 |
+
"a photo of the clean {}",
|
| 235 |
+
"a rendition of a {}",
|
| 236 |
+
"a photo of a nice {}",
|
| 237 |
+
"a good photo of a {}",
|
| 238 |
+
"a photo of the nice {}",
|
| 239 |
+
"a photo of the small {}",
|
| 240 |
+
"a photo of the weird {}",
|
| 241 |
+
"a photo of the large {}",
|
| 242 |
+
"a photo of a cool {}",
|
| 243 |
+
"a photo of a small {}",
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
imagenet_style_templates_small = [
|
| 247 |
+
"a painting in the style of {}",
|
| 248 |
+
"a rendering in the style of {}",
|
| 249 |
+
"a cropped painting in the style of {}",
|
| 250 |
+
"the painting in the style of {}",
|
| 251 |
+
"a clean painting in the style of {}",
|
| 252 |
+
"a dirty painting in the style of {}",
|
| 253 |
+
"a dark painting in the style of {}",
|
| 254 |
+
"a picture in the style of {}",
|
| 255 |
+
"a cool painting in the style of {}",
|
| 256 |
+
"a close-up painting in the style of {}",
|
| 257 |
+
"a bright painting in the style of {}",
|
| 258 |
+
"a cropped painting in the style of {}",
|
| 259 |
+
"a good painting in the style of {}",
|
| 260 |
+
"a close-up painting in the style of {}",
|
| 261 |
+
"a rendition in the style of {}",
|
| 262 |
+
"a nice painting in the style of {}",
|
| 263 |
+
"a small painting in the style of {}",
|
| 264 |
+
"a weird painting in the style of {}",
|
| 265 |
+
"a large painting in the style of {}",
|
| 266 |
+
]
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# Adapted from torch-ema https://github.com/fadel/pytorch_ema/blob/master/torch_ema/ema.py#L14
|
| 270 |
+
class EMAModel:
|
| 271 |
+
"""
|
| 272 |
+
Exponential Moving Average of models weights
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
def __init__(self, parameters: Iterable[torch.nn.Parameter], decay=0.9999):
|
| 276 |
+
parameters = list(parameters)
|
| 277 |
+
self.shadow_params = [p.clone().detach() for p in parameters]
|
| 278 |
+
|
| 279 |
+
self.decay = decay
|
| 280 |
+
self.optimization_step = 0
|
| 281 |
+
|
| 282 |
+
def get_decay(self, optimization_step):
|
| 283 |
+
"""
|
| 284 |
+
Compute the decay factor for the exponential moving average.
|
| 285 |
+
"""
|
| 286 |
+
value = (1 + optimization_step) / (10 + optimization_step)
|
| 287 |
+
return 1 - min(self.decay, value)
|
| 288 |
+
|
| 289 |
+
@torch.no_grad()
|
| 290 |
+
def step(self, parameters):
|
| 291 |
+
parameters = list(parameters)
|
| 292 |
+
|
| 293 |
+
self.optimization_step += 1
|
| 294 |
+
self.decay = self.get_decay(self.optimization_step)
|
| 295 |
+
|
| 296 |
+
for s_param, param in zip(self.shadow_params, parameters):
|
| 297 |
+
if param.requires_grad:
|
| 298 |
+
tmp = self.decay * (s_param - param)
|
| 299 |
+
s_param.sub_(tmp)
|
| 300 |
+
else:
|
| 301 |
+
s_param.copy_(param)
|
| 302 |
+
|
| 303 |
+
torch.cuda.empty_cache()
|
| 304 |
+
|
| 305 |
+
def copy_to(self, parameters: Iterable[torch.nn.Parameter]) -> None:
|
| 306 |
+
"""
|
| 307 |
+
Copy current averaged parameters into given collection of parameters.
|
| 308 |
+
Args:
|
| 309 |
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
| 310 |
+
updated with the stored moving averages. If `None`, the
|
| 311 |
+
parameters with which this `ExponentialMovingAverage` was
|
| 312 |
+
initialized will be used.
|
| 313 |
+
"""
|
| 314 |
+
parameters = list(parameters)
|
| 315 |
+
for s_param, param in zip(self.shadow_params, parameters):
|
| 316 |
+
param.data.copy_(s_param.data)
|
| 317 |
+
|
| 318 |
+
def to(self, device=None, dtype=None) -> None:
|
| 319 |
+
r"""Move internal buffers of the ExponentialMovingAverage to `device`.
|
| 320 |
+
Args:
|
| 321 |
+
device: like `device` argument to `torch.Tensor.to`
|
| 322 |
+
"""
|
| 323 |
+
# .to() on the tensors handles None correctly
|
| 324 |
+
self.shadow_params = [
|
| 325 |
+
p.to(device=device, dtype=dtype) if p.is_floating_point() else p.to(device=device)
|
| 326 |
+
for p in self.shadow_params
|
| 327 |
+
]
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class TextualInversionDataset(Dataset):
|
| 331 |
+
def __init__(
|
| 332 |
+
self,
|
| 333 |
+
data_root,
|
| 334 |
+
tokenizer,
|
| 335 |
+
learnable_property="object", # [object, style]
|
| 336 |
+
size=512,
|
| 337 |
+
repeats=100,
|
| 338 |
+
interpolation="bicubic",
|
| 339 |
+
flip_p=0.5,
|
| 340 |
+
set="train",
|
| 341 |
+
placeholder_token="*",
|
| 342 |
+
center_crop=False,
|
| 343 |
+
):
|
| 344 |
+
self.data_root = data_root
|
| 345 |
+
self.tokenizer = tokenizer
|
| 346 |
+
self.learnable_property = learnable_property
|
| 347 |
+
self.size = size
|
| 348 |
+
self.placeholder_token = placeholder_token
|
| 349 |
+
self.center_crop = center_crop
|
| 350 |
+
self.flip_p = flip_p
|
| 351 |
+
|
| 352 |
+
self.image_paths = [os.path.join(self.data_root, file_path) for file_path in os.listdir(self.data_root)]
|
| 353 |
+
|
| 354 |
+
self.num_images = len(self.image_paths)
|
| 355 |
+
self._length = self.num_images
|
| 356 |
+
|
| 357 |
+
if set == "train":
|
| 358 |
+
self._length = self.num_images * repeats
|
| 359 |
+
|
| 360 |
+
self.interpolation = {
|
| 361 |
+
"linear": PIL_INTERPOLATION["linear"],
|
| 362 |
+
"bilinear": PIL_INTERPOLATION["bilinear"],
|
| 363 |
+
"bicubic": PIL_INTERPOLATION["bicubic"],
|
| 364 |
+
"lanczos": PIL_INTERPOLATION["lanczos"],
|
| 365 |
+
}[interpolation]
|
| 366 |
+
|
| 367 |
+
self.templates = imagenet_style_templates_small if learnable_property == "style" else imagenet_templates_small
|
| 368 |
+
self.flip_transform = transforms.RandomHorizontalFlip(p=self.flip_p)
|
| 369 |
+
|
| 370 |
+
def __len__(self):
|
| 371 |
+
return self._length
|
| 372 |
+
|
| 373 |
+
def __getitem__(self, i):
|
| 374 |
+
example = {}
|
| 375 |
+
image = Image.open(self.image_paths[i % self.num_images])
|
| 376 |
+
|
| 377 |
+
if not image.mode == "RGB":
|
| 378 |
+
image = image.convert("RGB")
|
| 379 |
+
|
| 380 |
+
placeholder_string = self.placeholder_token
|
| 381 |
+
text = random.choice(self.templates).format(placeholder_string)
|
| 382 |
+
|
| 383 |
+
example["input_ids"] = self.tokenizer(
|
| 384 |
+
text,
|
| 385 |
+
padding="max_length",
|
| 386 |
+
truncation=True,
|
| 387 |
+
max_length=self.tokenizer.model_max_length,
|
| 388 |
+
return_tensors="pt",
|
| 389 |
+
).input_ids[0]
|
| 390 |
+
|
| 391 |
+
# default to score-sde preprocessing
|
| 392 |
+
img = np.array(image).astype(np.uint8)
|
| 393 |
+
|
| 394 |
+
if self.center_crop:
|
| 395 |
+
crop = min(img.shape[0], img.shape[1])
|
| 396 |
+
(
|
| 397 |
+
h,
|
| 398 |
+
w,
|
| 399 |
+
) = (
|
| 400 |
+
img.shape[0],
|
| 401 |
+
img.shape[1],
|
| 402 |
+
)
|
| 403 |
+
img = img[(h - crop) // 2 : (h + crop) // 2, (w - crop) // 2 : (w + crop) // 2]
|
| 404 |
+
|
| 405 |
+
image = Image.fromarray(img)
|
| 406 |
+
image = image.resize((self.size, self.size), resample=self.interpolation)
|
| 407 |
+
|
| 408 |
+
image = self.flip_transform(image)
|
| 409 |
+
image = np.array(image).astype(np.uint8)
|
| 410 |
+
image = (image / 127.5 - 1.0).astype(np.float32)
|
| 411 |
+
|
| 412 |
+
example["pixel_values"] = torch.from_numpy(image).permute(2, 0, 1)
|
| 413 |
+
return example
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def freeze_params(params):
|
| 417 |
+
for param in params:
|
| 418 |
+
param.requires_grad = False
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def generate_images(pipeline, prompt="", guidance_scale=7.5, num_inference_steps=50, num_images_per_prompt=1, seed=42):
|
| 422 |
+
generator = torch.Generator(pipeline.device).manual_seed(seed)
|
| 423 |
+
images = pipeline(
|
| 424 |
+
prompt,
|
| 425 |
+
guidance_scale=guidance_scale,
|
| 426 |
+
num_inference_steps=num_inference_steps,
|
| 427 |
+
generator=generator,
|
| 428 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 429 |
+
).images
|
| 430 |
+
_rows = int(math.sqrt(num_images_per_prompt))
|
| 431 |
+
grid = make_image_grid(images, rows=_rows, cols=num_images_per_prompt // _rows)
|
| 432 |
+
return grid
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def main():
|
| 436 |
+
args = parse_args()
|
| 437 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 438 |
+
|
| 439 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 440 |
+
|
| 441 |
+
accelerator = Accelerator(
|
| 442 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 443 |
+
mixed_precision=args.mixed_precision,
|
| 444 |
+
log_with="tensorboard",
|
| 445 |
+
project_config=accelerator_project_config,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
# If passed along, set the training seed now.
|
| 449 |
+
if args.seed is not None:
|
| 450 |
+
set_seed(args.seed)
|
| 451 |
+
|
| 452 |
+
# Handle the repository creation
|
| 453 |
+
if accelerator.is_main_process:
|
| 454 |
+
if args.output_dir is not None:
|
| 455 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 456 |
+
|
| 457 |
+
if args.push_to_hub:
|
| 458 |
+
repo_id = create_repo(
|
| 459 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 460 |
+
).repo_id
|
| 461 |
+
|
| 462 |
+
# Load the tokenizer and add the placeholder token as a additional special token
|
| 463 |
+
if args.tokenizer_name:
|
| 464 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 465 |
+
elif args.pretrained_model_name_or_path:
|
| 466 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 467 |
+
|
| 468 |
+
# Load models and create wrapper for stable diffusion
|
| 469 |
+
noise_scheduler = DDPMScheduler.from_config(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 470 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 471 |
+
args.pretrained_model_name_or_path,
|
| 472 |
+
subfolder="text_encoder",
|
| 473 |
+
revision=args.revision,
|
| 474 |
+
)
|
| 475 |
+
vae = AutoencoderKL.from_pretrained(
|
| 476 |
+
args.pretrained_model_name_or_path,
|
| 477 |
+
subfolder="vae",
|
| 478 |
+
revision=args.revision,
|
| 479 |
+
)
|
| 480 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 481 |
+
args.pretrained_model_name_or_path,
|
| 482 |
+
subfolder="unet",
|
| 483 |
+
revision=args.revision,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
train_unet = False
|
| 487 |
+
# Freeze vae and unet
|
| 488 |
+
freeze_params(vae.parameters())
|
| 489 |
+
if not args.do_quantization and not args.do_distillation:
|
| 490 |
+
# Add the placeholder token in tokenizer
|
| 491 |
+
num_added_tokens = tokenizer.add_tokens(args.placeholder_token)
|
| 492 |
+
if num_added_tokens == 0:
|
| 493 |
+
raise ValueError(
|
| 494 |
+
f"The tokenizer already contains the token {args.placeholder_token}. Please pass a different"
|
| 495 |
+
" `placeholder_token` that is not already in the tokenizer."
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# Convert the initializer_token, placeholder_token to ids
|
| 499 |
+
token_ids = tokenizer.encode(args.initializer_token, add_special_tokens=False)
|
| 500 |
+
# Check if initializer_token is a single token or a sequence of tokens
|
| 501 |
+
if len(token_ids) > 1:
|
| 502 |
+
raise ValueError("The initializer token must be a single token.")
|
| 503 |
+
|
| 504 |
+
initializer_token_id = token_ids[0]
|
| 505 |
+
placeholder_token_id = tokenizer.convert_tokens_to_ids(args.placeholder_token)
|
| 506 |
+
# Resize the token embeddings as we are adding new special tokens to the tokenizer
|
| 507 |
+
text_encoder.resize_token_embeddings(len(tokenizer))
|
| 508 |
+
|
| 509 |
+
# Initialise the newly added placeholder token with the embeddings of the initializer token
|
| 510 |
+
token_embeds = text_encoder.get_input_embeddings().weight.data
|
| 511 |
+
token_embeds[placeholder_token_id] = token_embeds[initializer_token_id]
|
| 512 |
+
|
| 513 |
+
freeze_params(unet.parameters())
|
| 514 |
+
# Freeze all parameters except for the token embeddings in text encoder
|
| 515 |
+
params_to_freeze = itertools.chain(
|
| 516 |
+
text_encoder.text_model.encoder.parameters(),
|
| 517 |
+
text_encoder.text_model.final_layer_norm.parameters(),
|
| 518 |
+
text_encoder.text_model.embeddings.position_embedding.parameters(),
|
| 519 |
+
)
|
| 520 |
+
freeze_params(params_to_freeze)
|
| 521 |
+
else:
|
| 522 |
+
train_unet = True
|
| 523 |
+
freeze_params(text_encoder.parameters())
|
| 524 |
+
|
| 525 |
+
if args.scale_lr:
|
| 526 |
+
args.learning_rate = (
|
| 527 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# Initialize the optimizer
|
| 531 |
+
optimizer = torch.optim.AdamW(
|
| 532 |
+
# only optimize the unet or embeddings of text_encoder
|
| 533 |
+
unet.parameters() if train_unet else text_encoder.get_input_embeddings().parameters(),
|
| 534 |
+
lr=args.learning_rate,
|
| 535 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 536 |
+
weight_decay=args.adam_weight_decay,
|
| 537 |
+
eps=args.adam_epsilon,
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
train_dataset = TextualInversionDataset(
|
| 541 |
+
data_root=args.train_data_dir,
|
| 542 |
+
tokenizer=tokenizer,
|
| 543 |
+
size=args.resolution,
|
| 544 |
+
placeholder_token=args.placeholder_token,
|
| 545 |
+
repeats=args.repeats,
|
| 546 |
+
learnable_property=args.learnable_property,
|
| 547 |
+
center_crop=args.center_crop,
|
| 548 |
+
set="train",
|
| 549 |
+
)
|
| 550 |
+
train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True)
|
| 551 |
+
|
| 552 |
+
# Scheduler and math around the number of training steps.
|
| 553 |
+
overrode_max_train_steps = False
|
| 554 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 555 |
+
if args.max_train_steps is None:
|
| 556 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 557 |
+
overrode_max_train_steps = True
|
| 558 |
+
|
| 559 |
+
lr_scheduler = get_scheduler(
|
| 560 |
+
args.lr_scheduler,
|
| 561 |
+
optimizer=optimizer,
|
| 562 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 563 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
if not train_unet:
|
| 567 |
+
text_encoder = accelerator.prepare(text_encoder)
|
| 568 |
+
unet.to(accelerator.device)
|
| 569 |
+
unet.eval()
|
| 570 |
+
else:
|
| 571 |
+
unet = accelerator.prepare(unet)
|
| 572 |
+
text_encoder.to(accelerator.device)
|
| 573 |
+
text_encoder.eval()
|
| 574 |
+
optimizer, train_dataloader, lr_scheduler = accelerator.prepare(optimizer, train_dataloader, lr_scheduler)
|
| 575 |
+
|
| 576 |
+
# Move vae to device
|
| 577 |
+
vae.to(accelerator.device)
|
| 578 |
+
|
| 579 |
+
# Keep vae in eval model as we don't train these
|
| 580 |
+
vae.eval()
|
| 581 |
+
|
| 582 |
+
compression_manager = None
|
| 583 |
+
|
| 584 |
+
def train_func(model):
|
| 585 |
+
if train_unet:
|
| 586 |
+
unet_ = model
|
| 587 |
+
text_encoder_ = text_encoder
|
| 588 |
+
else:
|
| 589 |
+
unet_ = unet
|
| 590 |
+
text_encoder_ = model
|
| 591 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 592 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 593 |
+
if overrode_max_train_steps:
|
| 594 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 595 |
+
# Afterwards we recalculate our number of training epochs
|
| 596 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 597 |
+
|
| 598 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 599 |
+
# The trackers initializes automatically on the main process.
|
| 600 |
+
if accelerator.is_main_process:
|
| 601 |
+
accelerator.init_trackers("textual_inversion", config=vars(args))
|
| 602 |
+
|
| 603 |
+
# Train!
|
| 604 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 605 |
+
|
| 606 |
+
logger.info("***** Running training *****")
|
| 607 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 608 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 609 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 610 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 611 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 612 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 613 |
+
# Only show the progress bar once on each machine.
|
| 614 |
+
progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 615 |
+
progress_bar.set_description("Steps")
|
| 616 |
+
global_step = 0
|
| 617 |
+
|
| 618 |
+
if train_unet and args.use_ema:
|
| 619 |
+
ema_unet = EMAModel(unet_.parameters())
|
| 620 |
+
|
| 621 |
+
for epoch in range(args.num_train_epochs):
|
| 622 |
+
model.train()
|
| 623 |
+
train_loss = 0.0
|
| 624 |
+
for step, batch in enumerate(train_dataloader):
|
| 625 |
+
with accelerator.accumulate(model):
|
| 626 |
+
# Convert images to latent space
|
| 627 |
+
latents = vae.encode(batch["pixel_values"]).latent_dist.sample().detach()
|
| 628 |
+
latents = latents * 0.18215
|
| 629 |
+
|
| 630 |
+
# Sample noise that we'll add to the latents
|
| 631 |
+
noise = torch.randn(latents.shape).to(latents.device)
|
| 632 |
+
bsz = latents.shape[0]
|
| 633 |
+
# Sample a random timestep for each image
|
| 634 |
+
timesteps = torch.randint(
|
| 635 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
|
| 636 |
+
).long()
|
| 637 |
+
|
| 638 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 639 |
+
# (this is the forward diffusion process)
|
| 640 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 641 |
+
|
| 642 |
+
# Get the text embedding for conditioning
|
| 643 |
+
encoder_hidden_states = text_encoder_(batch["input_ids"])[0]
|
| 644 |
+
|
| 645 |
+
# Predict the noise residual
|
| 646 |
+
model_pred = unet_(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 647 |
+
|
| 648 |
+
loss = F.mse_loss(model_pred, noise, reduction="none").mean([1, 2, 3]).mean()
|
| 649 |
+
if train_unet and compression_manager:
|
| 650 |
+
unet_inputs = {
|
| 651 |
+
"sample": noisy_latents,
|
| 652 |
+
"timestep": timesteps,
|
| 653 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 654 |
+
}
|
| 655 |
+
loss = compression_manager.callbacks.on_after_compute_loss(unet_inputs, model_pred, loss)
|
| 656 |
+
|
| 657 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 658 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
|
| 659 |
+
train_loss += avg_loss.item() / args.gradient_accumulation_steps
|
| 660 |
+
|
| 661 |
+
# Backpropagate
|
| 662 |
+
accelerator.backward(loss)
|
| 663 |
+
|
| 664 |
+
if train_unet:
|
| 665 |
+
if accelerator.sync_gradients:
|
| 666 |
+
accelerator.clip_grad_norm_(unet_.parameters(), args.max_grad_norm)
|
| 667 |
+
else:
|
| 668 |
+
# Zero out the gradients for all token embeddings except the newly added
|
| 669 |
+
# embeddings for the concept, as we only want to optimize the concept embeddings
|
| 670 |
+
if accelerator.num_processes > 1:
|
| 671 |
+
grads = text_encoder_.module.get_input_embeddings().weight.grad
|
| 672 |
+
else:
|
| 673 |
+
grads = text_encoder_.get_input_embeddings().weight.grad
|
| 674 |
+
# Get the index for tokens that we want to zero the grads for
|
| 675 |
+
index_grads_to_zero = torch.arange(len(tokenizer)) != placeholder_token_id
|
| 676 |
+
grads.data[index_grads_to_zero, :] = grads.data[index_grads_to_zero, :].fill_(0)
|
| 677 |
+
|
| 678 |
+
optimizer.step()
|
| 679 |
+
lr_scheduler.step()
|
| 680 |
+
optimizer.zero_grad()
|
| 681 |
+
|
| 682 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 683 |
+
if accelerator.sync_gradients:
|
| 684 |
+
if train_unet and args.use_ema:
|
| 685 |
+
ema_unet.step(unet_.parameters())
|
| 686 |
+
progress_bar.update(1)
|
| 687 |
+
global_step += 1
|
| 688 |
+
accelerator.log({"train_loss": train_loss}, step=global_step)
|
| 689 |
+
train_loss = 0.0
|
| 690 |
+
if not train_unet and global_step % args.save_steps == 0:
|
| 691 |
+
save_path = os.path.join(args.output_dir, f"learned_embeds-steps-{global_step}.bin")
|
| 692 |
+
save_progress(text_encoder_, placeholder_token_id, accelerator, args, save_path)
|
| 693 |
+
|
| 694 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 695 |
+
progress_bar.set_postfix(**logs)
|
| 696 |
+
accelerator.log(logs, step=global_step)
|
| 697 |
+
|
| 698 |
+
if global_step >= args.max_train_steps:
|
| 699 |
+
break
|
| 700 |
+
accelerator.wait_for_everyone()
|
| 701 |
+
|
| 702 |
+
if train_unet and args.use_ema:
|
| 703 |
+
ema_unet.copy_to(unet_.parameters())
|
| 704 |
+
|
| 705 |
+
if not train_unet:
|
| 706 |
+
return text_encoder_
|
| 707 |
+
|
| 708 |
+
if not train_unet:
|
| 709 |
+
text_encoder = train_func(text_encoder)
|
| 710 |
+
else:
|
| 711 |
+
import copy
|
| 712 |
+
|
| 713 |
+
model = copy.deepcopy(unet)
|
| 714 |
+
confs = []
|
| 715 |
+
if args.do_quantization:
|
| 716 |
+
from neural_compressor import QuantizationAwareTrainingConfig
|
| 717 |
+
|
| 718 |
+
q_conf = QuantizationAwareTrainingConfig()
|
| 719 |
+
confs.append(q_conf)
|
| 720 |
+
|
| 721 |
+
if args.do_distillation:
|
| 722 |
+
teacher_model = copy.deepcopy(model)
|
| 723 |
+
|
| 724 |
+
def attention_fetcher(x):
|
| 725 |
+
return x.sample
|
| 726 |
+
|
| 727 |
+
layer_mappings = [
|
| 728 |
+
[
|
| 729 |
+
[
|
| 730 |
+
"conv_in",
|
| 731 |
+
]
|
| 732 |
+
],
|
| 733 |
+
[
|
| 734 |
+
[
|
| 735 |
+
"time_embedding",
|
| 736 |
+
]
|
| 737 |
+
],
|
| 738 |
+
[["down_blocks.0.attentions.0", attention_fetcher]],
|
| 739 |
+
[["down_blocks.0.attentions.1", attention_fetcher]],
|
| 740 |
+
[
|
| 741 |
+
[
|
| 742 |
+
"down_blocks.0.resnets.0",
|
| 743 |
+
]
|
| 744 |
+
],
|
| 745 |
+
[
|
| 746 |
+
[
|
| 747 |
+
"down_blocks.0.resnets.1",
|
| 748 |
+
]
|
| 749 |
+
],
|
| 750 |
+
[
|
| 751 |
+
[
|
| 752 |
+
"down_blocks.0.downsamplers.0",
|
| 753 |
+
]
|
| 754 |
+
],
|
| 755 |
+
[["down_blocks.1.attentions.0", attention_fetcher]],
|
| 756 |
+
[["down_blocks.1.attentions.1", attention_fetcher]],
|
| 757 |
+
[
|
| 758 |
+
[
|
| 759 |
+
"down_blocks.1.resnets.0",
|
| 760 |
+
]
|
| 761 |
+
],
|
| 762 |
+
[
|
| 763 |
+
[
|
| 764 |
+
"down_blocks.1.resnets.1",
|
| 765 |
+
]
|
| 766 |
+
],
|
| 767 |
+
[
|
| 768 |
+
[
|
| 769 |
+
"down_blocks.1.downsamplers.0",
|
| 770 |
+
]
|
| 771 |
+
],
|
| 772 |
+
[["down_blocks.2.attentions.0", attention_fetcher]],
|
| 773 |
+
[["down_blocks.2.attentions.1", attention_fetcher]],
|
| 774 |
+
[
|
| 775 |
+
[
|
| 776 |
+
"down_blocks.2.resnets.0",
|
| 777 |
+
]
|
| 778 |
+
],
|
| 779 |
+
[
|
| 780 |
+
[
|
| 781 |
+
"down_blocks.2.resnets.1",
|
| 782 |
+
]
|
| 783 |
+
],
|
| 784 |
+
[
|
| 785 |
+
[
|
| 786 |
+
"down_blocks.2.downsamplers.0",
|
| 787 |
+
]
|
| 788 |
+
],
|
| 789 |
+
[
|
| 790 |
+
[
|
| 791 |
+
"down_blocks.3.resnets.0",
|
| 792 |
+
]
|
| 793 |
+
],
|
| 794 |
+
[
|
| 795 |
+
[
|
| 796 |
+
"down_blocks.3.resnets.1",
|
| 797 |
+
]
|
| 798 |
+
],
|
| 799 |
+
[
|
| 800 |
+
[
|
| 801 |
+
"up_blocks.0.resnets.0",
|
| 802 |
+
]
|
| 803 |
+
],
|
| 804 |
+
[
|
| 805 |
+
[
|
| 806 |
+
"up_blocks.0.resnets.1",
|
| 807 |
+
]
|
| 808 |
+
],
|
| 809 |
+
[
|
| 810 |
+
[
|
| 811 |
+
"up_blocks.0.resnets.2",
|
| 812 |
+
]
|
| 813 |
+
],
|
| 814 |
+
[
|
| 815 |
+
[
|
| 816 |
+
"up_blocks.0.upsamplers.0",
|
| 817 |
+
]
|
| 818 |
+
],
|
| 819 |
+
[["up_blocks.1.attentions.0", attention_fetcher]],
|
| 820 |
+
[["up_blocks.1.attentions.1", attention_fetcher]],
|
| 821 |
+
[["up_blocks.1.attentions.2", attention_fetcher]],
|
| 822 |
+
[
|
| 823 |
+
[
|
| 824 |
+
"up_blocks.1.resnets.0",
|
| 825 |
+
]
|
| 826 |
+
],
|
| 827 |
+
[
|
| 828 |
+
[
|
| 829 |
+
"up_blocks.1.resnets.1",
|
| 830 |
+
]
|
| 831 |
+
],
|
| 832 |
+
[
|
| 833 |
+
[
|
| 834 |
+
"up_blocks.1.resnets.2",
|
| 835 |
+
]
|
| 836 |
+
],
|
| 837 |
+
[
|
| 838 |
+
[
|
| 839 |
+
"up_blocks.1.upsamplers.0",
|
| 840 |
+
]
|
| 841 |
+
],
|
| 842 |
+
[["up_blocks.2.attentions.0", attention_fetcher]],
|
| 843 |
+
[["up_blocks.2.attentions.1", attention_fetcher]],
|
| 844 |
+
[["up_blocks.2.attentions.2", attention_fetcher]],
|
| 845 |
+
[
|
| 846 |
+
[
|
| 847 |
+
"up_blocks.2.resnets.0",
|
| 848 |
+
]
|
| 849 |
+
],
|
| 850 |
+
[
|
| 851 |
+
[
|
| 852 |
+
"up_blocks.2.resnets.1",
|
| 853 |
+
]
|
| 854 |
+
],
|
| 855 |
+
[
|
| 856 |
+
[
|
| 857 |
+
"up_blocks.2.resnets.2",
|
| 858 |
+
]
|
| 859 |
+
],
|
| 860 |
+
[
|
| 861 |
+
[
|
| 862 |
+
"up_blocks.2.upsamplers.0",
|
| 863 |
+
]
|
| 864 |
+
],
|
| 865 |
+
[["up_blocks.3.attentions.0", attention_fetcher]],
|
| 866 |
+
[["up_blocks.3.attentions.1", attention_fetcher]],
|
| 867 |
+
[["up_blocks.3.attentions.2", attention_fetcher]],
|
| 868 |
+
[
|
| 869 |
+
[
|
| 870 |
+
"up_blocks.3.resnets.0",
|
| 871 |
+
]
|
| 872 |
+
],
|
| 873 |
+
[
|
| 874 |
+
[
|
| 875 |
+
"up_blocks.3.resnets.1",
|
| 876 |
+
]
|
| 877 |
+
],
|
| 878 |
+
[
|
| 879 |
+
[
|
| 880 |
+
"up_blocks.3.resnets.2",
|
| 881 |
+
]
|
| 882 |
+
],
|
| 883 |
+
[["mid_block.attentions.0", attention_fetcher]],
|
| 884 |
+
[
|
| 885 |
+
[
|
| 886 |
+
"mid_block.resnets.0",
|
| 887 |
+
]
|
| 888 |
+
],
|
| 889 |
+
[
|
| 890 |
+
[
|
| 891 |
+
"mid_block.resnets.1",
|
| 892 |
+
]
|
| 893 |
+
],
|
| 894 |
+
[
|
| 895 |
+
[
|
| 896 |
+
"conv_out",
|
| 897 |
+
]
|
| 898 |
+
],
|
| 899 |
+
]
|
| 900 |
+
layer_names = [layer_mapping[0][0] for layer_mapping in layer_mappings]
|
| 901 |
+
if not set(layer_names).issubset([n[0] for n in model.named_modules()]):
|
| 902 |
+
raise ValueError(
|
| 903 |
+
"Provided model is not compatible with the default layer_mappings, "
|
| 904 |
+
'please use the model fine-tuned from "CompVis/stable-diffusion-v1-4", '
|
| 905 |
+
"or modify the layer_mappings variable to fit your model."
|
| 906 |
+
f"\nDefault layer_mappings are as such:\n{layer_mappings}"
|
| 907 |
+
)
|
| 908 |
+
from neural_compressor.config import DistillationConfig, IntermediateLayersKnowledgeDistillationLossConfig
|
| 909 |
+
|
| 910 |
+
distillation_criterion = IntermediateLayersKnowledgeDistillationLossConfig(
|
| 911 |
+
layer_mappings=layer_mappings,
|
| 912 |
+
loss_types=["MSE"] * len(layer_mappings),
|
| 913 |
+
loss_weights=[1.0 / len(layer_mappings)] * len(layer_mappings),
|
| 914 |
+
add_origin_loss=True,
|
| 915 |
+
)
|
| 916 |
+
d_conf = DistillationConfig(teacher_model=teacher_model, criterion=distillation_criterion)
|
| 917 |
+
confs.append(d_conf)
|
| 918 |
+
|
| 919 |
+
from neural_compressor.training import prepare_compression
|
| 920 |
+
|
| 921 |
+
compression_manager = prepare_compression(model, confs)
|
| 922 |
+
compression_manager.callbacks.on_train_begin()
|
| 923 |
+
model = compression_manager.model
|
| 924 |
+
train_func(model)
|
| 925 |
+
compression_manager.callbacks.on_train_end()
|
| 926 |
+
|
| 927 |
+
# Save the resulting model and its corresponding configuration in the given directory
|
| 928 |
+
model.save(args.output_dir)
|
| 929 |
+
|
| 930 |
+
logger.info(f"Optimized model saved to: {args.output_dir}.")
|
| 931 |
+
|
| 932 |
+
# change to framework model for further use
|
| 933 |
+
model = model.model
|
| 934 |
+
|
| 935 |
+
# Create the pipeline using using the trained modules and save it.
|
| 936 |
+
templates = imagenet_style_templates_small if args.learnable_property == "style" else imagenet_templates_small
|
| 937 |
+
prompt = templates[0].format(args.placeholder_token)
|
| 938 |
+
if accelerator.is_main_process:
|
| 939 |
+
pipeline = StableDiffusionPipeline.from_pretrained(
|
| 940 |
+
args.pretrained_model_name_or_path,
|
| 941 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 942 |
+
vae=vae,
|
| 943 |
+
unet=accelerator.unwrap_model(unet),
|
| 944 |
+
tokenizer=tokenizer,
|
| 945 |
+
)
|
| 946 |
+
pipeline.save_pretrained(args.output_dir)
|
| 947 |
+
pipeline = pipeline.to(unet.device)
|
| 948 |
+
baseline_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
|
| 949 |
+
baseline_model_images.save(
|
| 950 |
+
os.path.join(args.output_dir, "{}_baseline_model.png".format("_".join(prompt.split())))
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
if not train_unet:
|
| 954 |
+
# Also save the newly trained embeddings
|
| 955 |
+
save_path = os.path.join(args.output_dir, "learned_embeds.bin")
|
| 956 |
+
save_progress(text_encoder, placeholder_token_id, accelerator, args, save_path)
|
| 957 |
+
else:
|
| 958 |
+
setattr(pipeline, "unet", accelerator.unwrap_model(model))
|
| 959 |
+
if args.do_quantization:
|
| 960 |
+
pipeline = pipeline.to(torch.device("cpu"))
|
| 961 |
+
|
| 962 |
+
optimized_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
|
| 963 |
+
optimized_model_images.save(
|
| 964 |
+
os.path.join(args.output_dir, "{}_optimized_model.png".format("_".join(prompt.split())))
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
if args.push_to_hub:
|
| 968 |
+
upload_folder(
|
| 969 |
+
repo_id=repo_id,
|
| 970 |
+
folder_path=args.output_dir,
|
| 971 |
+
commit_message="End of training",
|
| 972 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
accelerator.end_training()
|
| 976 |
+
|
| 977 |
+
if args.do_quantization and args.verify_loading:
|
| 978 |
+
# Load the model obtained after Intel Neural Compressor quantization
|
| 979 |
+
from neural_compressor.utils.pytorch import load
|
| 980 |
+
|
| 981 |
+
loaded_model = load(args.output_dir, model=unet)
|
| 982 |
+
loaded_model.eval()
|
| 983 |
+
|
| 984 |
+
setattr(pipeline, "unet", loaded_model)
|
| 985 |
+
if args.do_quantization:
|
| 986 |
+
pipeline = pipeline.to(torch.device("cpu"))
|
| 987 |
+
|
| 988 |
+
loaded_model_images = generate_images(pipeline, prompt=prompt, seed=args.seed)
|
| 989 |
+
if loaded_model_images != optimized_model_images:
|
| 990 |
+
logger.info("The quantized model was not successfully loaded.")
|
| 991 |
+
else:
|
| 992 |
+
logger.info("The quantized model was successfully loaded.")
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
if __name__ == "__main__":
|
| 996 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/README.md
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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hance text-to-image models such as Stable Diffusion by enabling them to generate images based on image prompts rather than text prompts alone. Unlike traditional methods that rely solely on complex text prompts, IP Adapter introduces the concept of using image prompts, leveraging the idea that "an image is worth a thousand words." By decoupling cross-attention layers for text and image features, IP Adapter effectively integrates image prompts into the generation process without the need for extensive fine-tuning or large computing resources.
|
| 4 |
+
|
| 5 |
+
## Training locally with PyTorch
|
| 6 |
+
|
| 7 |
+
### Installing the dependencies
|
| 8 |
+
|
| 9 |
+
Before running the scripts, make sure to install the library's training dependencies:
|
| 10 |
+
|
| 11 |
+
**Important**
|
| 12 |
+
|
| 13 |
+
To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
git clone https://github.com/huggingface/diffusers
|
| 17 |
+
cd diffusers
|
| 18 |
+
pip install -e .
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Then cd in the example folder and run
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
And initialize an [🤗Accelerate](https://github.com/huggingface/accelerate/) environment with:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
accelerate config
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Or for a default accelerate configuration without answering questions about your environment
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
accelerate config default
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Or if your environment doesn't support an interactive shell e.g. a notebook
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
from accelerate.utils import write_basic_config
|
| 43 |
+
write_basic_config()
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Certainly! Below is the documentation in pure Markdown format:
|
| 47 |
+
|
| 48 |
+
### Accelerate Launch Command Documentation
|
| 49 |
+
|
| 50 |
+
#### Description:
|
| 51 |
+
The Accelerate launch command is used to train a model using multiple GPUs and mixed precision training. It launches the training script `tutorial_train_ip-adapter.py` with specified parameters and configurations.
|
| 52 |
+
|
| 53 |
+
#### Usage Example:
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
accelerate launch --mixed_precision "fp16" \
|
| 57 |
+
tutorial_train_ip-adapter.py \
|
| 58 |
+
--pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5/" \
|
| 59 |
+
--image_encoder_path="{image_encoder_path}" \
|
| 60 |
+
--data_json_file="{data.json}" \
|
| 61 |
+
--data_root_path="{image_path}" \
|
| 62 |
+
--mixed_precision="fp16" \
|
| 63 |
+
--resolution=512 \
|
| 64 |
+
--train_batch_size=8 \
|
| 65 |
+
--dataloader_num_workers=4 \
|
| 66 |
+
--learning_rate=1e-04 \
|
| 67 |
+
--weight_decay=0.01 \
|
| 68 |
+
--output_dir="{output_dir}" \
|
| 69 |
+
--save_steps=10000
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### Multi-GPU Script:
|
| 73 |
+
```
|
| 74 |
+
accelerate launch --num_processes 8 --multi_gpu --mixed_precision "fp16" \
|
| 75 |
+
tutorial_train_ip-adapter.py \
|
| 76 |
+
--pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5/" \
|
| 77 |
+
--image_encoder_path="{image_encoder_path}" \
|
| 78 |
+
--data_json_file="{data.json}" \
|
| 79 |
+
--data_root_path="{image_path}" \
|
| 80 |
+
--mixed_precision="fp16" \
|
| 81 |
+
--resolution=512 \
|
| 82 |
+
--train_batch_size=8 \
|
| 83 |
+
--dataloader_num_workers=4 \
|
| 84 |
+
--learning_rate=1e-04 \
|
| 85 |
+
--weight_decay=0.01 \
|
| 86 |
+
--output_dir="{output_dir}" \
|
| 87 |
+
--save_steps=10000
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
#### Parameters:
|
| 91 |
+
- `--num_processes`: Number of processes to launch for distributed training (in this example, 8 processes).
|
| 92 |
+
- `--multi_gpu`: Flag indicating the usage of multiple GPUs for training.
|
| 93 |
+
- `--mixed_precision "fp16"`: Enables mixed precision training with 16-bit floating-point precision.
|
| 94 |
+
- `tutorial_train_ip-adapter.py`: Name of the training script to be executed.
|
| 95 |
+
- `--pretrained_model_name_or_path`: Path or identifier for a pretrained model.
|
| 96 |
+
- `--image_encoder_path`: Path to the CLIP image encoder.
|
| 97 |
+
- `--data_json_file`: Path to the training data in JSON format.
|
| 98 |
+
- `--data_root_path`: Root path where training images are located.
|
| 99 |
+
- `--resolution`: Resolution of input images (512x512 in this example).
|
| 100 |
+
- `--train_batch_size`: Batch size for training data (8 in this example).
|
| 101 |
+
- `--dataloader_num_workers`: Number of subprocesses for data loading (4 in this example).
|
| 102 |
+
- `--learning_rate`: Learning rate for training (1e-04 in this example).
|
| 103 |
+
- `--weight_decay`: Weight decay for regularization (0.01 in this example).
|
| 104 |
+
- `--output_dir`: Directory to save model checkpoints and predictions.
|
| 105 |
+
- `--save_steps`: Frequency of saving checkpoints during training (10000 in this example).
|
| 106 |
+
|
| 107 |
+
### Inference
|
| 108 |
+
|
| 109 |
+
#### Description:
|
| 110 |
+
The provided inference code is used to load a trained model checkpoint and extract the components related to image projection and IP (Image Processing) adapter. These components are then saved into a binary file for later use in inference.
|
| 111 |
+
|
| 112 |
+
#### Usage Example:
|
| 113 |
+
```python
|
| 114 |
+
from safetensors.torch import load_file, save_file
|
| 115 |
+
|
| 116 |
+
# Load the trained model checkpoint in safetensors format
|
| 117 |
+
ckpt = "checkpoint-50000/pytorch_model.safetensors"
|
| 118 |
+
sd = load_file(ckpt) # Using safetensors load function
|
| 119 |
+
|
| 120 |
+
# Extract image projection and IP adapter components
|
| 121 |
+
image_proj_sd = {}
|
| 122 |
+
ip_sd = {}
|
| 123 |
+
|
| 124 |
+
for k in sd:
|
| 125 |
+
if k.startswith("unet"):
|
| 126 |
+
pass # Skip unet-related keys
|
| 127 |
+
elif k.startswith("image_proj_model"):
|
| 128 |
+
image_proj_sd[k.replace("image_proj_model.", "")] = sd[k]
|
| 129 |
+
elif k.startswith("adapter_modules"):
|
| 130 |
+
ip_sd[k.replace("adapter_modules.", "")] = sd[k]
|
| 131 |
+
|
| 132 |
+
# Save the components into separate safetensors files
|
| 133 |
+
save_file(image_proj_sd, "image_proj.safetensors")
|
| 134 |
+
save_file(ip_sd, "ip_adapter.safetensors")
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### Sample Inference Script using the CLIP Model
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
|
| 141 |
+
import torch
|
| 142 |
+
from safetensors.torch import load_file
|
| 143 |
+
from transformers import CLIPProcessor, CLIPModel # Using the Hugging Face CLIP model
|
| 144 |
+
|
| 145 |
+
# Load model components from safetensors
|
| 146 |
+
image_proj_ckpt = "image_proj.safetensors"
|
| 147 |
+
ip_adapter_ckpt = "ip_adapter.safetensors"
|
| 148 |
+
|
| 149 |
+
# Load the saved weights
|
| 150 |
+
image_proj_sd = load_file(image_proj_ckpt)
|
| 151 |
+
ip_adapter_sd = load_file(ip_adapter_ckpt)
|
| 152 |
+
|
| 153 |
+
# Define the model Parameters
|
| 154 |
+
class ImageProjectionModel(torch.nn.Module):
|
| 155 |
+
def __init__(self, input_dim=768, output_dim=512): # CLIP's default embedding size is 768
|
| 156 |
+
super().__init__()
|
| 157 |
+
self.model = torch.nn.Linear(input_dim, output_dim)
|
| 158 |
+
|
| 159 |
+
def forward(self, x):
|
| 160 |
+
return self.model(x)
|
| 161 |
+
|
| 162 |
+
class IPAdapterModel(torch.nn.Module):
|
| 163 |
+
def __init__(self, input_dim=512, output_dim=10): # Example for 10 classes
|
| 164 |
+
super().__init__()
|
| 165 |
+
self.model = torch.nn.Linear(input_dim, output_dim)
|
| 166 |
+
|
| 167 |
+
def forward(self, x):
|
| 168 |
+
return self.model(x)
|
| 169 |
+
|
| 170 |
+
# Initialize models
|
| 171 |
+
image_proj_model = ImageProjectionModel()
|
| 172 |
+
ip_adapter_model = IPAdapterModel()
|
| 173 |
+
|
| 174 |
+
# Load weights into models
|
| 175 |
+
image_proj_model.load_state_dict(image_proj_sd)
|
| 176 |
+
ip_adapter_model.load_state_dict(ip_adapter_sd)
|
| 177 |
+
|
| 178 |
+
# Set models to evaluation mode
|
| 179 |
+
image_proj_model.eval()
|
| 180 |
+
ip_adapter_model.eval()
|
| 181 |
+
|
| 182 |
+
#Inference pipeline
|
| 183 |
+
def inference(image_tensor):
|
| 184 |
+
"""
|
| 185 |
+
Run inference using the loaded models.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
image_tensor: Preprocessed image tensor from CLIPProcessor
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
Final inference results
|
| 192 |
+
"""
|
| 193 |
+
with torch.no_grad():
|
| 194 |
+
# Step 1: Project the image features
|
| 195 |
+
image_proj = image_proj_model(image_tensor)
|
| 196 |
+
|
| 197 |
+
# Step 2: Pass the projected features through the IP Adapter
|
| 198 |
+
result = ip_adapter_model(image_proj)
|
| 199 |
+
|
| 200 |
+
return result
|
| 201 |
+
|
| 202 |
+
# Using CLIP for image preprocessing
|
| 203 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 204 |
+
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 205 |
+
|
| 206 |
+
#Image file path
|
| 207 |
+
image_path = "path/to/image.jpg"
|
| 208 |
+
|
| 209 |
+
# Preprocess the image
|
| 210 |
+
inputs = processor(images=image_path, return_tensors="pt")
|
| 211 |
+
image_features = clip_model.get_image_features(inputs["pixel_values"])
|
| 212 |
+
|
| 213 |
+
# Normalize the image features as per CLIP's recommendations
|
| 214 |
+
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 215 |
+
|
| 216 |
+
# Run inference
|
| 217 |
+
output = inference(image_features)
|
| 218 |
+
print("Inference output:", output)
|
| 219 |
+
```
|
| 220 |
+
|
| 221 |
+
#### Parameters:
|
| 222 |
+
- `ckpt`: Path to the trained model checkpoint file.
|
| 223 |
+
- `map_location="cpu"`: Specifies that the model should be loaded onto the CPU.
|
| 224 |
+
- `image_proj_sd`: Dictionary to store the components related to image projection.
|
| 225 |
+
- `ip_sd`: Dictionary to store the components related to the IP adapter.
|
| 226 |
+
- `"unet"`, `"image_proj_model"`, `"adapter_modules"`: Prefixes indicating components of the model.
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.25.1
|
| 4 |
+
ip_adapter
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_faceid.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.nn.functional as F
|
| 11 |
+
from accelerate import Accelerator
|
| 12 |
+
from accelerate.utils import ProjectConfiguration
|
| 13 |
+
from ip_adapter.attention_processor_faceid import LoRAAttnProcessor, LoRAIPAttnProcessor
|
| 14 |
+
from ip_adapter.ip_adapter_faceid import MLPProjModel
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from torchvision import transforms
|
| 17 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 18 |
+
|
| 19 |
+
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Dataset
|
| 23 |
+
class MyDataset(torch.utils.data.Dataset):
|
| 24 |
+
def __init__(
|
| 25 |
+
self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
|
| 26 |
+
):
|
| 27 |
+
super().__init__()
|
| 28 |
+
|
| 29 |
+
self.tokenizer = tokenizer
|
| 30 |
+
self.size = size
|
| 31 |
+
self.i_drop_rate = i_drop_rate
|
| 32 |
+
self.t_drop_rate = t_drop_rate
|
| 33 |
+
self.ti_drop_rate = ti_drop_rate
|
| 34 |
+
self.image_root_path = image_root_path
|
| 35 |
+
|
| 36 |
+
self.data = json.load(
|
| 37 |
+
open(json_file)
|
| 38 |
+
) # list of dict: [{"image_file": "1.png", "id_embed_file": "faceid.bin"}]
|
| 39 |
+
|
| 40 |
+
self.transform = transforms.Compose(
|
| 41 |
+
[
|
| 42 |
+
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 43 |
+
transforms.CenterCrop(self.size),
|
| 44 |
+
transforms.ToTensor(),
|
| 45 |
+
transforms.Normalize([0.5], [0.5]),
|
| 46 |
+
]
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def __getitem__(self, idx):
|
| 50 |
+
item = self.data[idx]
|
| 51 |
+
text = item["text"]
|
| 52 |
+
image_file = item["image_file"]
|
| 53 |
+
|
| 54 |
+
# read image
|
| 55 |
+
raw_image = Image.open(os.path.join(self.image_root_path, image_file))
|
| 56 |
+
image = self.transform(raw_image.convert("RGB"))
|
| 57 |
+
|
| 58 |
+
face_id_embed = torch.load(item["id_embed_file"], map_location="cpu")
|
| 59 |
+
face_id_embed = torch.from_numpy(face_id_embed)
|
| 60 |
+
|
| 61 |
+
# drop
|
| 62 |
+
drop_image_embed = 0
|
| 63 |
+
rand_num = random.random()
|
| 64 |
+
if rand_num < self.i_drop_rate:
|
| 65 |
+
drop_image_embed = 1
|
| 66 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate):
|
| 67 |
+
text = ""
|
| 68 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
|
| 69 |
+
text = ""
|
| 70 |
+
drop_image_embed = 1
|
| 71 |
+
if drop_image_embed:
|
| 72 |
+
face_id_embed = torch.zeros_like(face_id_embed)
|
| 73 |
+
# get text and tokenize
|
| 74 |
+
text_input_ids = self.tokenizer(
|
| 75 |
+
text,
|
| 76 |
+
max_length=self.tokenizer.model_max_length,
|
| 77 |
+
padding="max_length",
|
| 78 |
+
truncation=True,
|
| 79 |
+
return_tensors="pt",
|
| 80 |
+
).input_ids
|
| 81 |
+
|
| 82 |
+
return {
|
| 83 |
+
"image": image,
|
| 84 |
+
"text_input_ids": text_input_ids,
|
| 85 |
+
"face_id_embed": face_id_embed,
|
| 86 |
+
"drop_image_embed": drop_image_embed,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def __len__(self):
|
| 90 |
+
return len(self.data)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def collate_fn(data):
|
| 94 |
+
images = torch.stack([example["image"] for example in data])
|
| 95 |
+
text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
|
| 96 |
+
face_id_embed = torch.stack([example["face_id_embed"] for example in data])
|
| 97 |
+
drop_image_embeds = [example["drop_image_embed"] for example in data]
|
| 98 |
+
|
| 99 |
+
return {
|
| 100 |
+
"images": images,
|
| 101 |
+
"text_input_ids": text_input_ids,
|
| 102 |
+
"face_id_embed": face_id_embed,
|
| 103 |
+
"drop_image_embeds": drop_image_embeds,
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class IPAdapter(torch.nn.Module):
|
| 108 |
+
"""IP-Adapter"""
|
| 109 |
+
|
| 110 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.unet = unet
|
| 113 |
+
self.image_proj_model = image_proj_model
|
| 114 |
+
self.adapter_modules = adapter_modules
|
| 115 |
+
|
| 116 |
+
if ckpt_path is not None:
|
| 117 |
+
self.load_from_checkpoint(ckpt_path)
|
| 118 |
+
|
| 119 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
|
| 120 |
+
ip_tokens = self.image_proj_model(image_embeds)
|
| 121 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 122 |
+
# Predict the noise residual
|
| 123 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 124 |
+
return noise_pred
|
| 125 |
+
|
| 126 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 127 |
+
# Calculate original checksums
|
| 128 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 129 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 130 |
+
|
| 131 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 132 |
+
|
| 133 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 134 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
|
| 135 |
+
self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
|
| 136 |
+
|
| 137 |
+
# Calculate new checksums
|
| 138 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 139 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 140 |
+
|
| 141 |
+
# Verify if the weights have changed
|
| 142 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 143 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
|
| 144 |
+
|
| 145 |
+
print(f"Successfully loaded weights from checkpoint {ckpt_path}")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def parse_args():
|
| 149 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--pretrained_model_name_or_path",
|
| 152 |
+
type=str,
|
| 153 |
+
default=None,
|
| 154 |
+
required=True,
|
| 155 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--pretrained_ip_adapter_path",
|
| 159 |
+
type=str,
|
| 160 |
+
default=None,
|
| 161 |
+
help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--data_json_file",
|
| 165 |
+
type=str,
|
| 166 |
+
default=None,
|
| 167 |
+
required=True,
|
| 168 |
+
help="Training data",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--data_root_path",
|
| 172 |
+
type=str,
|
| 173 |
+
default="",
|
| 174 |
+
required=True,
|
| 175 |
+
help="Training data root path",
|
| 176 |
+
)
|
| 177 |
+
parser.add_argument(
|
| 178 |
+
"--image_encoder_path",
|
| 179 |
+
type=str,
|
| 180 |
+
default=None,
|
| 181 |
+
required=True,
|
| 182 |
+
help="Path to CLIP image encoder",
|
| 183 |
+
)
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--output_dir",
|
| 186 |
+
type=str,
|
| 187 |
+
default="sd-ip_adapter",
|
| 188 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--logging_dir",
|
| 192 |
+
type=str,
|
| 193 |
+
default="logs",
|
| 194 |
+
help=(
|
| 195 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 196 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 197 |
+
),
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--resolution",
|
| 201 |
+
type=int,
|
| 202 |
+
default=512,
|
| 203 |
+
help=("The resolution for input images"),
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--learning_rate",
|
| 207 |
+
type=float,
|
| 208 |
+
default=1e-4,
|
| 209 |
+
help="Learning rate to use.",
|
| 210 |
+
)
|
| 211 |
+
parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 212 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
|
| 215 |
+
)
|
| 216 |
+
parser.add_argument(
|
| 217 |
+
"--dataloader_num_workers",
|
| 218 |
+
type=int,
|
| 219 |
+
default=0,
|
| 220 |
+
help=(
|
| 221 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 222 |
+
),
|
| 223 |
+
)
|
| 224 |
+
parser.add_argument(
|
| 225 |
+
"--save_steps",
|
| 226 |
+
type=int,
|
| 227 |
+
default=2000,
|
| 228 |
+
help=("Save a checkpoint of the training state every X updates"),
|
| 229 |
+
)
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--mixed_precision",
|
| 232 |
+
type=str,
|
| 233 |
+
default=None,
|
| 234 |
+
choices=["no", "fp16", "bf16"],
|
| 235 |
+
help=(
|
| 236 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 237 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 238 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 239 |
+
),
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument(
|
| 242 |
+
"--report_to",
|
| 243 |
+
type=str,
|
| 244 |
+
default="tensorboard",
|
| 245 |
+
help=(
|
| 246 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 247 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 248 |
+
),
|
| 249 |
+
)
|
| 250 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 251 |
+
|
| 252 |
+
args = parser.parse_args()
|
| 253 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 254 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 255 |
+
args.local_rank = env_local_rank
|
| 256 |
+
|
| 257 |
+
return args
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def main():
|
| 261 |
+
args = parse_args()
|
| 262 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 263 |
+
|
| 264 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 265 |
+
|
| 266 |
+
accelerator = Accelerator(
|
| 267 |
+
mixed_precision=args.mixed_precision,
|
| 268 |
+
log_with=args.report_to,
|
| 269 |
+
project_config=accelerator_project_config,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
if accelerator.is_main_process:
|
| 273 |
+
if args.output_dir is not None:
|
| 274 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 275 |
+
|
| 276 |
+
# Load scheduler, tokenizer and models.
|
| 277 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 278 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 279 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 280 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 281 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 282 |
+
# image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
|
| 283 |
+
# freeze parameters of models to save more memory
|
| 284 |
+
unet.requires_grad_(False)
|
| 285 |
+
vae.requires_grad_(False)
|
| 286 |
+
text_encoder.requires_grad_(False)
|
| 287 |
+
# image_encoder.requires_grad_(False)
|
| 288 |
+
|
| 289 |
+
# ip-adapter
|
| 290 |
+
image_proj_model = MLPProjModel(
|
| 291 |
+
cross_attention_dim=unet.config.cross_attention_dim,
|
| 292 |
+
id_embeddings_dim=512,
|
| 293 |
+
num_tokens=4,
|
| 294 |
+
)
|
| 295 |
+
# init adapter modules
|
| 296 |
+
lora_rank = 128
|
| 297 |
+
attn_procs = {}
|
| 298 |
+
unet_sd = unet.state_dict()
|
| 299 |
+
for name in unet.attn_processors.keys():
|
| 300 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 301 |
+
if name.startswith("mid_block"):
|
| 302 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 303 |
+
elif name.startswith("up_blocks"):
|
| 304 |
+
block_id = int(name[len("up_blocks.")])
|
| 305 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 306 |
+
elif name.startswith("down_blocks"):
|
| 307 |
+
block_id = int(name[len("down_blocks.")])
|
| 308 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 309 |
+
if cross_attention_dim is None:
|
| 310 |
+
attn_procs[name] = LoRAAttnProcessor(
|
| 311 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank
|
| 312 |
+
)
|
| 313 |
+
else:
|
| 314 |
+
layer_name = name.split(".processor")[0]
|
| 315 |
+
weights = {
|
| 316 |
+
"to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
|
| 317 |
+
"to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
|
| 318 |
+
}
|
| 319 |
+
attn_procs[name] = LoRAIPAttnProcessor(
|
| 320 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank
|
| 321 |
+
)
|
| 322 |
+
attn_procs[name].load_state_dict(weights, strict=False)
|
| 323 |
+
unet.set_attn_processor(attn_procs)
|
| 324 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 325 |
+
|
| 326 |
+
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
|
| 327 |
+
|
| 328 |
+
weight_dtype = torch.float32
|
| 329 |
+
if accelerator.mixed_precision == "fp16":
|
| 330 |
+
weight_dtype = torch.float16
|
| 331 |
+
elif accelerator.mixed_precision == "bf16":
|
| 332 |
+
weight_dtype = torch.bfloat16
|
| 333 |
+
# unet.to(accelerator.device, dtype=weight_dtype)
|
| 334 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 335 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 336 |
+
# image_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 337 |
+
|
| 338 |
+
# optimizer
|
| 339 |
+
params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
|
| 340 |
+
optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 341 |
+
|
| 342 |
+
# dataloader
|
| 343 |
+
train_dataset = MyDataset(
|
| 344 |
+
args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
|
| 345 |
+
)
|
| 346 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 347 |
+
train_dataset,
|
| 348 |
+
shuffle=True,
|
| 349 |
+
collate_fn=collate_fn,
|
| 350 |
+
batch_size=args.train_batch_size,
|
| 351 |
+
num_workers=args.dataloader_num_workers,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# Prepare everything with our `accelerator`.
|
| 355 |
+
ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
|
| 356 |
+
|
| 357 |
+
global_step = 0
|
| 358 |
+
for epoch in range(0, args.num_train_epochs):
|
| 359 |
+
begin = time.perf_counter()
|
| 360 |
+
for step, batch in enumerate(train_dataloader):
|
| 361 |
+
load_data_time = time.perf_counter() - begin
|
| 362 |
+
with accelerator.accumulate(ip_adapter):
|
| 363 |
+
# Convert images to latent space
|
| 364 |
+
with torch.no_grad():
|
| 365 |
+
latents = vae.encode(
|
| 366 |
+
batch["images"].to(accelerator.device, dtype=weight_dtype)
|
| 367 |
+
).latent_dist.sample()
|
| 368 |
+
latents = latents * vae.config.scaling_factor
|
| 369 |
+
|
| 370 |
+
# Sample noise that we'll add to the latents
|
| 371 |
+
noise = torch.randn_like(latents)
|
| 372 |
+
bsz = latents.shape[0]
|
| 373 |
+
# Sample a random timestep for each image
|
| 374 |
+
timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
|
| 375 |
+
timesteps = timesteps.long()
|
| 376 |
+
|
| 377 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 378 |
+
# (this is the forward diffusion process)
|
| 379 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 380 |
+
|
| 381 |
+
image_embeds = batch["face_id_embed"].to(accelerator.device, dtype=weight_dtype)
|
| 382 |
+
|
| 383 |
+
with torch.no_grad():
|
| 384 |
+
encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
|
| 385 |
+
|
| 386 |
+
noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
|
| 387 |
+
|
| 388 |
+
loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
|
| 389 |
+
|
| 390 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 391 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
|
| 392 |
+
|
| 393 |
+
# Backpropagate
|
| 394 |
+
accelerator.backward(loss)
|
| 395 |
+
optimizer.step()
|
| 396 |
+
optimizer.zero_grad()
|
| 397 |
+
|
| 398 |
+
if accelerator.is_main_process:
|
| 399 |
+
print(
|
| 400 |
+
"Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
|
| 401 |
+
epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
|
| 402 |
+
)
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
global_step += 1
|
| 406 |
+
|
| 407 |
+
if global_step % args.save_steps == 0:
|
| 408 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 409 |
+
accelerator.save_state(save_path)
|
| 410 |
+
|
| 411 |
+
begin = time.perf_counter()
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
if __name__ == "__main__":
|
| 415 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_ip-adapter.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from accelerate import Accelerator
|
| 12 |
+
from accelerate.utils import ProjectConfiguration
|
| 13 |
+
from ip_adapter.ip_adapter import ImageProjModel
|
| 14 |
+
from ip_adapter.utils import is_torch2_available
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from torchvision import transforms
|
| 17 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
| 18 |
+
|
| 19 |
+
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if is_torch2_available():
|
| 23 |
+
from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
|
| 24 |
+
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
|
| 25 |
+
else:
|
| 26 |
+
from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Dataset
|
| 30 |
+
class MyDataset(torch.utils.data.Dataset):
|
| 31 |
+
def __init__(
|
| 32 |
+
self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
|
| 33 |
+
):
|
| 34 |
+
super().__init__()
|
| 35 |
+
|
| 36 |
+
self.tokenizer = tokenizer
|
| 37 |
+
self.size = size
|
| 38 |
+
self.i_drop_rate = i_drop_rate
|
| 39 |
+
self.t_drop_rate = t_drop_rate
|
| 40 |
+
self.ti_drop_rate = ti_drop_rate
|
| 41 |
+
self.image_root_path = image_root_path
|
| 42 |
+
|
| 43 |
+
self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
|
| 44 |
+
|
| 45 |
+
self.transform = transforms.Compose(
|
| 46 |
+
[
|
| 47 |
+
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 48 |
+
transforms.CenterCrop(self.size),
|
| 49 |
+
transforms.ToTensor(),
|
| 50 |
+
transforms.Normalize([0.5], [0.5]),
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 54 |
+
|
| 55 |
+
def __getitem__(self, idx):
|
| 56 |
+
item = self.data[idx]
|
| 57 |
+
text = item["text"]
|
| 58 |
+
image_file = item["image_file"]
|
| 59 |
+
|
| 60 |
+
# read image
|
| 61 |
+
raw_image = Image.open(os.path.join(self.image_root_path, image_file))
|
| 62 |
+
image = self.transform(raw_image.convert("RGB"))
|
| 63 |
+
clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
|
| 64 |
+
|
| 65 |
+
# drop
|
| 66 |
+
drop_image_embed = 0
|
| 67 |
+
rand_num = random.random()
|
| 68 |
+
if rand_num < self.i_drop_rate:
|
| 69 |
+
drop_image_embed = 1
|
| 70 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate):
|
| 71 |
+
text = ""
|
| 72 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
|
| 73 |
+
text = ""
|
| 74 |
+
drop_image_embed = 1
|
| 75 |
+
# get text and tokenize
|
| 76 |
+
text_input_ids = self.tokenizer(
|
| 77 |
+
text,
|
| 78 |
+
max_length=self.tokenizer.model_max_length,
|
| 79 |
+
padding="max_length",
|
| 80 |
+
truncation=True,
|
| 81 |
+
return_tensors="pt",
|
| 82 |
+
).input_ids
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"image": image,
|
| 86 |
+
"text_input_ids": text_input_ids,
|
| 87 |
+
"clip_image": clip_image,
|
| 88 |
+
"drop_image_embed": drop_image_embed,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
def __len__(self):
|
| 92 |
+
return len(self.data)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def collate_fn(data):
|
| 96 |
+
images = torch.stack([example["image"] for example in data])
|
| 97 |
+
text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
|
| 98 |
+
clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
|
| 99 |
+
drop_image_embeds = [example["drop_image_embed"] for example in data]
|
| 100 |
+
|
| 101 |
+
return {
|
| 102 |
+
"images": images,
|
| 103 |
+
"text_input_ids": text_input_ids,
|
| 104 |
+
"clip_images": clip_images,
|
| 105 |
+
"drop_image_embeds": drop_image_embeds,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class IPAdapter(torch.nn.Module):
|
| 110 |
+
"""IP-Adapter"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.unet = unet
|
| 115 |
+
self.image_proj_model = image_proj_model
|
| 116 |
+
self.adapter_modules = adapter_modules
|
| 117 |
+
|
| 118 |
+
if ckpt_path is not None:
|
| 119 |
+
self.load_from_checkpoint(ckpt_path)
|
| 120 |
+
|
| 121 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
|
| 122 |
+
ip_tokens = self.image_proj_model(image_embeds)
|
| 123 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 124 |
+
# Predict the noise residual
|
| 125 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 126 |
+
return noise_pred
|
| 127 |
+
|
| 128 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 129 |
+
# Calculate original checksums
|
| 130 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 131 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 132 |
+
|
| 133 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 134 |
+
|
| 135 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 136 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
|
| 137 |
+
self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
|
| 138 |
+
|
| 139 |
+
# Calculate new checksums
|
| 140 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 141 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 142 |
+
|
| 143 |
+
# Verify if the weights have changed
|
| 144 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 145 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
|
| 146 |
+
|
| 147 |
+
print(f"Successfully loaded weights from checkpoint {ckpt_path}")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def parse_args():
|
| 151 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--pretrained_model_name_or_path",
|
| 154 |
+
type=str,
|
| 155 |
+
default=None,
|
| 156 |
+
required=True,
|
| 157 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument(
|
| 160 |
+
"--pretrained_ip_adapter_path",
|
| 161 |
+
type=str,
|
| 162 |
+
default=None,
|
| 163 |
+
help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--data_json_file",
|
| 167 |
+
type=str,
|
| 168 |
+
default=None,
|
| 169 |
+
required=True,
|
| 170 |
+
help="Training data",
|
| 171 |
+
)
|
| 172 |
+
parser.add_argument(
|
| 173 |
+
"--data_root_path",
|
| 174 |
+
type=str,
|
| 175 |
+
default="",
|
| 176 |
+
required=True,
|
| 177 |
+
help="Training data root path",
|
| 178 |
+
)
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--image_encoder_path",
|
| 181 |
+
type=str,
|
| 182 |
+
default=None,
|
| 183 |
+
required=True,
|
| 184 |
+
help="Path to CLIP image encoder",
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--output_dir",
|
| 188 |
+
type=str,
|
| 189 |
+
default="sd-ip_adapter",
|
| 190 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 191 |
+
)
|
| 192 |
+
parser.add_argument(
|
| 193 |
+
"--logging_dir",
|
| 194 |
+
type=str,
|
| 195 |
+
default="logs",
|
| 196 |
+
help=(
|
| 197 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 198 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 199 |
+
),
|
| 200 |
+
)
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--resolution",
|
| 203 |
+
type=int,
|
| 204 |
+
default=512,
|
| 205 |
+
help=("The resolution for input images"),
|
| 206 |
+
)
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--learning_rate",
|
| 209 |
+
type=float,
|
| 210 |
+
default=1e-4,
|
| 211 |
+
help="Learning rate to use.",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 214 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--dataloader_num_workers",
|
| 220 |
+
type=int,
|
| 221 |
+
default=0,
|
| 222 |
+
help=(
|
| 223 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 224 |
+
),
|
| 225 |
+
)
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
"--save_steps",
|
| 228 |
+
type=int,
|
| 229 |
+
default=2000,
|
| 230 |
+
help=("Save a checkpoint of the training state every X updates"),
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--mixed_precision",
|
| 234 |
+
type=str,
|
| 235 |
+
default=None,
|
| 236 |
+
choices=["no", "fp16", "bf16"],
|
| 237 |
+
help=(
|
| 238 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 239 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 240 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 241 |
+
),
|
| 242 |
+
)
|
| 243 |
+
parser.add_argument(
|
| 244 |
+
"--report_to",
|
| 245 |
+
type=str,
|
| 246 |
+
default="tensorboard",
|
| 247 |
+
help=(
|
| 248 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 249 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 250 |
+
),
|
| 251 |
+
)
|
| 252 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 253 |
+
|
| 254 |
+
args = parser.parse_args()
|
| 255 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 256 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 257 |
+
args.local_rank = env_local_rank
|
| 258 |
+
|
| 259 |
+
return args
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def main():
|
| 263 |
+
args = parse_args()
|
| 264 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 265 |
+
|
| 266 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 267 |
+
|
| 268 |
+
accelerator = Accelerator(
|
| 269 |
+
mixed_precision=args.mixed_precision,
|
| 270 |
+
log_with=args.report_to,
|
| 271 |
+
project_config=accelerator_project_config,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if accelerator.is_main_process:
|
| 275 |
+
if args.output_dir is not None:
|
| 276 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 277 |
+
|
| 278 |
+
# Load scheduler, tokenizer and models.
|
| 279 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 280 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 281 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 282 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 283 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 284 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
|
| 285 |
+
# freeze parameters of models to save more memory
|
| 286 |
+
unet.requires_grad_(False)
|
| 287 |
+
vae.requires_grad_(False)
|
| 288 |
+
text_encoder.requires_grad_(False)
|
| 289 |
+
image_encoder.requires_grad_(False)
|
| 290 |
+
|
| 291 |
+
# ip-adapter
|
| 292 |
+
image_proj_model = ImageProjModel(
|
| 293 |
+
cross_attention_dim=unet.config.cross_attention_dim,
|
| 294 |
+
clip_embeddings_dim=image_encoder.config.projection_dim,
|
| 295 |
+
clip_extra_context_tokens=4,
|
| 296 |
+
)
|
| 297 |
+
# init adapter modules
|
| 298 |
+
attn_procs = {}
|
| 299 |
+
unet_sd = unet.state_dict()
|
| 300 |
+
for name in unet.attn_processors.keys():
|
| 301 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 302 |
+
if name.startswith("mid_block"):
|
| 303 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 304 |
+
elif name.startswith("up_blocks"):
|
| 305 |
+
block_id = int(name[len("up_blocks.")])
|
| 306 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 307 |
+
elif name.startswith("down_blocks"):
|
| 308 |
+
block_id = int(name[len("down_blocks.")])
|
| 309 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 310 |
+
if cross_attention_dim is None:
|
| 311 |
+
attn_procs[name] = AttnProcessor()
|
| 312 |
+
else:
|
| 313 |
+
layer_name = name.split(".processor")[0]
|
| 314 |
+
weights = {
|
| 315 |
+
"to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
|
| 316 |
+
"to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
|
| 317 |
+
}
|
| 318 |
+
attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
|
| 319 |
+
attn_procs[name].load_state_dict(weights)
|
| 320 |
+
unet.set_attn_processor(attn_procs)
|
| 321 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 322 |
+
|
| 323 |
+
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
|
| 324 |
+
|
| 325 |
+
weight_dtype = torch.float32
|
| 326 |
+
if accelerator.mixed_precision == "fp16":
|
| 327 |
+
weight_dtype = torch.float16
|
| 328 |
+
elif accelerator.mixed_precision == "bf16":
|
| 329 |
+
weight_dtype = torch.bfloat16
|
| 330 |
+
# unet.to(accelerator.device, dtype=weight_dtype)
|
| 331 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 332 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 333 |
+
image_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 334 |
+
|
| 335 |
+
# optimizer
|
| 336 |
+
params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
|
| 337 |
+
optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 338 |
+
|
| 339 |
+
# dataloader
|
| 340 |
+
train_dataset = MyDataset(
|
| 341 |
+
args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
|
| 342 |
+
)
|
| 343 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 344 |
+
train_dataset,
|
| 345 |
+
shuffle=True,
|
| 346 |
+
collate_fn=collate_fn,
|
| 347 |
+
batch_size=args.train_batch_size,
|
| 348 |
+
num_workers=args.dataloader_num_workers,
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
# Prepare everything with our `accelerator`.
|
| 352 |
+
ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
|
| 353 |
+
|
| 354 |
+
global_step = 0
|
| 355 |
+
for epoch in range(0, args.num_train_epochs):
|
| 356 |
+
begin = time.perf_counter()
|
| 357 |
+
for step, batch in enumerate(train_dataloader):
|
| 358 |
+
load_data_time = time.perf_counter() - begin
|
| 359 |
+
with accelerator.accumulate(ip_adapter):
|
| 360 |
+
# Convert images to latent space
|
| 361 |
+
with torch.no_grad():
|
| 362 |
+
latents = vae.encode(
|
| 363 |
+
batch["images"].to(accelerator.device, dtype=weight_dtype)
|
| 364 |
+
).latent_dist.sample()
|
| 365 |
+
latents = latents * vae.config.scaling_factor
|
| 366 |
+
|
| 367 |
+
# Sample noise that we'll add to the latents
|
| 368 |
+
noise = torch.randn_like(latents)
|
| 369 |
+
bsz = latents.shape[0]
|
| 370 |
+
# Sample a random timestep for each image
|
| 371 |
+
timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
|
| 372 |
+
timesteps = timesteps.long()
|
| 373 |
+
|
| 374 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 375 |
+
# (this is the forward diffusion process)
|
| 376 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 377 |
+
|
| 378 |
+
with torch.no_grad():
|
| 379 |
+
image_embeds = image_encoder(
|
| 380 |
+
batch["clip_images"].to(accelerator.device, dtype=weight_dtype)
|
| 381 |
+
).image_embeds
|
| 382 |
+
image_embeds_ = []
|
| 383 |
+
for image_embed, drop_image_embed in zip(image_embeds, batch["drop_image_embeds"]):
|
| 384 |
+
if drop_image_embed == 1:
|
| 385 |
+
image_embeds_.append(torch.zeros_like(image_embed))
|
| 386 |
+
else:
|
| 387 |
+
image_embeds_.append(image_embed)
|
| 388 |
+
image_embeds = torch.stack(image_embeds_)
|
| 389 |
+
|
| 390 |
+
with torch.no_grad():
|
| 391 |
+
encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
|
| 392 |
+
|
| 393 |
+
noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
|
| 394 |
+
|
| 395 |
+
loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
|
| 396 |
+
|
| 397 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 398 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
|
| 399 |
+
|
| 400 |
+
# Backpropagate
|
| 401 |
+
accelerator.backward(loss)
|
| 402 |
+
optimizer.step()
|
| 403 |
+
optimizer.zero_grad()
|
| 404 |
+
|
| 405 |
+
if accelerator.is_main_process:
|
| 406 |
+
print(
|
| 407 |
+
"Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
|
| 408 |
+
epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
|
| 409 |
+
)
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
global_step += 1
|
| 413 |
+
|
| 414 |
+
if global_step % args.save_steps == 0:
|
| 415 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 416 |
+
accelerator.save_state(save_path)
|
| 417 |
+
|
| 418 |
+
begin = time.perf_counter()
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
if __name__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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from accelerate import Accelerator
|
| 12 |
+
from accelerate.utils import ProjectConfiguration
|
| 13 |
+
from ip_adapter.resampler import Resampler
|
| 14 |
+
from ip_adapter.utils import is_torch2_available
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from torchvision import transforms
|
| 17 |
+
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
| 18 |
+
|
| 19 |
+
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if is_torch2_available():
|
| 23 |
+
from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
|
| 24 |
+
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
|
| 25 |
+
else:
|
| 26 |
+
from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Dataset
|
| 30 |
+
class MyDataset(torch.utils.data.Dataset):
|
| 31 |
+
def __init__(
|
| 32 |
+
self, json_file, tokenizer, size=512, t_drop_rate=0.05, i_drop_rate=0.05, ti_drop_rate=0.05, image_root_path=""
|
| 33 |
+
):
|
| 34 |
+
super().__init__()
|
| 35 |
+
|
| 36 |
+
self.tokenizer = tokenizer
|
| 37 |
+
self.size = size
|
| 38 |
+
self.i_drop_rate = i_drop_rate
|
| 39 |
+
self.t_drop_rate = t_drop_rate
|
| 40 |
+
self.ti_drop_rate = ti_drop_rate
|
| 41 |
+
self.image_root_path = image_root_path
|
| 42 |
+
|
| 43 |
+
self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
|
| 44 |
+
|
| 45 |
+
self.transform = transforms.Compose(
|
| 46 |
+
[
|
| 47 |
+
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 48 |
+
transforms.CenterCrop(self.size),
|
| 49 |
+
transforms.ToTensor(),
|
| 50 |
+
transforms.Normalize([0.5], [0.5]),
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 54 |
+
|
| 55 |
+
def __getitem__(self, idx):
|
| 56 |
+
item = self.data[idx]
|
| 57 |
+
text = item["text"]
|
| 58 |
+
image_file = item["image_file"]
|
| 59 |
+
|
| 60 |
+
# read image
|
| 61 |
+
raw_image = Image.open(os.path.join(self.image_root_path, image_file))
|
| 62 |
+
image = self.transform(raw_image.convert("RGB"))
|
| 63 |
+
clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
|
| 64 |
+
|
| 65 |
+
# drop
|
| 66 |
+
drop_image_embed = 0
|
| 67 |
+
rand_num = random.random()
|
| 68 |
+
if rand_num < self.i_drop_rate:
|
| 69 |
+
drop_image_embed = 1
|
| 70 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate):
|
| 71 |
+
text = ""
|
| 72 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
|
| 73 |
+
text = ""
|
| 74 |
+
drop_image_embed = 1
|
| 75 |
+
# get text and tokenize
|
| 76 |
+
text_input_ids = self.tokenizer(
|
| 77 |
+
text,
|
| 78 |
+
max_length=self.tokenizer.model_max_length,
|
| 79 |
+
padding="max_length",
|
| 80 |
+
truncation=True,
|
| 81 |
+
return_tensors="pt",
|
| 82 |
+
).input_ids
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"image": image,
|
| 86 |
+
"text_input_ids": text_input_ids,
|
| 87 |
+
"clip_image": clip_image,
|
| 88 |
+
"drop_image_embed": drop_image_embed,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
def __len__(self):
|
| 92 |
+
return len(self.data)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def collate_fn(data):
|
| 96 |
+
images = torch.stack([example["image"] for example in data])
|
| 97 |
+
text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
|
| 98 |
+
clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
|
| 99 |
+
drop_image_embeds = [example["drop_image_embed"] for example in data]
|
| 100 |
+
|
| 101 |
+
return {
|
| 102 |
+
"images": images,
|
| 103 |
+
"text_input_ids": text_input_ids,
|
| 104 |
+
"clip_images": clip_images,
|
| 105 |
+
"drop_image_embeds": drop_image_embeds,
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class IPAdapter(torch.nn.Module):
|
| 110 |
+
"""IP-Adapter"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.unet = unet
|
| 115 |
+
self.image_proj_model = image_proj_model
|
| 116 |
+
self.adapter_modules = adapter_modules
|
| 117 |
+
|
| 118 |
+
if ckpt_path is not None:
|
| 119 |
+
self.load_from_checkpoint(ckpt_path)
|
| 120 |
+
|
| 121 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, image_embeds):
|
| 122 |
+
ip_tokens = self.image_proj_model(image_embeds)
|
| 123 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 124 |
+
# Predict the noise residual
|
| 125 |
+
noise_pred = self.unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 126 |
+
return noise_pred
|
| 127 |
+
|
| 128 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 129 |
+
# Calculate original checksums
|
| 130 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 131 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 132 |
+
|
| 133 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 134 |
+
|
| 135 |
+
# Check if 'latents' exists in both the saved state_dict and the current model's state_dict
|
| 136 |
+
strict_load_image_proj_model = True
|
| 137 |
+
if "latents" in state_dict["image_proj"] and "latents" in self.image_proj_model.state_dict():
|
| 138 |
+
# Check if the shapes are mismatched
|
| 139 |
+
if state_dict["image_proj"]["latents"].shape != self.image_proj_model.state_dict()["latents"].shape:
|
| 140 |
+
print(f"Shapes of 'image_proj.latents' in checkpoint {ckpt_path} and current model do not match.")
|
| 141 |
+
print("Removing 'latents' from checkpoint and loading the rest of the weights.")
|
| 142 |
+
del state_dict["image_proj"]["latents"]
|
| 143 |
+
strict_load_image_proj_model = False
|
| 144 |
+
|
| 145 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 146 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=strict_load_image_proj_model)
|
| 147 |
+
self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
|
| 148 |
+
|
| 149 |
+
# Calculate new checksums
|
| 150 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 151 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 152 |
+
|
| 153 |
+
# Verify if the weights have changed
|
| 154 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 155 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
|
| 156 |
+
|
| 157 |
+
print(f"Successfully loaded weights from checkpoint {ckpt_path}")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def parse_args():
|
| 161 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 162 |
+
parser.add_argument(
|
| 163 |
+
"--pretrained_model_name_or_path",
|
| 164 |
+
type=str,
|
| 165 |
+
default=None,
|
| 166 |
+
required=True,
|
| 167 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--pretrained_ip_adapter_path",
|
| 171 |
+
type=str,
|
| 172 |
+
default=None,
|
| 173 |
+
help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
|
| 174 |
+
)
|
| 175 |
+
parser.add_argument(
|
| 176 |
+
"--num_tokens",
|
| 177 |
+
type=int,
|
| 178 |
+
default=16,
|
| 179 |
+
help="Number of tokens to query from the CLIP image encoding.",
|
| 180 |
+
)
|
| 181 |
+
parser.add_argument(
|
| 182 |
+
"--data_json_file",
|
| 183 |
+
type=str,
|
| 184 |
+
default=None,
|
| 185 |
+
required=True,
|
| 186 |
+
help="Training data",
|
| 187 |
+
)
|
| 188 |
+
parser.add_argument(
|
| 189 |
+
"--data_root_path",
|
| 190 |
+
type=str,
|
| 191 |
+
default="",
|
| 192 |
+
required=True,
|
| 193 |
+
help="Training data root path",
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--image_encoder_path",
|
| 197 |
+
type=str,
|
| 198 |
+
default=None,
|
| 199 |
+
required=True,
|
| 200 |
+
help="Path to CLIP image encoder",
|
| 201 |
+
)
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--output_dir",
|
| 204 |
+
type=str,
|
| 205 |
+
default="sd-ip_adapter",
|
| 206 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 207 |
+
)
|
| 208 |
+
parser.add_argument(
|
| 209 |
+
"--logging_dir",
|
| 210 |
+
type=str,
|
| 211 |
+
default="logs",
|
| 212 |
+
help=(
|
| 213 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 214 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 215 |
+
),
|
| 216 |
+
)
|
| 217 |
+
parser.add_argument(
|
| 218 |
+
"--resolution",
|
| 219 |
+
type=int,
|
| 220 |
+
default=512,
|
| 221 |
+
help=("The resolution for input images"),
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--learning_rate",
|
| 225 |
+
type=float,
|
| 226 |
+
default=1e-4,
|
| 227 |
+
help="Learning rate to use.",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 230 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument(
|
| 235 |
+
"--dataloader_num_workers",
|
| 236 |
+
type=int,
|
| 237 |
+
default=0,
|
| 238 |
+
help=(
|
| 239 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 240 |
+
),
|
| 241 |
+
)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--save_steps",
|
| 244 |
+
type=int,
|
| 245 |
+
default=2000,
|
| 246 |
+
help=("Save a checkpoint of the training state every X updates"),
|
| 247 |
+
)
|
| 248 |
+
parser.add_argument(
|
| 249 |
+
"--mixed_precision",
|
| 250 |
+
type=str,
|
| 251 |
+
default=None,
|
| 252 |
+
choices=["no", "fp16", "bf16"],
|
| 253 |
+
help=(
|
| 254 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 255 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 256 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 257 |
+
),
|
| 258 |
+
)
|
| 259 |
+
parser.add_argument(
|
| 260 |
+
"--report_to",
|
| 261 |
+
type=str,
|
| 262 |
+
default="tensorboard",
|
| 263 |
+
help=(
|
| 264 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 265 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 266 |
+
),
|
| 267 |
+
)
|
| 268 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 269 |
+
|
| 270 |
+
args = parser.parse_args()
|
| 271 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 272 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 273 |
+
args.local_rank = env_local_rank
|
| 274 |
+
|
| 275 |
+
return args
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def main():
|
| 279 |
+
args = parse_args()
|
| 280 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 281 |
+
|
| 282 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 283 |
+
|
| 284 |
+
accelerator = Accelerator(
|
| 285 |
+
mixed_precision=args.mixed_precision,
|
| 286 |
+
log_with=args.report_to,
|
| 287 |
+
project_config=accelerator_project_config,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
if accelerator.is_main_process:
|
| 291 |
+
if args.output_dir is not None:
|
| 292 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 293 |
+
|
| 294 |
+
# Load scheduler, tokenizer and models.
|
| 295 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 296 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 297 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 298 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 299 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 300 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
|
| 301 |
+
# freeze parameters of models to save more memory
|
| 302 |
+
unet.requires_grad_(False)
|
| 303 |
+
vae.requires_grad_(False)
|
| 304 |
+
text_encoder.requires_grad_(False)
|
| 305 |
+
image_encoder.requires_grad_(False)
|
| 306 |
+
|
| 307 |
+
# ip-adapter-plus
|
| 308 |
+
image_proj_model = Resampler(
|
| 309 |
+
dim=unet.config.cross_attention_dim,
|
| 310 |
+
depth=4,
|
| 311 |
+
dim_head=64,
|
| 312 |
+
heads=12,
|
| 313 |
+
num_queries=args.num_tokens,
|
| 314 |
+
embedding_dim=image_encoder.config.hidden_size,
|
| 315 |
+
output_dim=unet.config.cross_attention_dim,
|
| 316 |
+
ff_mult=4,
|
| 317 |
+
)
|
| 318 |
+
# init adapter modules
|
| 319 |
+
attn_procs = {}
|
| 320 |
+
unet_sd = unet.state_dict()
|
| 321 |
+
for name in unet.attn_processors.keys():
|
| 322 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 323 |
+
if name.startswith("mid_block"):
|
| 324 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 325 |
+
elif name.startswith("up_blocks"):
|
| 326 |
+
block_id = int(name[len("up_blocks.")])
|
| 327 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 328 |
+
elif name.startswith("down_blocks"):
|
| 329 |
+
block_id = int(name[len("down_blocks.")])
|
| 330 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 331 |
+
if cross_attention_dim is None:
|
| 332 |
+
attn_procs[name] = AttnProcessor()
|
| 333 |
+
else:
|
| 334 |
+
layer_name = name.split(".processor")[0]
|
| 335 |
+
weights = {
|
| 336 |
+
"to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
|
| 337 |
+
"to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
|
| 338 |
+
}
|
| 339 |
+
attn_procs[name] = IPAttnProcessor(
|
| 340 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=args.num_tokens
|
| 341 |
+
)
|
| 342 |
+
attn_procs[name].load_state_dict(weights)
|
| 343 |
+
unet.set_attn_processor(attn_procs)
|
| 344 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 345 |
+
|
| 346 |
+
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
|
| 347 |
+
|
| 348 |
+
weight_dtype = torch.float32
|
| 349 |
+
if accelerator.mixed_precision == "fp16":
|
| 350 |
+
weight_dtype = torch.float16
|
| 351 |
+
elif accelerator.mixed_precision == "bf16":
|
| 352 |
+
weight_dtype = torch.bfloat16
|
| 353 |
+
# unet.to(accelerator.device, dtype=weight_dtype)
|
| 354 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 355 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 356 |
+
image_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 357 |
+
|
| 358 |
+
# optimizer
|
| 359 |
+
params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
|
| 360 |
+
optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 361 |
+
|
| 362 |
+
# dataloader
|
| 363 |
+
train_dataset = MyDataset(
|
| 364 |
+
args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path
|
| 365 |
+
)
|
| 366 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 367 |
+
train_dataset,
|
| 368 |
+
shuffle=True,
|
| 369 |
+
collate_fn=collate_fn,
|
| 370 |
+
batch_size=args.train_batch_size,
|
| 371 |
+
num_workers=args.dataloader_num_workers,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
# Prepare everything with our `accelerator`.
|
| 375 |
+
ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
|
| 376 |
+
|
| 377 |
+
global_step = 0
|
| 378 |
+
for epoch in range(0, args.num_train_epochs):
|
| 379 |
+
begin = time.perf_counter()
|
| 380 |
+
for step, batch in enumerate(train_dataloader):
|
| 381 |
+
load_data_time = time.perf_counter() - begin
|
| 382 |
+
with accelerator.accumulate(ip_adapter):
|
| 383 |
+
# Convert images to latent space
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
latents = vae.encode(
|
| 386 |
+
batch["images"].to(accelerator.device, dtype=weight_dtype)
|
| 387 |
+
).latent_dist.sample()
|
| 388 |
+
latents = latents * vae.config.scaling_factor
|
| 389 |
+
|
| 390 |
+
# Sample noise that we'll add to the latents
|
| 391 |
+
noise = torch.randn_like(latents)
|
| 392 |
+
bsz = latents.shape[0]
|
| 393 |
+
# Sample a random timestep for each image
|
| 394 |
+
timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
|
| 395 |
+
timesteps = timesteps.long()
|
| 396 |
+
|
| 397 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 398 |
+
# (this is the forward diffusion process)
|
| 399 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 400 |
+
|
| 401 |
+
clip_images = []
|
| 402 |
+
for clip_image, drop_image_embed in zip(batch["clip_images"], batch["drop_image_embeds"]):
|
| 403 |
+
if drop_image_embed == 1:
|
| 404 |
+
clip_images.append(torch.zeros_like(clip_image))
|
| 405 |
+
else:
|
| 406 |
+
clip_images.append(clip_image)
|
| 407 |
+
clip_images = torch.stack(clip_images, dim=0)
|
| 408 |
+
with torch.no_grad():
|
| 409 |
+
image_embeds = image_encoder(
|
| 410 |
+
clip_images.to(accelerator.device, dtype=weight_dtype), output_hidden_states=True
|
| 411 |
+
).hidden_states[-2]
|
| 412 |
+
|
| 413 |
+
with torch.no_grad():
|
| 414 |
+
encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
|
| 415 |
+
|
| 416 |
+
noise_pred = ip_adapter(noisy_latents, timesteps, encoder_hidden_states, image_embeds)
|
| 417 |
+
|
| 418 |
+
loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
|
| 419 |
+
|
| 420 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 421 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
|
| 422 |
+
|
| 423 |
+
# Backpropagate
|
| 424 |
+
accelerator.backward(loss)
|
| 425 |
+
optimizer.step()
|
| 426 |
+
optimizer.zero_grad()
|
| 427 |
+
|
| 428 |
+
if accelerator.is_main_process:
|
| 429 |
+
print(
|
| 430 |
+
"Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
|
| 431 |
+
epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
global_step += 1
|
| 436 |
+
|
| 437 |
+
if global_step % args.save_steps == 0:
|
| 438 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 439 |
+
accelerator.save_state(save_path)
|
| 440 |
+
|
| 441 |
+
begin = time.perf_counter()
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
if __name__ == "__main__":
|
| 445 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/ip_adapter/tutorial_train_sdxl.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import itertools
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from accelerate import Accelerator
|
| 13 |
+
from accelerate.utils import ProjectConfiguration
|
| 14 |
+
from ip_adapter.ip_adapter import ImageProjModel
|
| 15 |
+
from ip_adapter.utils import is_torch2_available
|
| 16 |
+
from PIL import Image
|
| 17 |
+
from torchvision import transforms
|
| 18 |
+
from transformers import (
|
| 19 |
+
CLIPImageProcessor,
|
| 20 |
+
CLIPTextModel,
|
| 21 |
+
CLIPTextModelWithProjection,
|
| 22 |
+
CLIPTokenizer,
|
| 23 |
+
CLIPVisionModelWithProjection,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch2_available():
|
| 30 |
+
from ip_adapter.attention_processor import AttnProcessor2_0 as AttnProcessor
|
| 31 |
+
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
|
| 32 |
+
else:
|
| 33 |
+
from ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Dataset
|
| 37 |
+
class MyDataset(torch.utils.data.Dataset):
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
json_file,
|
| 41 |
+
tokenizer,
|
| 42 |
+
tokenizer_2,
|
| 43 |
+
size=1024,
|
| 44 |
+
center_crop=True,
|
| 45 |
+
t_drop_rate=0.05,
|
| 46 |
+
i_drop_rate=0.05,
|
| 47 |
+
ti_drop_rate=0.05,
|
| 48 |
+
image_root_path="",
|
| 49 |
+
):
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
self.tokenizer = tokenizer
|
| 53 |
+
self.tokenizer_2 = tokenizer_2
|
| 54 |
+
self.size = size
|
| 55 |
+
self.center_crop = center_crop
|
| 56 |
+
self.i_drop_rate = i_drop_rate
|
| 57 |
+
self.t_drop_rate = t_drop_rate
|
| 58 |
+
self.ti_drop_rate = ti_drop_rate
|
| 59 |
+
self.image_root_path = image_root_path
|
| 60 |
+
|
| 61 |
+
self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
|
| 62 |
+
|
| 63 |
+
self.transform = transforms.Compose(
|
| 64 |
+
[
|
| 65 |
+
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 66 |
+
transforms.ToTensor(),
|
| 67 |
+
transforms.Normalize([0.5], [0.5]),
|
| 68 |
+
]
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 72 |
+
|
| 73 |
+
def __getitem__(self, idx):
|
| 74 |
+
item = self.data[idx]
|
| 75 |
+
text = item["text"]
|
| 76 |
+
image_file = item["image_file"]
|
| 77 |
+
|
| 78 |
+
# read image
|
| 79 |
+
raw_image = Image.open(os.path.join(self.image_root_path, image_file))
|
| 80 |
+
|
| 81 |
+
# original size
|
| 82 |
+
original_width, original_height = raw_image.size
|
| 83 |
+
original_size = torch.tensor([original_height, original_width])
|
| 84 |
+
|
| 85 |
+
image_tensor = self.transform(raw_image.convert("RGB"))
|
| 86 |
+
# random crop
|
| 87 |
+
delta_h = image_tensor.shape[1] - self.size
|
| 88 |
+
delta_w = image_tensor.shape[2] - self.size
|
| 89 |
+
assert not all([delta_h, delta_w])
|
| 90 |
+
|
| 91 |
+
if self.center_crop:
|
| 92 |
+
top = delta_h // 2
|
| 93 |
+
left = delta_w // 2
|
| 94 |
+
else:
|
| 95 |
+
top = np.random.randint(0, delta_h + 1)
|
| 96 |
+
left = np.random.randint(0, delta_w + 1)
|
| 97 |
+
image = transforms.functional.crop(image_tensor, top=top, left=left, height=self.size, width=self.size)
|
| 98 |
+
crop_coords_top_left = torch.tensor([top, left])
|
| 99 |
+
|
| 100 |
+
clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
|
| 101 |
+
|
| 102 |
+
# drop
|
| 103 |
+
drop_image_embed = 0
|
| 104 |
+
rand_num = random.random()
|
| 105 |
+
if rand_num < self.i_drop_rate:
|
| 106 |
+
drop_image_embed = 1
|
| 107 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate):
|
| 108 |
+
text = ""
|
| 109 |
+
elif rand_num < (self.i_drop_rate + self.t_drop_rate + self.ti_drop_rate):
|
| 110 |
+
text = ""
|
| 111 |
+
drop_image_embed = 1
|
| 112 |
+
|
| 113 |
+
# get text and tokenize
|
| 114 |
+
text_input_ids = self.tokenizer(
|
| 115 |
+
text,
|
| 116 |
+
max_length=self.tokenizer.model_max_length,
|
| 117 |
+
padding="max_length",
|
| 118 |
+
truncation=True,
|
| 119 |
+
return_tensors="pt",
|
| 120 |
+
).input_ids
|
| 121 |
+
|
| 122 |
+
text_input_ids_2 = self.tokenizer_2(
|
| 123 |
+
text,
|
| 124 |
+
max_length=self.tokenizer_2.model_max_length,
|
| 125 |
+
padding="max_length",
|
| 126 |
+
truncation=True,
|
| 127 |
+
return_tensors="pt",
|
| 128 |
+
).input_ids
|
| 129 |
+
|
| 130 |
+
return {
|
| 131 |
+
"image": image,
|
| 132 |
+
"text_input_ids": text_input_ids,
|
| 133 |
+
"text_input_ids_2": text_input_ids_2,
|
| 134 |
+
"clip_image": clip_image,
|
| 135 |
+
"drop_image_embed": drop_image_embed,
|
| 136 |
+
"original_size": original_size,
|
| 137 |
+
"crop_coords_top_left": crop_coords_top_left,
|
| 138 |
+
"target_size": torch.tensor([self.size, self.size]),
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
def __len__(self):
|
| 142 |
+
return len(self.data)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def collate_fn(data):
|
| 146 |
+
images = torch.stack([example["image"] for example in data])
|
| 147 |
+
text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
|
| 148 |
+
text_input_ids_2 = torch.cat([example["text_input_ids_2"] for example in data], dim=0)
|
| 149 |
+
clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
|
| 150 |
+
drop_image_embeds = [example["drop_image_embed"] for example in data]
|
| 151 |
+
original_size = torch.stack([example["original_size"] for example in data])
|
| 152 |
+
crop_coords_top_left = torch.stack([example["crop_coords_top_left"] for example in data])
|
| 153 |
+
target_size = torch.stack([example["target_size"] for example in data])
|
| 154 |
+
|
| 155 |
+
return {
|
| 156 |
+
"images": images,
|
| 157 |
+
"text_input_ids": text_input_ids,
|
| 158 |
+
"text_input_ids_2": text_input_ids_2,
|
| 159 |
+
"clip_images": clip_images,
|
| 160 |
+
"drop_image_embeds": drop_image_embeds,
|
| 161 |
+
"original_size": original_size,
|
| 162 |
+
"crop_coords_top_left": crop_coords_top_left,
|
| 163 |
+
"target_size": target_size,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class IPAdapter(torch.nn.Module):
|
| 168 |
+
"""IP-Adapter"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, unet, image_proj_model, adapter_modules, ckpt_path=None):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.unet = unet
|
| 173 |
+
self.image_proj_model = image_proj_model
|
| 174 |
+
self.adapter_modules = adapter_modules
|
| 175 |
+
|
| 176 |
+
if ckpt_path is not None:
|
| 177 |
+
self.load_from_checkpoint(ckpt_path)
|
| 178 |
+
|
| 179 |
+
def forward(self, noisy_latents, timesteps, encoder_hidden_states, unet_added_cond_kwargs, image_embeds):
|
| 180 |
+
ip_tokens = self.image_proj_model(image_embeds)
|
| 181 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, ip_tokens], dim=1)
|
| 182 |
+
# Predict the noise residual
|
| 183 |
+
noise_pred = self.unet(
|
| 184 |
+
noisy_latents, timesteps, encoder_hidden_states, added_cond_kwargs=unet_added_cond_kwargs
|
| 185 |
+
).sample
|
| 186 |
+
return noise_pred
|
| 187 |
+
|
| 188 |
+
def load_from_checkpoint(self, ckpt_path: str):
|
| 189 |
+
# Calculate original checksums
|
| 190 |
+
orig_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 191 |
+
orig_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 192 |
+
|
| 193 |
+
state_dict = torch.load(ckpt_path, map_location="cpu")
|
| 194 |
+
|
| 195 |
+
# Load state dict for image_proj_model and adapter_modules
|
| 196 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"], strict=True)
|
| 197 |
+
self.adapter_modules.load_state_dict(state_dict["ip_adapter"], strict=True)
|
| 198 |
+
|
| 199 |
+
# Calculate new checksums
|
| 200 |
+
new_ip_proj_sum = torch.sum(torch.stack([torch.sum(p) for p in self.image_proj_model.parameters()]))
|
| 201 |
+
new_adapter_sum = torch.sum(torch.stack([torch.sum(p) for p in self.adapter_modules.parameters()]))
|
| 202 |
+
|
| 203 |
+
# Verify if the weights have changed
|
| 204 |
+
assert orig_ip_proj_sum != new_ip_proj_sum, "Weights of image_proj_model did not change!"
|
| 205 |
+
assert orig_adapter_sum != new_adapter_sum, "Weights of adapter_modules did not change!"
|
| 206 |
+
|
| 207 |
+
print(f"Successfully loaded weights from checkpoint {ckpt_path}")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def parse_args():
|
| 211 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 212 |
+
parser.add_argument(
|
| 213 |
+
"--pretrained_model_name_or_path",
|
| 214 |
+
type=str,
|
| 215 |
+
default=None,
|
| 216 |
+
required=True,
|
| 217 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--pretrained_ip_adapter_path",
|
| 221 |
+
type=str,
|
| 222 |
+
default=None,
|
| 223 |
+
help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--data_json_file",
|
| 227 |
+
type=str,
|
| 228 |
+
default=None,
|
| 229 |
+
required=True,
|
| 230 |
+
help="Training data",
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--data_root_path",
|
| 234 |
+
type=str,
|
| 235 |
+
default="",
|
| 236 |
+
required=True,
|
| 237 |
+
help="Training data root path",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--image_encoder_path",
|
| 241 |
+
type=str,
|
| 242 |
+
default=None,
|
| 243 |
+
required=True,
|
| 244 |
+
help="Path to CLIP image encoder",
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--output_dir",
|
| 248 |
+
type=str,
|
| 249 |
+
default="sd-ip_adapter",
|
| 250 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 251 |
+
)
|
| 252 |
+
parser.add_argument(
|
| 253 |
+
"--logging_dir",
|
| 254 |
+
type=str,
|
| 255 |
+
default="logs",
|
| 256 |
+
help=(
|
| 257 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 258 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 259 |
+
),
|
| 260 |
+
)
|
| 261 |
+
parser.add_argument(
|
| 262 |
+
"--resolution",
|
| 263 |
+
type=int,
|
| 264 |
+
default=512,
|
| 265 |
+
help=("The resolution for input images"),
|
| 266 |
+
)
|
| 267 |
+
parser.add_argument(
|
| 268 |
+
"--learning_rate",
|
| 269 |
+
type=float,
|
| 270 |
+
default=1e-4,
|
| 271 |
+
help="Learning rate to use.",
|
| 272 |
+
)
|
| 273 |
+
parser.add_argument("--weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 274 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 275 |
+
parser.add_argument(
|
| 276 |
+
"--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
|
| 277 |
+
)
|
| 278 |
+
parser.add_argument("--noise_offset", type=float, default=None, help="noise offset")
|
| 279 |
+
parser.add_argument(
|
| 280 |
+
"--dataloader_num_workers",
|
| 281 |
+
type=int,
|
| 282 |
+
default=0,
|
| 283 |
+
help=(
|
| 284 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 285 |
+
),
|
| 286 |
+
)
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--save_steps",
|
| 289 |
+
type=int,
|
| 290 |
+
default=2000,
|
| 291 |
+
help=("Save a checkpoint of the training state every X updates"),
|
| 292 |
+
)
|
| 293 |
+
parser.add_argument(
|
| 294 |
+
"--mixed_precision",
|
| 295 |
+
type=str,
|
| 296 |
+
default=None,
|
| 297 |
+
choices=["no", "fp16", "bf16"],
|
| 298 |
+
help=(
|
| 299 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 300 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 301 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 302 |
+
),
|
| 303 |
+
)
|
| 304 |
+
parser.add_argument(
|
| 305 |
+
"--report_to",
|
| 306 |
+
type=str,
|
| 307 |
+
default="tensorboard",
|
| 308 |
+
help=(
|
| 309 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 310 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 311 |
+
),
|
| 312 |
+
)
|
| 313 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 314 |
+
|
| 315 |
+
args = parser.parse_args()
|
| 316 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 317 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 318 |
+
args.local_rank = env_local_rank
|
| 319 |
+
|
| 320 |
+
return args
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def main():
|
| 324 |
+
args = parse_args()
|
| 325 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 326 |
+
|
| 327 |
+
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
|
| 328 |
+
|
| 329 |
+
accelerator = Accelerator(
|
| 330 |
+
mixed_precision=args.mixed_precision,
|
| 331 |
+
log_with=args.report_to,
|
| 332 |
+
project_config=accelerator_project_config,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
if accelerator.is_main_process:
|
| 336 |
+
if args.output_dir is not None:
|
| 337 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 338 |
+
|
| 339 |
+
# Load scheduler, tokenizer and models.
|
| 340 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 341 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 342 |
+
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
|
| 343 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer_2")
|
| 344 |
+
text_encoder_2 = CLIPTextModelWithProjection.from_pretrained(
|
| 345 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2"
|
| 346 |
+
)
|
| 347 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
|
| 348 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 349 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
|
| 350 |
+
# freeze parameters of models to save more memory
|
| 351 |
+
unet.requires_grad_(False)
|
| 352 |
+
vae.requires_grad_(False)
|
| 353 |
+
text_encoder.requires_grad_(False)
|
| 354 |
+
text_encoder_2.requires_grad_(False)
|
| 355 |
+
image_encoder.requires_grad_(False)
|
| 356 |
+
|
| 357 |
+
# ip-adapter
|
| 358 |
+
num_tokens = 4
|
| 359 |
+
image_proj_model = ImageProjModel(
|
| 360 |
+
cross_attention_dim=unet.config.cross_attention_dim,
|
| 361 |
+
clip_embeddings_dim=image_encoder.config.projection_dim,
|
| 362 |
+
clip_extra_context_tokens=num_tokens,
|
| 363 |
+
)
|
| 364 |
+
# init adapter modules
|
| 365 |
+
attn_procs = {}
|
| 366 |
+
unet_sd = unet.state_dict()
|
| 367 |
+
for name in unet.attn_processors.keys():
|
| 368 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 369 |
+
if name.startswith("mid_block"):
|
| 370 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 371 |
+
elif name.startswith("up_blocks"):
|
| 372 |
+
block_id = int(name[len("up_blocks.")])
|
| 373 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 374 |
+
elif name.startswith("down_blocks"):
|
| 375 |
+
block_id = int(name[len("down_blocks.")])
|
| 376 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 377 |
+
if cross_attention_dim is None:
|
| 378 |
+
attn_procs[name] = AttnProcessor()
|
| 379 |
+
else:
|
| 380 |
+
layer_name = name.split(".processor")[0]
|
| 381 |
+
weights = {
|
| 382 |
+
"to_k_ip.weight": unet_sd[layer_name + ".to_k.weight"],
|
| 383 |
+
"to_v_ip.weight": unet_sd[layer_name + ".to_v.weight"],
|
| 384 |
+
}
|
| 385 |
+
attn_procs[name] = IPAttnProcessor(
|
| 386 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_tokens=num_tokens
|
| 387 |
+
)
|
| 388 |
+
attn_procs[name].load_state_dict(weights)
|
| 389 |
+
unet.set_attn_processor(attn_procs)
|
| 390 |
+
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
|
| 391 |
+
|
| 392 |
+
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
|
| 393 |
+
|
| 394 |
+
weight_dtype = torch.float32
|
| 395 |
+
if accelerator.mixed_precision == "fp16":
|
| 396 |
+
weight_dtype = torch.float16
|
| 397 |
+
elif accelerator.mixed_precision == "bf16":
|
| 398 |
+
weight_dtype = torch.bfloat16
|
| 399 |
+
# unet.to(accelerator.device, dtype=weight_dtype)
|
| 400 |
+
vae.to(accelerator.device) # use fp32
|
| 401 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 402 |
+
text_encoder_2.to(accelerator.device, dtype=weight_dtype)
|
| 403 |
+
image_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 404 |
+
|
| 405 |
+
# optimizer
|
| 406 |
+
params_to_opt = itertools.chain(ip_adapter.image_proj_model.parameters(), ip_adapter.adapter_modules.parameters())
|
| 407 |
+
optimizer = torch.optim.AdamW(params_to_opt, lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 408 |
+
|
| 409 |
+
# dataloader
|
| 410 |
+
train_dataset = MyDataset(
|
| 411 |
+
args.data_json_file,
|
| 412 |
+
tokenizer=tokenizer,
|
| 413 |
+
tokenizer_2=tokenizer_2,
|
| 414 |
+
size=args.resolution,
|
| 415 |
+
image_root_path=args.data_root_path,
|
| 416 |
+
)
|
| 417 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 418 |
+
train_dataset,
|
| 419 |
+
shuffle=True,
|
| 420 |
+
collate_fn=collate_fn,
|
| 421 |
+
batch_size=args.train_batch_size,
|
| 422 |
+
num_workers=args.dataloader_num_workers,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
# Prepare everything with our `accelerator`.
|
| 426 |
+
ip_adapter, optimizer, train_dataloader = accelerator.prepare(ip_adapter, optimizer, train_dataloader)
|
| 427 |
+
|
| 428 |
+
global_step = 0
|
| 429 |
+
for epoch in range(0, args.num_train_epochs):
|
| 430 |
+
begin = time.perf_counter()
|
| 431 |
+
for step, batch in enumerate(train_dataloader):
|
| 432 |
+
load_data_time = time.perf_counter() - begin
|
| 433 |
+
with accelerator.accumulate(ip_adapter):
|
| 434 |
+
# Convert images to latent space
|
| 435 |
+
with torch.no_grad():
|
| 436 |
+
# vae of sdxl should use fp32
|
| 437 |
+
latents = vae.encode(batch["images"].to(accelerator.device, dtype=vae.dtype)).latent_dist.sample()
|
| 438 |
+
latents = latents * vae.config.scaling_factor
|
| 439 |
+
latents = latents.to(accelerator.device, dtype=weight_dtype)
|
| 440 |
+
|
| 441 |
+
# Sample noise that we'll add to the latents
|
| 442 |
+
noise = torch.randn_like(latents)
|
| 443 |
+
if args.noise_offset:
|
| 444 |
+
# https://www.crosslabs.org//blog/diffusion-with-offset-noise
|
| 445 |
+
noise += args.noise_offset * torch.randn((latents.shape[0], latents.shape[1], 1, 1)).to(
|
| 446 |
+
accelerator.device, dtype=weight_dtype
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
bsz = latents.shape[0]
|
| 450 |
+
# Sample a random timestep for each image
|
| 451 |
+
timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
|
| 452 |
+
timesteps = timesteps.long()
|
| 453 |
+
|
| 454 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 455 |
+
# (this is the forward diffusion process)
|
| 456 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 457 |
+
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
image_embeds = image_encoder(
|
| 460 |
+
batch["clip_images"].to(accelerator.device, dtype=weight_dtype)
|
| 461 |
+
).image_embeds
|
| 462 |
+
image_embeds_ = []
|
| 463 |
+
for image_embed, drop_image_embed in zip(image_embeds, batch["drop_image_embeds"]):
|
| 464 |
+
if drop_image_embed == 1:
|
| 465 |
+
image_embeds_.append(torch.zeros_like(image_embed))
|
| 466 |
+
else:
|
| 467 |
+
image_embeds_.append(image_embed)
|
| 468 |
+
image_embeds = torch.stack(image_embeds_)
|
| 469 |
+
|
| 470 |
+
with torch.no_grad():
|
| 471 |
+
encoder_output = text_encoder(
|
| 472 |
+
batch["text_input_ids"].to(accelerator.device), output_hidden_states=True
|
| 473 |
+
)
|
| 474 |
+
text_embeds = encoder_output.hidden_states[-2]
|
| 475 |
+
encoder_output_2 = text_encoder_2(
|
| 476 |
+
batch["text_input_ids_2"].to(accelerator.device), output_hidden_states=True
|
| 477 |
+
)
|
| 478 |
+
pooled_text_embeds = encoder_output_2[0]
|
| 479 |
+
text_embeds_2 = encoder_output_2.hidden_states[-2]
|
| 480 |
+
text_embeds = torch.concat([text_embeds, text_embeds_2], dim=-1) # concat
|
| 481 |
+
|
| 482 |
+
# add cond
|
| 483 |
+
add_time_ids = [
|
| 484 |
+
batch["original_size"].to(accelerator.device),
|
| 485 |
+
batch["crop_coords_top_left"].to(accelerator.device),
|
| 486 |
+
batch["target_size"].to(accelerator.device),
|
| 487 |
+
]
|
| 488 |
+
add_time_ids = torch.cat(add_time_ids, dim=1).to(accelerator.device, dtype=weight_dtype)
|
| 489 |
+
unet_added_cond_kwargs = {"text_embeds": pooled_text_embeds, "time_ids": add_time_ids}
|
| 490 |
+
|
| 491 |
+
noise_pred = ip_adapter(noisy_latents, timesteps, text_embeds, unet_added_cond_kwargs, image_embeds)
|
| 492 |
+
|
| 493 |
+
loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
|
| 494 |
+
|
| 495 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 496 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean().item()
|
| 497 |
+
|
| 498 |
+
# Backpropagate
|
| 499 |
+
accelerator.backward(loss)
|
| 500 |
+
optimizer.step()
|
| 501 |
+
optimizer.zero_grad()
|
| 502 |
+
|
| 503 |
+
if accelerator.is_main_process:
|
| 504 |
+
print(
|
| 505 |
+
"Epoch {}, step {}, data_time: {}, time: {}, step_loss: {}".format(
|
| 506 |
+
epoch, step, load_data_time, time.perf_counter() - begin, avg_loss
|
| 507 |
+
)
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
global_step += 1
|
| 511 |
+
|
| 512 |
+
if global_step % args.save_steps == 0:
|
| 513 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 514 |
+
accelerator.save_state(save_path)
|
| 515 |
+
|
| 516 |
+
begin = time.perf_counter()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
if __name__ == "__main__":
|
| 520 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/README.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stable Diffusion text-to-image fine-tuning
|
| 2 |
+
This extended LoRA training script was authored by [haofanwang](https://github.com/haofanwang).
|
| 3 |
+
This is an experimental LoRA extension of [this example](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py). We further support add LoRA layers for text encoder.
|
| 4 |
+
|
| 5 |
+
## Training with LoRA
|
| 6 |
+
|
| 7 |
+
Low-Rank Adaption of Large Language Models was first introduced by Microsoft in [LoRA: Low-Rank Adaptation of Large Language Models](https://huggingface.co/papers/2106.09685) by *Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, Weizhu Chen*.
|
| 8 |
+
|
| 9 |
+
In a nutshell, LoRA allows adapting pretrained models by adding pairs of rank-decomposition matrices to existing weights and **only** training those newly added weights. This has a couple of advantages:
|
| 10 |
+
|
| 11 |
+
- Previous pretrained weights are kept frozen so that model is not prone to [catastrophic forgetting](https://www.pnas.org/doi/10.1073/pnas.1611835114).
|
| 12 |
+
- Rank-decomposition matrices have significantly fewer parameters than original model, which means that trained LoRA weights are easily portable.
|
| 13 |
+
- LoRA attention layers allow to control to which extent the model is adapted toward new training images via a `scale` parameter.
|
| 14 |
+
|
| 15 |
+
[cloneofsimo](https://github.com/cloneofsimo) was the first to try out LoRA training for Stable Diffusion in the popular [lora](https://github.com/cloneofsimo/lora) GitHub repository.
|
| 16 |
+
|
| 17 |
+
With LoRA, it's possible to fine-tune Stable Diffusion on a custom image-caption pair dataset
|
| 18 |
+
on consumer GPUs like Tesla T4, Tesla V100.
|
| 19 |
+
|
| 20 |
+
### Training
|
| 21 |
+
|
| 22 |
+
First, you need to set up your development environment as is explained in the [installation section](#installing-the-dependencies). Make sure to set the `MODEL_NAME` and `DATASET_NAME` environment variables. Here, we will use [Stable Diffusion v1-4](https://hf.co/CompVis/stable-diffusion-v1-4) and the [Narutos dataset](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions).
|
| 23 |
+
|
| 24 |
+
**___Note: Change the `resolution` to 768 if you are using the [stable-diffusion-2](https://huggingface.co/stabilityai/stable-diffusion-2) 768x768 model.___**
|
| 25 |
+
|
| 26 |
+
**___Note: It is quite useful to monitor the training progress by regularly generating sample images during training. [Weights and Biases](https://docs.wandb.ai/quickstart) is a nice solution to easily see generating images during training. All you need to do is to run `pip install wandb` before training to automatically log images.___**
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
export MODEL_NAME="CompVis/stable-diffusion-v1-4"
|
| 30 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
For this example we want to directly store the trained LoRA embeddings on the Hub, so
|
| 34 |
+
we need to be logged in and add the `--push_to_hub` flag.
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
hf auth login
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Now we can start training!
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
accelerate launch --mixed_precision="fp16" train_text_to_image_lora.py \
|
| 44 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 45 |
+
--dataset_name=$DATASET_NAME --caption_column="text" \
|
| 46 |
+
--resolution=512 --random_flip \
|
| 47 |
+
--train_batch_size=1 \
|
| 48 |
+
--num_train_epochs=100 --checkpointing_steps=5000 \
|
| 49 |
+
--learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
|
| 50 |
+
--seed=42 \
|
| 51 |
+
--output_dir="sd-naruto-model-lora" \
|
| 52 |
+
--validation_prompt="cute dragon creature" --report_to="wandb"
|
| 53 |
+
--use_peft \
|
| 54 |
+
--lora_r=4 --lora_alpha=32 \
|
| 55 |
+
--lora_text_encoder_r=4 --lora_text_encoder_alpha=32
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
The above command will also run inference as fine-tuning progresses and log the results to Weights and Biases.
|
| 59 |
+
|
| 60 |
+
**___Note: When using LoRA we can use a much higher learning rate compared to non-LoRA fine-tuning. Here we use *1e-4* instead of the usual *1e-5*. Also, by using LoRA, it's possible to run `train_text_to_image_lora.py` in consumer GPUs like T4 or V100.___**
|
| 61 |
+
|
| 62 |
+
The final LoRA embedding weights have been uploaded to [sayakpaul/sd-model-finetuned-lora-t4](https://huggingface.co/sayakpaul/sd-model-finetuned-lora-t4). **___Note: [The final weights](https://huggingface.co/sayakpaul/sd-model-finetuned-lora-t4/blob/main/pytorch_lora_weights.bin) are only 3 MB in size, which is orders of magnitudes smaller than the original model.___**
|
| 63 |
+
|
| 64 |
+
You can check some inference samples that were logged during the course of the fine-tuning process [here](https://wandb.ai/sayakpaul/text2image-fine-tune/runs/q4lc0xsw).
|
| 65 |
+
|
| 66 |
+
### Inference
|
| 67 |
+
|
| 68 |
+
Once you have trained a model using above command, the inference can be done simply using the `StableDiffusionPipeline` after loading the trained LoRA weights. You
|
| 69 |
+
need to pass the `output_dir` for loading the LoRA weights which, in this case, is `sd-naruto-model-lora`.
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
from diffusers import StableDiffusionPipeline
|
| 73 |
+
import torch
|
| 74 |
+
|
| 75 |
+
model_path = "sayakpaul/sd-model-finetuned-lora-t4"
|
| 76 |
+
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16)
|
| 77 |
+
pipe.unet.load_attn_procs(model_path)
|
| 78 |
+
pipe.to("cuda")
|
| 79 |
+
|
| 80 |
+
prompt = "A naruto with green eyes and red legs."
|
| 81 |
+
image = pipe(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
|
| 82 |
+
image.save("naruto.png")
|
| 83 |
+
```
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate>=0.16.0
|
| 2 |
+
torchvision
|
| 3 |
+
transformers>=4.25.1
|
| 4 |
+
datasets
|
| 5 |
+
ftfy
|
| 6 |
+
tensorboard
|
| 7 |
+
Jinja2
|
| 8 |
+
git+https://github.com/huggingface/peft.git
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lora/train_text_to_image_lora.py
ADDED
|
@@ -0,0 +1,1026 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Fine-tuning script for Stable Diffusion for text2image with support for LoRA."""
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import itertools
|
| 19 |
+
import json
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import random
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import datasets
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
import torch.utils.checkpoint
|
| 31 |
+
import transformers
|
| 32 |
+
from accelerate import Accelerator
|
| 33 |
+
from accelerate.logging import get_logger
|
| 34 |
+
from accelerate.utils import ProjectConfiguration, set_seed
|
| 35 |
+
from datasets import load_dataset
|
| 36 |
+
from huggingface_hub import create_repo, upload_folder
|
| 37 |
+
from packaging import version
|
| 38 |
+
from torchvision import transforms
|
| 39 |
+
from tqdm.auto import tqdm
|
| 40 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
| 41 |
+
|
| 42 |
+
import diffusers
|
| 43 |
+
from diffusers import AutoencoderKL, DDPMScheduler, DiffusionPipeline, UNet2DConditionModel
|
| 44 |
+
from diffusers.loaders import AttnProcsLayers
|
| 45 |
+
from diffusers.models.attention_processor import LoRAAttnProcessor
|
| 46 |
+
from diffusers.optimization import get_scheduler
|
| 47 |
+
from diffusers.utils import check_min_version, is_wandb_available
|
| 48 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 52 |
+
check_min_version("0.14.0.dev0")
|
| 53 |
+
|
| 54 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def save_model_card(repo_id: str, images=None, base_model=str, dataset_name=str, repo_folder=None):
|
| 58 |
+
img_str = ""
|
| 59 |
+
for i, image in enumerate(images):
|
| 60 |
+
image.save(os.path.join(repo_folder, f"image_{i}.png"))
|
| 61 |
+
img_str += f"\n"
|
| 62 |
+
|
| 63 |
+
yaml = f"""
|
| 64 |
+
---
|
| 65 |
+
license: creativeml-openrail-m
|
| 66 |
+
base_model: {base_model}
|
| 67 |
+
tags:
|
| 68 |
+
- stable-diffusion
|
| 69 |
+
- stable-diffusion-diffusers
|
| 70 |
+
- text-to-image
|
| 71 |
+
- diffusers
|
| 72 |
+
- diffusers-training
|
| 73 |
+
- lora
|
| 74 |
+
inference: true
|
| 75 |
+
---
|
| 76 |
+
"""
|
| 77 |
+
model_card = f"""
|
| 78 |
+
# LoRA text2image fine-tuning - {repo_id}
|
| 79 |
+
These are LoRA adaption weights for {base_model}. The weights were fine-tuned on the {dataset_name} dataset. You can find some example images in the following. \n
|
| 80 |
+
{img_str}
|
| 81 |
+
"""
|
| 82 |
+
with open(os.path.join(repo_folder, "README.md"), "w") as f:
|
| 83 |
+
f.write(yaml + model_card)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def parse_args():
|
| 87 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
| 88 |
+
parser.add_argument(
|
| 89 |
+
"--pretrained_model_name_or_path",
|
| 90 |
+
type=str,
|
| 91 |
+
default=None,
|
| 92 |
+
required=True,
|
| 93 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--revision",
|
| 97 |
+
type=str,
|
| 98 |
+
default=None,
|
| 99 |
+
required=False,
|
| 100 |
+
help="Revision of pretrained model identifier from huggingface.co/models.",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--dataset_name",
|
| 104 |
+
type=str,
|
| 105 |
+
default=None,
|
| 106 |
+
help=(
|
| 107 |
+
"The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
|
| 108 |
+
" dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
|
| 109 |
+
" or to a folder containing files that 🤗 Datasets can understand."
|
| 110 |
+
),
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--dataset_config_name",
|
| 114 |
+
type=str,
|
| 115 |
+
default=None,
|
| 116 |
+
help="The config of the Dataset, leave as None if there's only one config.",
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--train_data_dir",
|
| 120 |
+
type=str,
|
| 121 |
+
default=None,
|
| 122 |
+
help=(
|
| 123 |
+
"A folder containing the training data. Folder contents must follow the structure described in"
|
| 124 |
+
" https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
|
| 125 |
+
" must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
|
| 126 |
+
),
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--image_column", type=str, default="image", help="The column of the dataset containing an image."
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument(
|
| 132 |
+
"--caption_column",
|
| 133 |
+
type=str,
|
| 134 |
+
default="text",
|
| 135 |
+
help="The column of the dataset containing a caption or a list of captions.",
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--validation_prompt", type=str, default=None, help="A prompt that is sampled during training for inference."
|
| 139 |
+
)
|
| 140 |
+
parser.add_argument(
|
| 141 |
+
"--num_validation_images",
|
| 142 |
+
type=int,
|
| 143 |
+
default=4,
|
| 144 |
+
help="Number of images that should be generated during validation with `validation_prompt`.",
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--validation_epochs",
|
| 148 |
+
type=int,
|
| 149 |
+
default=1,
|
| 150 |
+
help=(
|
| 151 |
+
"Run fine-tuning validation every X epochs. The validation process consists of running the prompt"
|
| 152 |
+
" `args.validation_prompt` multiple times: `args.num_validation_images`."
|
| 153 |
+
),
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument(
|
| 156 |
+
"--max_train_samples",
|
| 157 |
+
type=int,
|
| 158 |
+
default=None,
|
| 159 |
+
help=(
|
| 160 |
+
"For debugging purposes or quicker training, truncate the number of training examples to this "
|
| 161 |
+
"value if set."
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--output_dir",
|
| 166 |
+
type=str,
|
| 167 |
+
default="sd-model-finetuned-lora",
|
| 168 |
+
help="The output directory where the model predictions and checkpoints will be written.",
|
| 169 |
+
)
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--cache_dir",
|
| 172 |
+
type=str,
|
| 173 |
+
default=None,
|
| 174 |
+
help="The directory where the downloaded models and datasets will be stored.",
|
| 175 |
+
)
|
| 176 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 177 |
+
parser.add_argument(
|
| 178 |
+
"--resolution",
|
| 179 |
+
type=int,
|
| 180 |
+
default=512,
|
| 181 |
+
help=(
|
| 182 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
| 183 |
+
" resolution"
|
| 184 |
+
),
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument(
|
| 187 |
+
"--center_crop",
|
| 188 |
+
default=False,
|
| 189 |
+
action="store_true",
|
| 190 |
+
help=(
|
| 191 |
+
"Whether to center crop the input images to the resolution. If not set, the images will be randomly"
|
| 192 |
+
" cropped. The images will be resized to the resolution first before cropping."
|
| 193 |
+
),
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--random_flip",
|
| 197 |
+
action="store_true",
|
| 198 |
+
help="whether to randomly flip images horizontally",
|
| 199 |
+
)
|
| 200 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
|
| 201 |
+
|
| 202 |
+
# lora args
|
| 203 |
+
parser.add_argument("--use_peft", action="store_true", help="Whether to use peft to support lora")
|
| 204 |
+
parser.add_argument("--lora_r", type=int, default=4, help="Lora rank, only used if use_lora is True")
|
| 205 |
+
parser.add_argument("--lora_alpha", type=int, default=32, help="Lora alpha, only used if lora is True")
|
| 206 |
+
parser.add_argument("--lora_dropout", type=float, default=0.0, help="Lora dropout, only used if use_lora is True")
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--lora_bias",
|
| 209 |
+
type=str,
|
| 210 |
+
default="none",
|
| 211 |
+
help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora is True",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--lora_text_encoder_r",
|
| 215 |
+
type=int,
|
| 216 |
+
default=4,
|
| 217 |
+
help="Lora rank for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument(
|
| 220 |
+
"--lora_text_encoder_alpha",
|
| 221 |
+
type=int,
|
| 222 |
+
default=32,
|
| 223 |
+
help="Lora alpha for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--lora_text_encoder_dropout",
|
| 227 |
+
type=float,
|
| 228 |
+
default=0.0,
|
| 229 |
+
help="Lora dropout for text encoder, only used if `use_lora` and `train_text_encoder` are True",
|
| 230 |
+
)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--lora_text_encoder_bias",
|
| 233 |
+
type=str,
|
| 234 |
+
default="none",
|
| 235 |
+
help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora and `train_text_encoder` are True",
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
parser.add_argument(
|
| 239 |
+
"--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
|
| 240 |
+
)
|
| 241 |
+
parser.add_argument("--num_train_epochs", type=int, default=100)
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--max_train_steps",
|
| 244 |
+
type=int,
|
| 245 |
+
default=None,
|
| 246 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 247 |
+
)
|
| 248 |
+
parser.add_argument(
|
| 249 |
+
"--gradient_accumulation_steps",
|
| 250 |
+
type=int,
|
| 251 |
+
default=1,
|
| 252 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 253 |
+
)
|
| 254 |
+
parser.add_argument(
|
| 255 |
+
"--gradient_checkpointing",
|
| 256 |
+
action="store_true",
|
| 257 |
+
help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
|
| 258 |
+
)
|
| 259 |
+
parser.add_argument(
|
| 260 |
+
"--learning_rate",
|
| 261 |
+
type=float,
|
| 262 |
+
default=1e-4,
|
| 263 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 264 |
+
)
|
| 265 |
+
parser.add_argument(
|
| 266 |
+
"--scale_lr",
|
| 267 |
+
action="store_true",
|
| 268 |
+
default=False,
|
| 269 |
+
help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
|
| 270 |
+
)
|
| 271 |
+
parser.add_argument(
|
| 272 |
+
"--lr_scheduler",
|
| 273 |
+
type=str,
|
| 274 |
+
default="constant",
|
| 275 |
+
help=(
|
| 276 |
+
'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
|
| 277 |
+
' "constant", "constant_with_warmup"]'
|
| 278 |
+
),
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
"--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
|
| 282 |
+
)
|
| 283 |
+
parser.add_argument(
|
| 284 |
+
"--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
"--allow_tf32",
|
| 288 |
+
action="store_true",
|
| 289 |
+
help=(
|
| 290 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
| 291 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
| 292 |
+
),
|
| 293 |
+
)
|
| 294 |
+
parser.add_argument(
|
| 295 |
+
"--dataloader_num_workers",
|
| 296 |
+
type=int,
|
| 297 |
+
default=0,
|
| 298 |
+
help=(
|
| 299 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
| 300 |
+
),
|
| 301 |
+
)
|
| 302 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 303 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 304 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 305 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 306 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 307 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 308 |
+
parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"--hub_model_id",
|
| 311 |
+
type=str,
|
| 312 |
+
default=None,
|
| 313 |
+
help="The name of the repository to keep in sync with the local `output_dir`.",
|
| 314 |
+
)
|
| 315 |
+
parser.add_argument(
|
| 316 |
+
"--logging_dir",
|
| 317 |
+
type=str,
|
| 318 |
+
default="logs",
|
| 319 |
+
help=(
|
| 320 |
+
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
|
| 321 |
+
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
|
| 322 |
+
),
|
| 323 |
+
)
|
| 324 |
+
parser.add_argument(
|
| 325 |
+
"--mixed_precision",
|
| 326 |
+
type=str,
|
| 327 |
+
default=None,
|
| 328 |
+
choices=["no", "fp16", "bf16"],
|
| 329 |
+
help=(
|
| 330 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
| 331 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
| 332 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
| 333 |
+
),
|
| 334 |
+
)
|
| 335 |
+
parser.add_argument(
|
| 336 |
+
"--report_to",
|
| 337 |
+
type=str,
|
| 338 |
+
default="tensorboard",
|
| 339 |
+
help=(
|
| 340 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
|
| 341 |
+
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
|
| 342 |
+
),
|
| 343 |
+
)
|
| 344 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 345 |
+
parser.add_argument(
|
| 346 |
+
"--checkpointing_steps",
|
| 347 |
+
type=int,
|
| 348 |
+
default=500,
|
| 349 |
+
help=(
|
| 350 |
+
"Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
|
| 351 |
+
" training using `--resume_from_checkpoint`."
|
| 352 |
+
),
|
| 353 |
+
)
|
| 354 |
+
parser.add_argument(
|
| 355 |
+
"--checkpoints_total_limit",
|
| 356 |
+
type=int,
|
| 357 |
+
default=None,
|
| 358 |
+
help=(
|
| 359 |
+
"Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
|
| 360 |
+
" See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
|
| 361 |
+
" for more docs"
|
| 362 |
+
),
|
| 363 |
+
)
|
| 364 |
+
parser.add_argument(
|
| 365 |
+
"--resume_from_checkpoint",
|
| 366 |
+
type=str,
|
| 367 |
+
default=None,
|
| 368 |
+
help=(
|
| 369 |
+
"Whether training should be resumed from a previous checkpoint. Use a path saved by"
|
| 370 |
+
' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
|
| 371 |
+
),
|
| 372 |
+
)
|
| 373 |
+
parser.add_argument(
|
| 374 |
+
"--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
args = parser.parse_args()
|
| 378 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 379 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 380 |
+
args.local_rank = env_local_rank
|
| 381 |
+
|
| 382 |
+
# Sanity checks
|
| 383 |
+
if args.dataset_name is None and args.train_data_dir is None:
|
| 384 |
+
raise ValueError("Need either a dataset name or a training folder.")
|
| 385 |
+
|
| 386 |
+
return args
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
DATASET_NAME_MAPPING = {
|
| 390 |
+
"lambdalabs/naruto-blip-captions": ("image", "text"),
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def main():
|
| 395 |
+
args = parse_args()
|
| 396 |
+
if args.report_to == "wandb" and args.hub_token is not None:
|
| 397 |
+
raise ValueError(
|
| 398 |
+
"You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
|
| 399 |
+
" Please use `hf auth login` to authenticate with the Hub."
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
logging_dir = os.path.join(args.output_dir, args.logging_dir)
|
| 403 |
+
|
| 404 |
+
accelerator_project_config = ProjectConfiguration(
|
| 405 |
+
total_limit=args.checkpoints_total_limit, project_dir=args.output_dir, logging_dir=logging_dir
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
accelerator = Accelerator(
|
| 409 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 410 |
+
mixed_precision=args.mixed_precision,
|
| 411 |
+
log_with=args.report_to,
|
| 412 |
+
project_config=accelerator_project_config,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
# Disable AMP for MPS.
|
| 416 |
+
if torch.backends.mps.is_available():
|
| 417 |
+
accelerator.native_amp = False
|
| 418 |
+
|
| 419 |
+
if args.report_to == "wandb":
|
| 420 |
+
if not is_wandb_available():
|
| 421 |
+
raise ImportError("Make sure to install wandb if you want to use it for logging during training.")
|
| 422 |
+
import wandb
|
| 423 |
+
|
| 424 |
+
# Make one log on every process with the configuration for debugging.
|
| 425 |
+
logging.basicConfig(
|
| 426 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 427 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 428 |
+
level=logging.INFO,
|
| 429 |
+
)
|
| 430 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 431 |
+
if accelerator.is_local_main_process:
|
| 432 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 433 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 434 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 435 |
+
else:
|
| 436 |
+
datasets.utils.logging.set_verbosity_error()
|
| 437 |
+
transformers.utils.logging.set_verbosity_error()
|
| 438 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 439 |
+
|
| 440 |
+
# If passed along, set the training seed now.
|
| 441 |
+
if args.seed is not None:
|
| 442 |
+
set_seed(args.seed)
|
| 443 |
+
|
| 444 |
+
# Handle the repository creation
|
| 445 |
+
if accelerator.is_main_process:
|
| 446 |
+
if args.output_dir is not None:
|
| 447 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 448 |
+
|
| 449 |
+
if args.push_to_hub:
|
| 450 |
+
repo_id = create_repo(
|
| 451 |
+
repo_id=args.hub_model_id or Path(args.output_dir).name, exist_ok=True, token=args.hub_token
|
| 452 |
+
).repo_id
|
| 453 |
+
|
| 454 |
+
# Load scheduler, tokenizer and models.
|
| 455 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 456 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 457 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
|
| 458 |
+
)
|
| 459 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 460 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 461 |
+
)
|
| 462 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
|
| 463 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 464 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 468 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 469 |
+
weight_dtype = torch.float32
|
| 470 |
+
if accelerator.mixed_precision == "fp16":
|
| 471 |
+
weight_dtype = torch.float16
|
| 472 |
+
elif accelerator.mixed_precision == "bf16":
|
| 473 |
+
weight_dtype = torch.bfloat16
|
| 474 |
+
|
| 475 |
+
if args.use_peft:
|
| 476 |
+
from peft import LoraConfig, LoraModel, get_peft_model_state_dict, set_peft_model_state_dict
|
| 477 |
+
|
| 478 |
+
UNET_TARGET_MODULES = ["to_q", "to_v", "query", "value"]
|
| 479 |
+
TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
|
| 480 |
+
|
| 481 |
+
config = LoraConfig(
|
| 482 |
+
r=args.lora_r,
|
| 483 |
+
lora_alpha=args.lora_alpha,
|
| 484 |
+
target_modules=UNET_TARGET_MODULES,
|
| 485 |
+
lora_dropout=args.lora_dropout,
|
| 486 |
+
bias=args.lora_bias,
|
| 487 |
+
)
|
| 488 |
+
unet = LoraModel(config, unet)
|
| 489 |
+
|
| 490 |
+
vae.requires_grad_(False)
|
| 491 |
+
if args.train_text_encoder:
|
| 492 |
+
config = LoraConfig(
|
| 493 |
+
r=args.lora_text_encoder_r,
|
| 494 |
+
lora_alpha=args.lora_text_encoder_alpha,
|
| 495 |
+
target_modules=TEXT_ENCODER_TARGET_MODULES,
|
| 496 |
+
lora_dropout=args.lora_text_encoder_dropout,
|
| 497 |
+
bias=args.lora_text_encoder_bias,
|
| 498 |
+
)
|
| 499 |
+
text_encoder = LoraModel(config, text_encoder)
|
| 500 |
+
else:
|
| 501 |
+
# freeze parameters of models to save more memory
|
| 502 |
+
unet.requires_grad_(False)
|
| 503 |
+
vae.requires_grad_(False)
|
| 504 |
+
|
| 505 |
+
text_encoder.requires_grad_(False)
|
| 506 |
+
|
| 507 |
+
# now we will add new LoRA weights to the attention layers
|
| 508 |
+
# It's important to realize here how many attention weights will be added and of which sizes
|
| 509 |
+
# The sizes of the attention layers consist only of two different variables:
|
| 510 |
+
# 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`.
|
| 511 |
+
# 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`.
|
| 512 |
+
|
| 513 |
+
# Let's first see how many attention processors we will have to set.
|
| 514 |
+
# For Stable Diffusion, it should be equal to:
|
| 515 |
+
# - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12
|
| 516 |
+
# - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2
|
| 517 |
+
# - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18
|
| 518 |
+
# => 32 layers
|
| 519 |
+
|
| 520 |
+
# Set correct lora layers
|
| 521 |
+
lora_attn_procs = {}
|
| 522 |
+
for name in unet.attn_processors.keys():
|
| 523 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 524 |
+
if name.startswith("mid_block"):
|
| 525 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 526 |
+
elif name.startswith("up_blocks"):
|
| 527 |
+
block_id = int(name[len("up_blocks.")])
|
| 528 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 529 |
+
elif name.startswith("down_blocks"):
|
| 530 |
+
block_id = int(name[len("down_blocks.")])
|
| 531 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 532 |
+
|
| 533 |
+
lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)
|
| 534 |
+
|
| 535 |
+
unet.set_attn_processor(lora_attn_procs)
|
| 536 |
+
lora_layers = AttnProcsLayers(unet.attn_processors)
|
| 537 |
+
|
| 538 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 539 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 540 |
+
if not args.train_text_encoder:
|
| 541 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 542 |
+
|
| 543 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 544 |
+
if is_xformers_available():
|
| 545 |
+
import xformers
|
| 546 |
+
|
| 547 |
+
xformers_version = version.parse(xformers.__version__)
|
| 548 |
+
if xformers_version == version.parse("0.0.16"):
|
| 549 |
+
logger.warning(
|
| 550 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 551 |
+
)
|
| 552 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 553 |
+
else:
|
| 554 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 555 |
+
|
| 556 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 557 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 558 |
+
if args.allow_tf32:
|
| 559 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 560 |
+
|
| 561 |
+
if args.scale_lr:
|
| 562 |
+
args.learning_rate = (
|
| 563 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# Initialize the optimizer
|
| 567 |
+
if args.use_8bit_adam:
|
| 568 |
+
try:
|
| 569 |
+
import bitsandbytes as bnb
|
| 570 |
+
except ImportError:
|
| 571 |
+
raise ImportError(
|
| 572 |
+
"Please install bitsandbytes to use 8-bit Adam. You can do so by running `pip install bitsandbytes`"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
optimizer_cls = bnb.optim.AdamW8bit
|
| 576 |
+
else:
|
| 577 |
+
optimizer_cls = torch.optim.AdamW
|
| 578 |
+
|
| 579 |
+
if args.use_peft:
|
| 580 |
+
# Optimizer creation
|
| 581 |
+
params_to_optimize = (
|
| 582 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 583 |
+
if args.train_text_encoder
|
| 584 |
+
else unet.parameters()
|
| 585 |
+
)
|
| 586 |
+
optimizer = optimizer_cls(
|
| 587 |
+
params_to_optimize,
|
| 588 |
+
lr=args.learning_rate,
|
| 589 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 590 |
+
weight_decay=args.adam_weight_decay,
|
| 591 |
+
eps=args.adam_epsilon,
|
| 592 |
+
)
|
| 593 |
+
else:
|
| 594 |
+
optimizer = optimizer_cls(
|
| 595 |
+
lora_layers.parameters(),
|
| 596 |
+
lr=args.learning_rate,
|
| 597 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 598 |
+
weight_decay=args.adam_weight_decay,
|
| 599 |
+
eps=args.adam_epsilon,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
# Get the datasets: you can either provide your own training and evaluation files (see below)
|
| 603 |
+
# or specify a Dataset from the hub (the dataset will be downloaded automatically from the datasets Hub).
|
| 604 |
+
|
| 605 |
+
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
|
| 606 |
+
# download the dataset.
|
| 607 |
+
if args.dataset_name is not None:
|
| 608 |
+
# Downloading and loading a dataset from the hub.
|
| 609 |
+
dataset = load_dataset(
|
| 610 |
+
args.dataset_name,
|
| 611 |
+
args.dataset_config_name,
|
| 612 |
+
cache_dir=args.cache_dir,
|
| 613 |
+
)
|
| 614 |
+
else:
|
| 615 |
+
data_files = {}
|
| 616 |
+
if args.train_data_dir is not None:
|
| 617 |
+
data_files["train"] = os.path.join(args.train_data_dir, "**")
|
| 618 |
+
dataset = load_dataset(
|
| 619 |
+
"imagefolder",
|
| 620 |
+
data_files=data_files,
|
| 621 |
+
cache_dir=args.cache_dir,
|
| 622 |
+
)
|
| 623 |
+
# See more about loading custom images at
|
| 624 |
+
# https://huggingface.co/docs/datasets/v2.4.0/en/image_load#imagefolder
|
| 625 |
+
|
| 626 |
+
# Preprocessing the datasets.
|
| 627 |
+
# We need to tokenize inputs and targets.
|
| 628 |
+
column_names = dataset["train"].column_names
|
| 629 |
+
|
| 630 |
+
# 6. Get the column names for input/target.
|
| 631 |
+
dataset_columns = DATASET_NAME_MAPPING.get(args.dataset_name, None)
|
| 632 |
+
if args.image_column is None:
|
| 633 |
+
image_column = dataset_columns[0] if dataset_columns is not None else column_names[0]
|
| 634 |
+
else:
|
| 635 |
+
image_column = args.image_column
|
| 636 |
+
if image_column not in column_names:
|
| 637 |
+
raise ValueError(
|
| 638 |
+
f"--image_column' value '{args.image_column}' needs to be one of: {', '.join(column_names)}"
|
| 639 |
+
)
|
| 640 |
+
if args.caption_column is None:
|
| 641 |
+
caption_column = dataset_columns[1] if dataset_columns is not None else column_names[1]
|
| 642 |
+
else:
|
| 643 |
+
caption_column = args.caption_column
|
| 644 |
+
if caption_column not in column_names:
|
| 645 |
+
raise ValueError(
|
| 646 |
+
f"--caption_column' value '{args.caption_column}' needs to be one of: {', '.join(column_names)}"
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
# Preprocessing the datasets.
|
| 650 |
+
# We need to tokenize input captions and transform the images.
|
| 651 |
+
def tokenize_captions(examples, is_train=True):
|
| 652 |
+
captions = []
|
| 653 |
+
for caption in examples[caption_column]:
|
| 654 |
+
if isinstance(caption, str):
|
| 655 |
+
captions.append(caption)
|
| 656 |
+
elif isinstance(caption, (list, np.ndarray)):
|
| 657 |
+
# take a random caption if there are multiple
|
| 658 |
+
captions.append(random.choice(caption) if is_train else caption[0])
|
| 659 |
+
else:
|
| 660 |
+
raise ValueError(
|
| 661 |
+
f"Caption column `{caption_column}` should contain either strings or lists of strings."
|
| 662 |
+
)
|
| 663 |
+
inputs = tokenizer(
|
| 664 |
+
captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
|
| 665 |
+
)
|
| 666 |
+
return inputs.input_ids
|
| 667 |
+
|
| 668 |
+
# Preprocessing the datasets.
|
| 669 |
+
train_transforms = transforms.Compose(
|
| 670 |
+
[
|
| 671 |
+
transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 672 |
+
transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
|
| 673 |
+
transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
|
| 674 |
+
transforms.ToTensor(),
|
| 675 |
+
transforms.Normalize([0.5], [0.5]),
|
| 676 |
+
]
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
def preprocess_train(examples):
|
| 680 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 681 |
+
examples["pixel_values"] = [train_transforms(image) for image in images]
|
| 682 |
+
examples["input_ids"] = tokenize_captions(examples)
|
| 683 |
+
return examples
|
| 684 |
+
|
| 685 |
+
with accelerator.main_process_first():
|
| 686 |
+
if args.max_train_samples is not None:
|
| 687 |
+
dataset["train"] = dataset["train"].shuffle(seed=args.seed).select(range(args.max_train_samples))
|
| 688 |
+
# Set the training transforms
|
| 689 |
+
train_dataset = dataset["train"].with_transform(preprocess_train)
|
| 690 |
+
|
| 691 |
+
def collate_fn(examples):
|
| 692 |
+
pixel_values = torch.stack([example["pixel_values"] for example in examples])
|
| 693 |
+
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
|
| 694 |
+
input_ids = torch.stack([example["input_ids"] for example in examples])
|
| 695 |
+
return {"pixel_values": pixel_values, "input_ids": input_ids}
|
| 696 |
+
|
| 697 |
+
# DataLoaders creation:
|
| 698 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 699 |
+
train_dataset,
|
| 700 |
+
shuffle=True,
|
| 701 |
+
collate_fn=collate_fn,
|
| 702 |
+
batch_size=args.train_batch_size,
|
| 703 |
+
num_workers=args.dataloader_num_workers,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
# Scheduler and math around the number of training steps.
|
| 707 |
+
overrode_max_train_steps = False
|
| 708 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 709 |
+
if args.max_train_steps is None:
|
| 710 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 711 |
+
overrode_max_train_steps = True
|
| 712 |
+
|
| 713 |
+
lr_scheduler = get_scheduler(
|
| 714 |
+
args.lr_scheduler,
|
| 715 |
+
optimizer=optimizer,
|
| 716 |
+
num_warmup_steps=args.lr_warmup_steps * accelerator.num_processes,
|
| 717 |
+
num_training_steps=args.max_train_steps * accelerator.num_processes,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
# Prepare everything with our `accelerator`.
|
| 721 |
+
if args.use_peft:
|
| 722 |
+
if args.train_text_encoder:
|
| 723 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 724 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
| 725 |
+
)
|
| 726 |
+
else:
|
| 727 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 728 |
+
unet, optimizer, train_dataloader, lr_scheduler
|
| 729 |
+
)
|
| 730 |
+
else:
|
| 731 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 732 |
+
lora_layers, optimizer, train_dataloader, lr_scheduler
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 736 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 737 |
+
if overrode_max_train_steps:
|
| 738 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 739 |
+
# Afterwards we recalculate our number of training epochs
|
| 740 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 741 |
+
|
| 742 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 743 |
+
# The trackers initializes automatically on the main process.
|
| 744 |
+
if accelerator.is_main_process:
|
| 745 |
+
accelerator.init_trackers("text2image-fine-tune", config=vars(args))
|
| 746 |
+
|
| 747 |
+
# Train!
|
| 748 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 749 |
+
|
| 750 |
+
logger.info("***** Running training *****")
|
| 751 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 752 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 753 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 754 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 755 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 756 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 757 |
+
global_step = 0
|
| 758 |
+
first_epoch = 0
|
| 759 |
+
|
| 760 |
+
# Potentially load in the weights and states from a previous save
|
| 761 |
+
if args.resume_from_checkpoint:
|
| 762 |
+
if args.resume_from_checkpoint != "latest":
|
| 763 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 764 |
+
else:
|
| 765 |
+
# Get the most recent checkpoint
|
| 766 |
+
dirs = os.listdir(args.output_dir)
|
| 767 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 768 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 769 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 770 |
+
|
| 771 |
+
if path is None:
|
| 772 |
+
accelerator.print(
|
| 773 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 774 |
+
)
|
| 775 |
+
args.resume_from_checkpoint = None
|
| 776 |
+
else:
|
| 777 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 778 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 779 |
+
global_step = int(path.split("-")[1])
|
| 780 |
+
|
| 781 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 782 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 783 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 784 |
+
|
| 785 |
+
# Only show the progress bar once on each machine.
|
| 786 |
+
progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 787 |
+
progress_bar.set_description("Steps")
|
| 788 |
+
|
| 789 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 790 |
+
unet.train()
|
| 791 |
+
if args.train_text_encoder:
|
| 792 |
+
text_encoder.train()
|
| 793 |
+
train_loss = 0.0
|
| 794 |
+
for step, batch in enumerate(train_dataloader):
|
| 795 |
+
# Skip steps until we reach the resumed step
|
| 796 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 797 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 798 |
+
progress_bar.update(1)
|
| 799 |
+
continue
|
| 800 |
+
|
| 801 |
+
with accelerator.accumulate(unet):
|
| 802 |
+
# Convert images to latent space
|
| 803 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 804 |
+
latents = latents * vae.config.scaling_factor
|
| 805 |
+
|
| 806 |
+
# Sample noise that we'll add to the latents
|
| 807 |
+
noise = torch.randn_like(latents)
|
| 808 |
+
bsz = latents.shape[0]
|
| 809 |
+
# Sample a random timestep for each image
|
| 810 |
+
timesteps = torch.randint(0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device)
|
| 811 |
+
timesteps = timesteps.long()
|
| 812 |
+
|
| 813 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 814 |
+
# (this is the forward diffusion process)
|
| 815 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 816 |
+
|
| 817 |
+
# Get the text embedding for conditioning
|
| 818 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 819 |
+
|
| 820 |
+
# Get the target for loss depending on the prediction type
|
| 821 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 822 |
+
target = noise
|
| 823 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 824 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 825 |
+
else:
|
| 826 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 827 |
+
|
| 828 |
+
# Predict the noise residual and compute loss
|
| 829 |
+
model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
| 830 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 831 |
+
|
| 832 |
+
# Gather the losses across all processes for logging (if we use distributed training).
|
| 833 |
+
avg_loss = accelerator.gather(loss.repeat(args.train_batch_size)).mean()
|
| 834 |
+
train_loss += avg_loss.item() / args.gradient_accumulation_steps
|
| 835 |
+
|
| 836 |
+
# Backpropagate
|
| 837 |
+
accelerator.backward(loss)
|
| 838 |
+
if accelerator.sync_gradients:
|
| 839 |
+
if args.use_peft:
|
| 840 |
+
params_to_clip = (
|
| 841 |
+
itertools.chain(unet.parameters(), text_encoder.parameters())
|
| 842 |
+
if args.train_text_encoder
|
| 843 |
+
else unet.parameters()
|
| 844 |
+
)
|
| 845 |
+
else:
|
| 846 |
+
params_to_clip = lora_layers.parameters()
|
| 847 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 848 |
+
optimizer.step()
|
| 849 |
+
lr_scheduler.step()
|
| 850 |
+
optimizer.zero_grad()
|
| 851 |
+
|
| 852 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 853 |
+
if accelerator.sync_gradients:
|
| 854 |
+
progress_bar.update(1)
|
| 855 |
+
global_step += 1
|
| 856 |
+
accelerator.log({"train_loss": train_loss}, step=global_step)
|
| 857 |
+
train_loss = 0.0
|
| 858 |
+
|
| 859 |
+
if global_step % args.checkpointing_steps == 0:
|
| 860 |
+
if accelerator.is_main_process:
|
| 861 |
+
save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 862 |
+
accelerator.save_state(save_path)
|
| 863 |
+
logger.info(f"Saved state to {save_path}")
|
| 864 |
+
|
| 865 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 866 |
+
progress_bar.set_postfix(**logs)
|
| 867 |
+
|
| 868 |
+
if global_step >= args.max_train_steps:
|
| 869 |
+
break
|
| 870 |
+
|
| 871 |
+
if accelerator.is_main_process:
|
| 872 |
+
if args.validation_prompt is not None and epoch % args.validation_epochs == 0:
|
| 873 |
+
logger.info(
|
| 874 |
+
f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
|
| 875 |
+
f" {args.validation_prompt}."
|
| 876 |
+
)
|
| 877 |
+
# create pipeline
|
| 878 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 879 |
+
args.pretrained_model_name_or_path,
|
| 880 |
+
unet=accelerator.unwrap_model(unet),
|
| 881 |
+
text_encoder=accelerator.unwrap_model(text_encoder),
|
| 882 |
+
revision=args.revision,
|
| 883 |
+
torch_dtype=weight_dtype,
|
| 884 |
+
)
|
| 885 |
+
pipeline = pipeline.to(accelerator.device)
|
| 886 |
+
pipeline.set_progress_bar_config(disable=True)
|
| 887 |
+
|
| 888 |
+
# run inference
|
| 889 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 890 |
+
images = []
|
| 891 |
+
for _ in range(args.num_validation_images):
|
| 892 |
+
images.append(
|
| 893 |
+
pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0]
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
if accelerator.is_main_process:
|
| 897 |
+
for tracker in accelerator.trackers:
|
| 898 |
+
if tracker.name == "tensorboard":
|
| 899 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 900 |
+
tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
|
| 901 |
+
if tracker.name == "wandb":
|
| 902 |
+
tracker.log(
|
| 903 |
+
{
|
| 904 |
+
"validation": [
|
| 905 |
+
wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
|
| 906 |
+
for i, image in enumerate(images)
|
| 907 |
+
]
|
| 908 |
+
}
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
del pipeline
|
| 912 |
+
torch.cuda.empty_cache()
|
| 913 |
+
|
| 914 |
+
# Save the lora layers
|
| 915 |
+
accelerator.wait_for_everyone()
|
| 916 |
+
if accelerator.is_main_process:
|
| 917 |
+
if args.use_peft:
|
| 918 |
+
lora_config = {}
|
| 919 |
+
unwarpped_unet = accelerator.unwrap_model(unet)
|
| 920 |
+
state_dict = get_peft_model_state_dict(unwarpped_unet, state_dict=accelerator.get_state_dict(unet))
|
| 921 |
+
lora_config["peft_config"] = unwarpped_unet.get_peft_config_as_dict(inference=True)
|
| 922 |
+
if args.train_text_encoder:
|
| 923 |
+
unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
|
| 924 |
+
text_encoder_state_dict = get_peft_model_state_dict(
|
| 925 |
+
unwarpped_text_encoder, state_dict=accelerator.get_state_dict(text_encoder)
|
| 926 |
+
)
|
| 927 |
+
text_encoder_state_dict = {f"text_encoder_{k}": v for k, v in text_encoder_state_dict.items()}
|
| 928 |
+
state_dict.update(text_encoder_state_dict)
|
| 929 |
+
lora_config["text_encoder_peft_config"] = unwarpped_text_encoder.get_peft_config_as_dict(
|
| 930 |
+
inference=True
|
| 931 |
+
)
|
| 932 |
+
|
| 933 |
+
accelerator.save(state_dict, os.path.join(args.output_dir, f"{global_step}_lora.pt"))
|
| 934 |
+
with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "w") as f:
|
| 935 |
+
json.dump(lora_config, f)
|
| 936 |
+
else:
|
| 937 |
+
unet = unet.to(torch.float32)
|
| 938 |
+
unet.save_attn_procs(args.output_dir)
|
| 939 |
+
|
| 940 |
+
if args.push_to_hub:
|
| 941 |
+
save_model_card(
|
| 942 |
+
repo_id,
|
| 943 |
+
images=images,
|
| 944 |
+
base_model=args.pretrained_model_name_or_path,
|
| 945 |
+
dataset_name=args.dataset_name,
|
| 946 |
+
repo_folder=args.output_dir,
|
| 947 |
+
)
|
| 948 |
+
upload_folder(
|
| 949 |
+
repo_id=repo_id,
|
| 950 |
+
folder_path=args.output_dir,
|
| 951 |
+
commit_message="End of training",
|
| 952 |
+
ignore_patterns=["step_*", "epoch_*"],
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
# Final inference
|
| 956 |
+
# Load previous pipeline
|
| 957 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 958 |
+
args.pretrained_model_name_or_path, revision=args.revision, torch_dtype=weight_dtype
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
if args.use_peft:
|
| 962 |
+
|
| 963 |
+
def load_and_set_lora_ckpt(pipe, ckpt_dir, global_step, device, dtype):
|
| 964 |
+
with open(os.path.join(args.output_dir, f"{global_step}_lora_config.json"), "r") as f:
|
| 965 |
+
lora_config = json.load(f)
|
| 966 |
+
print(lora_config)
|
| 967 |
+
|
| 968 |
+
checkpoint = os.path.join(args.output_dir, f"{global_step}_lora.pt")
|
| 969 |
+
lora_checkpoint_sd = torch.load(checkpoint)
|
| 970 |
+
unet_lora_ds = {k: v for k, v in lora_checkpoint_sd.items() if "text_encoder_" not in k}
|
| 971 |
+
text_encoder_lora_ds = {
|
| 972 |
+
k.replace("text_encoder_", ""): v for k, v in lora_checkpoint_sd.items() if "text_encoder_" in k
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
unet_config = LoraConfig(**lora_config["peft_config"])
|
| 976 |
+
pipe.unet = LoraModel(unet_config, pipe.unet)
|
| 977 |
+
set_peft_model_state_dict(pipe.unet, unet_lora_ds)
|
| 978 |
+
|
| 979 |
+
if "text_encoder_peft_config" in lora_config:
|
| 980 |
+
text_encoder_config = LoraConfig(**lora_config["text_encoder_peft_config"])
|
| 981 |
+
pipe.text_encoder = LoraModel(text_encoder_config, pipe.text_encoder)
|
| 982 |
+
set_peft_model_state_dict(pipe.text_encoder, text_encoder_lora_ds)
|
| 983 |
+
|
| 984 |
+
if dtype in (torch.float16, torch.bfloat16):
|
| 985 |
+
pipe.unet.half()
|
| 986 |
+
pipe.text_encoder.half()
|
| 987 |
+
|
| 988 |
+
pipe.to(device)
|
| 989 |
+
return pipe
|
| 990 |
+
|
| 991 |
+
pipeline = load_and_set_lora_ckpt(pipeline, args.output_dir, global_step, accelerator.device, weight_dtype)
|
| 992 |
+
|
| 993 |
+
else:
|
| 994 |
+
pipeline = pipeline.to(accelerator.device)
|
| 995 |
+
# load attention processors
|
| 996 |
+
pipeline.unet.load_attn_procs(args.output_dir)
|
| 997 |
+
|
| 998 |
+
# run inference
|
| 999 |
+
if args.seed is not None:
|
| 1000 |
+
generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
|
| 1001 |
+
else:
|
| 1002 |
+
generator = None
|
| 1003 |
+
images = []
|
| 1004 |
+
for _ in range(args.num_validation_images):
|
| 1005 |
+
images.append(pipeline(args.validation_prompt, num_inference_steps=30, generator=generator).images[0])
|
| 1006 |
+
|
| 1007 |
+
if accelerator.is_main_process:
|
| 1008 |
+
for tracker in accelerator.trackers:
|
| 1009 |
+
if tracker.name == "tensorboard":
|
| 1010 |
+
np_images = np.stack([np.asarray(img) for img in images])
|
| 1011 |
+
tracker.writer.add_images("test", np_images, epoch, dataformats="NHWC")
|
| 1012 |
+
if tracker.name == "wandb":
|
| 1013 |
+
tracker.log(
|
| 1014 |
+
{
|
| 1015 |
+
"test": [
|
| 1016 |
+
wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
|
| 1017 |
+
for i, image in enumerate(images)
|
| 1018 |
+
]
|
| 1019 |
+
}
|
| 1020 |
+
)
|
| 1021 |
+
|
| 1022 |
+
accelerator.end_training()
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
if __name__ == "__main__":
|
| 1026 |
+
main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/examples/research_projects/lpl/README.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Latent Perceptual Loss (LPL) for Stable Diffusion XL
|
| 2 |
+
|
| 3 |
+
This directory contains an implementation of Latent Perceptual Loss (LPL) for training Stable Diffusion XL models, based on the paper: [Boosting Latent Diffusion with Perceptual Objectives](https://huggingface.co/papers/2411.04873) (Berrada et al., 2025). LPL is a perceptual loss that operates in the latent space of a VAE, helping to improve the quality and consistency of generated images by bridging the disconnect between the diffusion model and the autoencoder decoder. The implementation is based on the reference implementation provided by Tariq Berrada.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
LPL addresses a key limitation in latent diffusion models (LDMs): the disconnect between the diffusion model training and the autoencoder decoder. While LDMs train in the latent space, they don't receive direct feedback about how well their outputs decode into high-quality images. This can lead to:
|
| 8 |
+
|
| 9 |
+
- Loss of fine details in generated images
|
| 10 |
+
- Inconsistent image quality
|
| 11 |
+
- Structural artifacts
|
| 12 |
+
- Reduced sharpness and realism
|
| 13 |
+
|
| 14 |
+
LPL works by comparing intermediate features from the VAE decoder between the predicted and target latents. This helps the model learn better perceptual features and can lead to:
|
| 15 |
+
|
| 16 |
+
- Improved image quality and consistency (6-20% FID improvement)
|
| 17 |
+
- Better preservation of fine details
|
| 18 |
+
- More stable training, especially at high noise levels
|
| 19 |
+
- Better handling of structural information
|
| 20 |
+
- Sharper and more realistic textures
|
| 21 |
+
|
| 22 |
+
## Implementation Details
|
| 23 |
+
|
| 24 |
+
The LPL implementation follows the paper's methodology and includes several key features:
|
| 25 |
+
|
| 26 |
+
1. **Feature Extraction**: Extracts intermediate features from the VAE decoder, including:
|
| 27 |
+
- Middle block features
|
| 28 |
+
- Up block features (configurable number of blocks)
|
| 29 |
+
- Proper gradient checkpointing for memory efficiency
|
| 30 |
+
- Features are extracted only for timesteps below the threshold (high SNR)
|
| 31 |
+
|
| 32 |
+
2. **Feature Normalization**: Multiple normalization options as validated in the paper:
|
| 33 |
+
- `default`: Normalize each feature map independently
|
| 34 |
+
- `shared`: Cross-normalize features using target statistics (recommended)
|
| 35 |
+
- `batch`: Batch-wise normalization
|
| 36 |
+
|
| 37 |
+
3. **Outlier Handling**: Optional removal of outliers in feature maps using:
|
| 38 |
+
- Quantile-based filtering (2% quantiles)
|
| 39 |
+
- Morphological operations (opening/closing)
|
| 40 |
+
- Adaptive thresholding based on standard deviation
|
| 41 |
+
|
| 42 |
+
4. **Loss Types**:
|
| 43 |
+
- MSE loss (default)
|
| 44 |
+
- L1 loss
|
| 45 |
+
- Optional power law weighting (2^(-i) for layer i)
|
| 46 |
+
|
| 47 |
+
## Usage
|
| 48 |
+
|
| 49 |
+
To use LPL in your training, add the following arguments to your training command:
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
python examples/research_projects/lpl/train_sdxl_lpl.py \
|
| 53 |
+
--use_lpl \
|
| 54 |
+
--lpl_weight 1.0 \ # Weight for LPL loss (1.0-2.0 recommended)
|
| 55 |
+
--lpl_t_threshold 200 \ # Apply LPL only for timesteps < threshold (high SNR)
|
| 56 |
+
--lpl_loss_type mse \ # Loss type: "mse" or "l1"
|
| 57 |
+
--lpl_norm_type shared \ # Normalization type: "default", "shared" (recommended), or "batch"
|
| 58 |
+
--lpl_pow_law \ # Use power law weighting for layers
|
| 59 |
+
--lpl_num_blocks 4 \ # Number of up blocks to use (1-4)
|
| 60 |
+
--lpl_remove_outliers \ # Remove outliers in feature maps
|
| 61 |
+
--lpl_scale \ # Scale LPL loss by noise level weights
|
| 62 |
+
--lpl_start 0 \ # Step to start applying LPL
|
| 63 |
+
# ... other training arguments ...
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
### Key Parameters
|
| 67 |
+
|
| 68 |
+
- `lpl_weight`: Controls the strength of the LPL loss relative to the main diffusion loss. Higher values (1.0-2.0) improve quality but may slow training.
|
| 69 |
+
- `lpl_t_threshold`: LPL is only applied for timesteps below this threshold (high SNR). Lower values (100-200) focus on more important timesteps.
|
| 70 |
+
- `lpl_loss_type`: Choose between MSE (default) and L1 loss. MSE is recommended for most cases.
|
| 71 |
+
- `lpl_norm_type`: Feature normalization strategy. "shared" is recommended as it showed best results in the paper.
|
| 72 |
+
- `lpl_pow_law`: Whether to use power law weighting (2^(-i) for layer i). Recommended for better feature balance.
|
| 73 |
+
- `lpl_num_blocks`: Number of up blocks to use for feature extraction (1-4). More blocks capture more features but use more memory.
|
| 74 |
+
- `lpl_remove_outliers`: Whether to remove outliers in feature maps. Recommended for stable training.
|
| 75 |
+
- `lpl_scale`: Whether to scale LPL loss by noise level weights. Helps focus on more important timesteps.
|
| 76 |
+
- `lpl_start`: Training step to start applying LPL. Can be used to warm up training.
|
| 77 |
+
|
| 78 |
+
## Recommendations
|
| 79 |
+
|
| 80 |
+
1. **Starting Point** (based on paper results):
|
| 81 |
+
```bash
|
| 82 |
+
--use_lpl \
|
| 83 |
+
--lpl_weight 1.0 \
|
| 84 |
+
--lpl_t_threshold 200 \
|
| 85 |
+
--lpl_loss_type mse \
|
| 86 |
+
--lpl_norm_type shared \
|
| 87 |
+
--lpl_pow_law \
|
| 88 |
+
--lpl_num_blocks 4 \
|
| 89 |
+
--lpl_remove_outliers \
|
| 90 |
+
--lpl_scale
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
2. **Memory Efficiency**:
|
| 94 |
+
- Use `--gradient_checkpointing` for memory efficiency (enabled by default)
|
| 95 |
+
- Reduce `lpl_num_blocks` if memory is constrained (2-3 blocks still give good results)
|
| 96 |
+
- Consider using `--lpl_scale` to focus on more important timesteps
|
| 97 |
+
- Features are extracted only for timesteps below threshold to save memory
|
| 98 |
+
|
| 99 |
+
3. **Quality vs Speed**:
|
| 100 |
+
- Higher `lpl_weight` (1.0-2.0) for better quality
|
| 101 |
+
- Lower `lpl_t_threshold` (100-200) for faster training
|
| 102 |
+
- Use `lpl_remove_outliers` for more stable training
|
| 103 |
+
- `lpl_norm_type shared` provides best quality/speed trade-off
|
| 104 |
+
|
| 105 |
+
## Technical Details
|
| 106 |
+
|
| 107 |
+
### Feature Extraction
|
| 108 |
+
|
| 109 |
+
The LPL implementation extracts features from the VAE decoder in the following order:
|
| 110 |
+
1. Middle block output
|
| 111 |
+
2. Up block outputs (configurable number of blocks)
|
| 112 |
+
|
| 113 |
+
Each feature map is processed with:
|
| 114 |
+
1. Optional outlier removal (2% quantiles, morphological operations)
|
| 115 |
+
2. Feature normalization (shared statistics recommended)
|
| 116 |
+
3. Loss calculation (MSE or L1)
|
| 117 |
+
4. Optional power law weighting (2^(-i) for layer i)
|
| 118 |
+
|
| 119 |
+
### Loss Calculation
|
| 120 |
+
|
| 121 |
+
For each feature map:
|
| 122 |
+
1. Features are normalized according to the chosen strategy
|
| 123 |
+
2. Loss is calculated between normalized features
|
| 124 |
+
3. Outliers are masked out (if enabled)
|
| 125 |
+
4. Loss is weighted by layer depth (if power law enabled)
|
| 126 |
+
5. Final loss is averaged across all layers
|
| 127 |
+
|
| 128 |
+
### Memory Considerations
|
| 129 |
+
|
| 130 |
+
- Gradient checkpointing is used by default
|
| 131 |
+
- Features are extracted only for timesteps below the threshold
|
| 132 |
+
- Outlier removal is done in-place to save memory
|
| 133 |
+
- Feature normalization is done efficiently using vectorized operations
|
| 134 |
+
- Memory usage scales linearly with number of blocks used
|
| 135 |
+
|
| 136 |
+
## Results
|
| 137 |
+
|
| 138 |
+
Based on the paper's findings, LPL provides:
|
| 139 |
+
- 6-20% improvement in FID scores
|
| 140 |
+
- Better preservation of fine details
|
| 141 |
+
- More realistic textures and structures
|
| 142 |
+
- Improved consistency across different resolutions
|
| 143 |
+
- Better performance on both small and large datasets
|
| 144 |
+
|
| 145 |
+
## Citation
|
| 146 |
+
|
| 147 |
+
If you use this implementation in your research, please cite:
|
| 148 |
+
|
| 149 |
+
```bibtex
|
| 150 |
+
@inproceedings{berrada2025boosting,
|
| 151 |
+
title={Boosting Latent Diffusion with Perceptual Objectives},
|
| 152 |
+
author={Tariq Berrada and Pietro Astolfi and Melissa Hall and Marton Havasi and Yohann Benchetrit and Adriana Romero-Soriano and Karteek Alahari and Michal Drozdzal and Jakob Verbeek},
|
| 153 |
+
booktitle={The Thirteenth International Conference on Learning Representations},
|
| 154 |
+
year={2025},
|
| 155 |
+
url={https://openreview.net/forum?id=y4DtzADzd1}
|
| 156 |
+
}
|
| 157 |
+
```
|