Write me a code for finetuning of stable diffusion 1.5 with ip adapter on images dataset. Finetune only ip-adapter. Implement ip-adapter model here. IP adapter checkpoint, sd checkpoint image projection model and vae will be loaded from hard drive. Dont implement IP-adapter code, import it
Assistant
User
Remove arguments, define every parameter inside of script
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import os
import random
import argparse
from pathlib import Path
import json
import itertools
import time
import torch
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
from transformers import CLIPImageProcessor
from accelerate import Accelerator
from accelerate.utils import ProjectConfiguration
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
from ip_adapter.ip_adapter import ImageProjModel, IPAdapter # Import IPAdapter
def parse_args():
parser = argparse.ArgumentParser(description="Finetuning SD1.5 with IP-Adapter")
parser.add_argument(
"--pretrained_model_name_or_path",
type=str,
required=True,
help="Path to pretrained SD1.5 model",
)
parser.add_argument(
"--pretrained_ip_adapter_path",
type=str,
required=True,
help="Path to pretrained IP-Adapter checkpoint",
)
parser.add_argument(
"--data_json_file",
type=str,
required=True,
help="Path to JSON file with image paths and captions",
)
parser.add_argument(
"--data_root_path",
type=str,
default="",
help="Root path for images in the JSON file",
)
parser.add_argument(
"--image_encoder_path",
type=str,
required=True,
help="Path to CLIP image encoder",
)
parser.add_argument(
"--output_dir",
type=str,
default="sd-ip_adapter-finetuned",
help="Output directory for checkpoints",
)
# ... other arguments like learning rate, batch size, epochs, etc.
return parser.parse_args()
# Dataset and collate_fn remain the same as in the original code
class MyDataset(torch.utils.data.Dataset):
# ... (same as in original code)
def collate_fn(data):
# ... (same as in original code)
def main():
args = parse_args()
# ... (Accelerator setup remains the same)
# Load models
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="text_encoder")
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae")
unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
# Freeze pretrained models
unet.requires_grad_(False)
vae.requires_grad_(False)
text_encoder.requires_grad_(False)
image_encoder.requires_grad_(False)
# Initialize IP-Adapter components
image_proj_model = ImageProjModel(
cross_attention_dim=unet.config.cross_attention_dim,
clip_embeddings_dim=image_encoder.config.projection_dim,
clip_extra_context_tokens=4, # Adjust if needed
)
# Initialize adapter modules (same as original code)
attn_procs = {}
# ... (rest of the attn_procs initialization)
unet.set_attn_processor(attn_procs)
adapter_modules = torch.nn.ModuleList(unet.attn_processors.values())
# Load pretrained IP-Adapter
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, args.pretrained_ip_adapter_path)
# ... (rest of the code remains largely the same, including optimizer, dataloader,
# accelerator preparation, training loop, and saving checkpoints)
if __name__ == "__main__":
main()
Key changes:
Import IPAdapter: Import the IPAdapter class directly.
Initialization: Initialize the image_proj_model and LoRA layers. The number of extra context tokens (4 in this example) can be adjusted as needed.
Loading Checkpoint: Instantiate IPAdapter and load the pretrained weights using the provided path.
Freezing: Freeze the unet, vae, text_encoder, and image_encoder to finetune only the IP-Adapter.
Training Loop: The training loop remains almost identical, with minor adjustments as needed for any new arguments or hyperparameters you've added. Ensure the loss calculation and backpropagation are only applied to the IP-Adapter's parameters.
python
import os
import random
import json
import itertools
import time
import torch
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
from transformers import CLIPImageProcessor
from accelerate import Accelerator
from accelerate.utils import ProjectConfiguration
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
from ip_adapter.ip_adapter import ImageProjModel, IPAdapter # Import IPAdapter
# Define parameters within the script
pretrained_model_name_or_path = "CompVis/stable-diffusion-v1-4" # Path to pretrained SD1.5 model
pretrained_ip_adapter_path = "path/to/your/ip_adapter_checkpoint.pt" # Path to pretrained IP-Adapter checkpoint
data_json_file = "path/to/your/data.json" # Path to JSON file with image paths and captions
data_root_path = "" # Root path for images in the JSON file if needed
image_encoder_path = "openai/clip-vit-large-patch14" # Path to CLIP image encoder
output_dir = "sd-ip_adapter-finetuned" # Output directory for checkpoints
learning_rate = 1e-4 # Learning rate
weight_decay = 1e-2 # Weight decay
num_train_epochs = 100 # Number of training epochs
train_batch_size = 8 # Training batch size
dataloader_num_workers = 0 # Number of dataloader workers
save_steps = 2000 # Save checkpoint every X steps
mixed_precision = "fp16" # Mixed precision mode ("no", "fp16", "bf16")
report_to = "tensorboard" # Report to tensorboard
resolution = 512 # image resolution
# ... other parameters as needed
# Dataset and collate_fn remain the same
class MyDataset(torch.utils.data.Dataset):
# ... (same as in original code, but use the parameters defined above)
def collate_fn(data):
# ... (same as in original code)
def main():
logging_dir = Path(output_dir, "logs")
accelerator_project_config = ProjectConfiguration(project_dir=output_dir, logging_dir=logging_dir)
accelerator = Accelerator(
mixed_precision=mixed_precision,
log_with=report_to,
project_config=accelerator_project_config,
)
if accelerator.is_main_process:
if output_dir is not None:
os.makedirs(output_dir, exist_ok=True)
# Load models (use the defined parameters)
noise_scheduler = DDPMScheduler.from_pretrained(pretrained_model_name_or_path, subfolder="scheduler")
tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_name_or_path, subfolder="tokenizer")
text_encoder = CLIPTextModel.from_pretrained(pretrained_model_name_or_path, subfolder="text_encoder")
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
unet = UNet2DConditionModel.from_pretrained(pretrained_model_name_or_path, subfolder="unet")
image_encoder = CLIPVisionModelWithProjection.from_pretrained(image_encoder_path)
# Freeze pretrained models
# ... (same as before)
# Initialize IP-Adapter components (using the defined parameters)
image_proj_model = ImageProjModel(
cross_attention_dim=unet.config.cross_attention_dim,
clip_embeddings_dim=image_encoder.config.projection_dim,
clip_extra_context_tokens=4, # Or any other value you need
)
# ... (attn_procs and adapter_modules initialization)
ip_adapter = IPAdapter(unet, image_proj_model, adapter_modules, pretrained_ip_adapter_path)
# ... (Optimizer, dataloader, accelerator preparation, training loop, saving)
if __name__ == "__main__":
main()
Key changes:
Removed parse_args(): All arguments are now defined as variables within the script.
Parameter Definitions: All necessary parameters like paths, learning rate, batch size, etc., are defined directly in the script.
Dataset and Training Loop: The MyDataset class and the training loop now reference these in-script parameters instead of relying on args.
Now you can run this script directly without command-line arguments. Just modify the parameter values at the beginning of the script to suit your needs.