File size: 9,761 Bytes
27898b7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
import os
import torch
import cv2
import numpy as np
from PIL import Image
import argparse
from diffusers import DDPMScheduler
from pipeline_sdxl_ipadapter import StableDiffusionXLControlNeXtPipeline
from transformers import CLIPVisionModelWithProjection
from transformers import CLIPTokenizer
import onnxruntime as ort
from configs import *
def log_validation(
vae,
scheduler,
text_encoder,
tokenizer,
unet,
controlnet,
args,
device,
image_proj,
text_encoder2,
tokenizer2,
image_encoder
):
if len(args.validation_image) == len(args.validation_prompt):
validation_images = args.validation_image
validation_prompts = args.validation_prompt
elif len(args.validation_image) == 1:
validation_images = args.validation_image * len(args.validation_prompt)
validation_prompts = args.validation_prompt
elif len(args.validation_prompt) == 1:
validation_images = args.validation_image
validation_prompts = args.validation_prompt * len(args.validation_image)
else:
raise ValueError(
"number of `args.validation_image` and `args.validation_prompt` should be checked in `parse_args`"
)
if args.negative_prompt is not None:
negative_prompts = args.negative_prompt
assert len(validation_prompts) == len(validation_prompts)
else:
negative_prompts = None
inference_ctx = torch.autocast(device)
pipeline = StableDiffusionXLControlNeXtPipeline(
vae=vae,
text_encoder=text_encoder,
text_encoder_2=text_encoder2,
tokenizer=tokenizer,
tokenizer_2=tokenizer2,
unet=unet,
controlnext=controlnet,
scheduler=scheduler,
image_encoder=image_encoder,
device=device,
image_proj=image_proj
)
image_logs = []
pil_image = args.pil_image
if args.pil_image is not None:
pil_image = Image.open(pil_image).convert("RGB")
for i, (validation_prompt, validation_image) in enumerate(zip(validation_prompts, validation_images)):
validation_image = Image.open(validation_image).convert("RGB")
images = []
negative_prompt = negative_prompts[i] if negative_prompts is not None else None
for _ in range(args.num_validation_images):
with inference_ctx:
image = pipeline(
prompt=validation_prompt,
controlnet_image=validation_image,
num_inference_steps=args.num_inference_steps,
guidance_rescale = args.guidance_scale,
negative_prompt=negative_prompt,
ip_adapter_image=pil_image,
control_scale=args.controlnext_scale,
width = args.width,
height=args.height,
)[0]
images.append(image)
image_logs.append(
{"validation_image": validation_image.resize((args.width,args.height)),
"ip_adapter_image": pil_image.resize((args.width,args.height)),
"images": images, "validation_prompt": validation_prompt}
)
save_dir_path = args.output_dir
if not os.path.exists(save_dir_path):
os.makedirs(save_dir_path)
for i, log in enumerate(image_logs):
images = log["images"]
validation_prompt = log["validation_prompt"]
ip_adapter_image = log["ip_adapter_image"]
validation_image = log["validation_image"]
formatted_images = []
formatted_images.append(np.asarray(validation_image))
formatted_images.append(np.asarray(ip_adapter_image))
for image in images:
formatted_images.append(np.asarray(image))
for idx, img in enumerate(formatted_images):
print(f"Image {idx} shape: {img.shape}")
formatted_images = np.concatenate(formatted_images, 1)
file_path = os.path.join(save_dir_path, "image_{}.png".format(i))
formatted_images = cv2.cvtColor(formatted_images, cv2.COLOR_BGR2RGB)
print("Save images to:", file_path)
cv2.imwrite(file_path, formatted_images)
return image_logs
def parse_args(input_args=None):
parser = argparse.ArgumentParser(description="Simple example of a ControlNet training script.")
parser.add_argument(
"--output_dir",
type=str,
default=None,
help="The output directory where the inference result will be written.",
)
parser.add_argument(
"--pil_image",
type=str,
default=None,
help="IP Adapter image path.",
)
parser.add_argument(
"--validation_prompt",
type=str,
default=None,
nargs="+",
help=(
"A set of prompts evaluated every `--validation_steps` and logged to `--report_to`."
" Provide either a matching number of `--validation_image`s, a single `--validation_image`"
" to be used with all prompts, or a single prompt that will be used with all `--validation_image`s."
),
)
parser.add_argument(
"--negative_prompt",
type=str,
default=None,
nargs="+",
help=(
"A set of prompts evaluated every `--validation_steps` and logged to `--report_to`."
" Provide either a matching number of `--validation_image`s, a single `--validation_image`"
" to be used with all prompts, or a single prompt that will be used with all `--validation_image`s."
),
)
parser.add_argument(
"--validation_image",
type=str,
default=None,
nargs="+",
help=(
"A set of paths to the controlnet conditioning image be evaluated every `--validation_steps`"
" and logged to `--report_to`. Provide either a matching number of `--validation_prompt`s, a"
" a single `--validation_prompt` to be used with all `--validation_image`s, or a single"
" `--validation_image` that will be used with all `--validation_prompt`s."
),
)
parser.add_argument(
"--num_validation_images",
type=int,
default=1,
help="Number of images to be generated for each `--validation_image`, `--validation_prompt` pair.",
)
parser.add_argument(
"--num_inference_steps",
type=int,
default=30,
help="Number of steps for inference.",
)
parser.add_argument(
"--controlnext_scale",
type=float,
default=2.5,
help="ControlNext scale.",
)
parser.add_argument(
"--guidance_scale",
type=float,
default=7.5,
help="Guidance scale.",
)
parser.add_argument(
"--height",
type=int,
default=1024,
help="The height of output image.",
)
parser.add_argument(
"--width",
type=int,
default=1024,
help="The width of output image.",
)
if input_args is not None:
args = parser.parse_args(input_args)
else:
args = parser.parse_args()
if args.validation_prompt is not None and args.validation_image is None:
raise ValueError("`--validation_image` must be set if `--validation_prompt` is set")
if args.validation_prompt is None and args.validation_image is not None:
raise ValueError("`--validation_prompt` must be set if `--validation_image` is set")
if (
args.validation_image is not None
and args.validation_prompt is not None
and len(args.validation_image) != 1
and len(args.validation_prompt) != 1
and len(args.validation_image) != len(args.validation_prompt)
):
raise ValueError(
"Must provide either 1 `--validation_image`, 1 `--validation_prompt`,"
" or the same number of `--validation_prompt`s and `--validation_image`s"
)
return args
if __name__ == "__main__":
args = parse_args()
device = 'cuda:0'
vae_session = ort.InferenceSession(VAE_ONNX_PATH, providers=providers, sess_options=session_options)
unet_session = ort.InferenceSession(UNET_ONNX_PATH, providers=providers, sess_options=session_options, provider_options=provider_options_1)
tokenizer = CLIPTokenizer.from_pretrained(TOKENIZER_PATH)
tokenizer2 = CLIPTokenizer.from_pretrained(TOKENIZER_PATH2)
text_encoder_session = ort.InferenceSession(TEXT_ENCODER_PATH, providers=providers, sess_options=session_options)
text_encoder_session2 = ort.InferenceSession(TEXT_ENCODER_PATH2, providers=providers, sess_options=session_options)
scheduler = DDPMScheduler.from_pretrained(SCHEDULER_PATH)
controlnet = ort.InferenceSession(CONTROLNEXT_ONNX_PATH, providers=providers, sess_options=session_options)
#image_encoder = ort.InferenceSession(IMAGE_ENCODER_ONNX_PATH, providers=providers, provider_options=provider_options_0)
image_encoder = CLIPVisionModelWithProjection.from_pretrained('h94/IP-Adapter', subfolder = 'sdxl_models/image_encoder').to(device, dtype=torch.float32)
image_proj = ort.InferenceSession(PROJ_ONNX_PATH, providers=providers, sess_options=session_options)
log_validation(
vae=vae_session,
scheduler=scheduler,
text_encoder=text_encoder_session,
tokenizer=tokenizer,
unet=unet_session,
controlnet=controlnet,
image_encoder = image_encoder,
args=args,
device=device,
image_proj = image_proj,
text_encoder2 = text_encoder_session2,
tokenizer2 = tokenizer2
) |