python Copy code
import os
import argparse
from pathlib import Path
import json
import time
from typing import List
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.logging import get_logger
from accelerate.utils import ProjectConfiguration
from diffusers import AutoencoderKL, DDPMScheduler, UNet2DConditionModel
from transformers import CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
from safetensors import safe_open
from ip_adapter.ip_adapter import IPAdapter, ImageProjModel
from ip_adapter.utils import is_torch2_available, get_generator
if is_torch2_available():
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
else:
from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessor
# Dataset
class MyDataset(torch.utils.data.Dataset):
def __init__(self, json_file, tokenizer, size=512, image_root_path=""):
super().__init__()
self.tokenizer = tokenizer
self.size = size
self.image_root_path = image_root_path
self.data = json.load(open(json_file)) # list of dict: [{"image_file": "1.png", "text": "A dog"}]
self.transform = transforms.Compose([
transforms.Resize(self.size, interpolation=transforms.InterpolationMode.BILINEAR),
transforms.CenterCrop(self.size),
transforms.ToTensor(),
transforms.Normalize([0.5], [0.5]),
])
self.clip_image_processor = CLIPImageProcessor()
def __getitem__(self, idx):
item = self.data[idx]
text = item["text"]
image_file = item["image_file"]
# read image
raw_image = Image.open(os.path.join(self.image_root_path, image_file))
image = self.transform(raw_image.convert("RGB"))
clip_image = self.clip_image_processor(images=raw_image, return_tensors="pt").pixel_values
# get text and tokenize
text_input_ids = self.tokenizer(
text,
max_length=self.tokenizer.model_max_length,
padding="max_length",
truncation=True,
return_tensors="pt"
).input_ids
return {
"image": image,
"text_input_ids": text_input_ids,
"clip_image": clip_image,
}
def __len__(self):
return len(self.data)
def collate_fn(data):
images = torch.stack([example["image"] for example in data])
text_input_ids = torch.cat([example["text_input_ids"] for example in data], dim=0)
clip_images = torch.cat([example["clip_image"] for example in data], dim=0)
return {
"images": images,
"text_input_ids": text_input_ids,
"clip_images": clip_images,
}
def parse_args():
parser = argparse.ArgumentParser(description="Simple example of a training script.")
parser.add_argument(
"--pretrained_model_name_or_path",
type=str,
default=None,
required=True,
help="Path to pretrained model or model identifier from huggingface.co/models.",
)
parser.add_argument(
"--pretrained_ip_adapter_path",
type=str,
default=None,
required=True,
help="Path to pretrained ip adapter model. If not specified weights are initialized randomly.",
)
parser.add_argument(
"--image_proj_model_path",
type=str,
default=None,
required=True,
help="Path to image projection model.",
)
parser.add_argument(
"--[Redacted Person]",
type=str,
default=None,
required=True,
help="Path to vae.",
)
parser.add_argument(
"--unet_config_file",
type=str,
default=None,
required=True,
help="Path to unet config file.",
)
parser.add_argument(
"--vae_config_file",
type=str,
default=None,
required=True,
help="Path to vae config file.",
)
parser.add_argument(
"--data_json_file",
type=str,
default=None,
required=True,
help="Training data",
)
parser.add_argument(
"--data_root_path",
type=str,
default="",
required=True,
help="Training data root path",
)
parser.add_argument(
"--image_encoder_path",
type=str,
default=None,
required=True,
help="Path to CLIP image encoder",
)
parser.add_argument(
"--output_dir",
type=str,
default="sd-ip_adapter",
help="The output directory where the model predictions and checkpoints will be written.",
)
parser.add_argument(
"--logging_dir",
type=str,
default="logs",
help=(
"[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
" *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
),
)
parser.add_argument(
"--resolution",
type=int,
default=512,
help=(
"The resolution for input images"
),
)
parser.add_argument(
"--train_batch_size", type=int, default=8, help="Batch size (per device) for the training dataloader."
)
parser.add_argument(
"--dataloader_num_workers",
type=int,
default=0,
help=(
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
),
)
parser.add_argument(
"--mixed_precision",
type=str,
default=None,
choices=["no", "fp16", "bf16"],
help=(
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
),
)
parser.add_argument(
"--report_to",
type=str,
default="tensorboard",
help=(
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
),
)
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
parser.add_argument(
"--num_samples",
type=int,
default=4,
help="Number of images to generate per prompt.",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="A seed for reproducible generation.",
)
parser.add_argument(
"--guidance_scale",
type=float,
default=7.5,
help="Guidance scale as defined in Classifier-Free Diffusion Guidance.",
)
parser.add_argument(
"--num_inference_steps",
type=int,
default=30,
help="The number of denoising steps.",
)
parser.add_argument(
"--scale",
type=float,
default=1.0,
help="The scale of the image prompt.",
)
args = parser.parse_args()
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
if env_local_rank != -1 and env_local_rank != args.local_rank:
args.local_rank = env_local_rank
return args
def main():
args = parse_args()
logging_dir = Path(args.output_dir, args.logging_dir)
accelerator_project_config = ProjectConfiguration(project_dir=args.output_dir, logging_dir=logging_dir)
accelerator = Accelerator(
mixed_precision=args.mixed_precision,
log_with=args.report_to,
project_config=accelerator_project_config,
)
if accelerator.is_main_process:
if args.output_dir is not None:
os.makedirs(args.output_dir, exist_ok=True)
# Load scheduler, tokenizer and 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")
with open(args.unet_config_file, 'r') as f:
unet_config = json.load(f)
unet = UNet2DConditionModel(**unet_config)
with open(args.vae_config_file, 'r') as f:
vae_config = json.load(f)
vae = AutoencoderKL(**vae_config)
image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)
# freeze parameters of models to save more memory
unet.requires_grad_(False)
vae.requires_grad_(False)
text_encoder.requires_grad_(False)
image_encoder.requires_grad_(False)
#ip-adapter
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,
)
# init adapter modules
attn_procs = {}
unet_sd = unet.state_dict()
for name in unet.attn_processors.keys():
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
if name.startswith("mid_block"):
hidden_size = unet.config.block_out_channels[-1]
[Redacted Person] name.startswith("up_blocks"):
block_id = int(name[len("up_blocks.")])
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
[Redacted Person] name.startswith("down_blocks"):
block_id = int(name[len("down_blocks.")])
hidden_size = unet.config.block_out_channels[block_id]
if cross_attention_dim is None:
attn_procs[name] = AttnProcessor()
else:
attn_procs[name] = IPAttnProcessor(
hidden_size=hidden_size,
cross_attention_dim=cross_attention_dim,
scale=1.0,
num_tokens=4,
)
unet.set_attn_processor(attn_procs)
ip_adapter = IPAdapter(
sd_pipe = None,
image_encoder_path = None,
ip_ckpt = None,
device = accelerator.device,
num_tokens = 4
)
#load weights
state_dict = {"image_proj": {}, "ip_adapter": {}}
with safe_open(args.pretrained_ip_adapter_path, framework="pt", device="cpu") as f:
for key in [Redacted Person]():
if key.startswith("image_proj."):
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
[Redacted Person] key.startswith("ip_adapter."):
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
image_proj_model.load_state_dict(state_dict["image_proj"])
ip_layers = torch.nn.ModuleList(unet.attn_processors.values())
ip_layers.load_state_dict(state_dict["ip_adapter"])
with safe_open(args.image_proj_model_path, framework="pt", device="cpu") as f:
image_proj_model_sd = {k:f.get_tensor(k) for k in f.keys()}
image_proj_model.load_state_dict(image_proj_model_sd)
with safe_open(args.vae_path, framework="pt", device="cpu") as f:
vae_sd = {k:f.get_tensor(k) for k in f.keys()}
vae.load_state_dict(vae_sd)
weight_dtype = torch.float32
if accelerator.mixed_precision == "fp16":
weight_dtype = torch.float16
elif accelerator.mixed_precision == "bf16":
weight_dtype = torch.bfloat16
unet.to(accelerator.device, dtype=weight_dtype)
vae.to(accelerator.device, dtype=weight_dtype)
text_encoder.to(accelerator.device, dtype=weight_dtype)
image_encoder.to(accelerator.device, dtype=weight_dtype)
image_proj_model.to(accelerator.device, dtype=weight_dtype)
ip_layers.to(accelerator.device, dtype=weight_dtype)
# dataloader
train_dataset = MyDataset(args.data_json_file, tokenizer=tokenizer, size=args.resolution, image_root_path=args.data_root_path)
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
shuffle=False,
collate_fn=collate_fn,
batch_size=args.train_batch_size,
num_workers=args.dataloader_num_workers,
)
# Prepare everything with our `accelerator`.
unet, train_dataloader = accelerator.prepare(unet, train_dataloader)
generator = get_generator(args.seed, accelerator.device)
global_step = 0
for step, batch in enumerate(train_dataloader):
begin = time.perf_counter()
with torch.no_grad():
# Convert images to latent space
latents = vae.encode(batch["images"].to(accelerator.device, dtype=weight_dtype)).latent_dist.sample()
latents = latents * vae.config.scaling_factor
# Sample noise that we'll add to the latents
noise = torch.randn_like(latents)
bsz = latents.shape[0]
# Sample a random timestep for each image
timesteps = torch.randint(0, noise_scheduler.num_train_timesteps, (bsz,), device=latents.device)
timesteps = timesteps.long()
# Add noise to the latents according to the noise magnitude at each timestep
# (this is the forward diffusion process)
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
image_embeds = image_encoder(batch["clip_images"].to(accelerator.device, dtype=weight_dtype)).image_embeds
encoder_hidden_states = text_encoder(batch["text_input_ids"].to(accelerator.device))[0]
image_prompt_embeds, uncond_image_prompt_embeds = ip_adapter.get_image_embeds(
clip_image_embeds=image_embeds
)
bs_embed, seq_len, _ = image_prompt_embeds.shape
image_prompt_embeds = image_prompt_embeds.repeat(1, args.num_samples, 1)
image_prompt_embeds = image_prompt_embeds.view(bs_embed * args.num_samples, seq_len, -1)
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, args.num_samples, 1)
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * args.num_samples, seq_len, -1)
with torch.inference_mode():
prompt_embeds_, negative_prompt_embeds_ = text_encoder.encode_prompt(
["best quality, high quality"] * bsz,
device=accelerator.device,
num_images_per_prompt=args.num_samples,
do_classifier_free_guidance=True,
negative_prompt=["monochrome, lowres, bad anatomy, worst quality, low quality"] * bsz,
)
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
images = ip_adapter.pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
guidance_scale=args.guidance_scale,
num_inference_steps=args.num_inference_steps,
generator=generator,
).images
if accelerator.is_main_process:
for i, image in enumerate(images):
image.save(os.path.join(args.output_dir, f"step_{step}_image_{i}.png"))
print("step: {}, time: {}".format(step, time.perf_counter() - begin))
global_step += 1
if __name__ == "__main__":
main()
This code will load the necessary components, process your image dataset, and generate images using Stable Diffusion with IP-Adapter, saving the results to your specified output directory.