Spaces:
Paused
Paused
ResearcherXman commited on
Commit ·
ec7fc1c
1
Parent(s): f4fab1d
support lcm and multi-controlnets
Browse filesFiles changed (12)
- app.py+284-128
- controlnet_util.pyAdded+39
- gradio_cached_examples/25/Generated Image/2880a3d19ef9b42e3ed2/image.pngDeleted
- gradio_cached_examples/25/Generated Image/38dde1388c41109c5d39/image.pngDeleted
- gradio_cached_examples/25/Generated Image/6cb5a3af223906666bfd/image.pngDeleted
- gradio_cached_examples/25/Generated Image/7e6ea85f77dd925d842c/image.pngDeleted
- gradio_cached_examples/25/Generated Image/e56b029833685ff77e6a/image.pngDeleted
- gradio_cached_examples/25/log.csvDeleted-6
- ip_adapter/attention_processor.py+146-8
- model_util.pyAdded+472
- pipeline_stable_diffusion_xl_instantid.py → pipeline_stable_diffusion_xl_instantid_full.pyRenamed+102-21
- requirements.txt+7-3
12345678910111213141516171819202122239 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011 unmodified line10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115219 unmodified lines1721731741751761771781791801811821831841851861871881891901911921 unmodified line1941951961971981992002012022032042052062071 unmodified line2092102112122132142151 unmodified line2172182192202212222232242252262272282292302312322332342352362372382399 unmodified lines2492502512522532544 unmodified lines2592602612622632642652662673 unmodified lines2712722732742752762772782 unmodified lines2812822832842852862872882892902912922 unmodified lines2952962972982993003013023033043 unmodified lines3083093103113123133143153163176 unmodified lines3243253263273283293303313323333343353363373383393403413423433443453463473483493506 unmodified lines3573583593603613623633643653663673683693703713723733743753763773783793803813822 unmodified lines3853863873883893903913923933943953963973983994004014021 unmodified line4044054064074084094104114124134141 unmodified line416417418419420421422423424425426427428429430431432433434435436import mathimport randomimport cv2import gradio as grimport numpy as npimport PILimport spacesimport torchfrom diffusers.models import ControlNetModelfrom diffusers.utils import load_imagefrom insightface.app import FaceAnalysisfrom PIL import Imagefrom pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipelinefrom style_template import styles# global variableMAX_SEED = np.iinfo(np.int32).maxdevice = "cuda" if torch.cuda.is_available() else "cpu"STYLE_NAMES = list(styles.keys())DEFAULT_STYLE_NAME = "Watercolor"9 unmodified lineshf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints")# Load face encoderapp = FaceAnalysis(name="antelopev2", root="./", providers=["CPUExecutionProvider"])app.prepare(ctx_id=0, det_size=(640, 640))# Path to InstantID modelsface_adapter = "./checkpoints/ip-adapter.bin"controlnet_path = "./checkpoints/ControlNetModel"# Load pipelinecontrolnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)base_model_path = "wangqixun/YamerMIX_v8"pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(base_model_path,controlnet=controlnet,torch_dtype=torch.float16,safety_checker=None,feature_extractor=None,)pipe.cuda()pipe.load_ip_adapter_instantid(face_adapter)pipe.image_proj_model.to("cuda")pipe.unet.to("cuda")def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:if randomize_seed:seed = random.randint(0, MAX_SEED)return seeddef remove_tips():return gr.update(visible=False)def get_example():case = [["./examples/yann-lecun_resize.jpg","a man","Snow","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/musk_resize.jpeg","a man","Mars","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/sam_resize.png","a man","Jungle","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, gree",],["./examples/schmidhuber_resize.png","a man","Neon","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/kaifu_resize.png","a man","Vibrant Color","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",1 unmodified line]return casedef run_for_examples(face_file, prompt, style, negative_prompt):return generate_image(face_file, None, prompt, negative_prompt, style, True, 30, 0.8, 0.8, 5, 42)def convert_from_cv2_to_image(img: np.ndarray) -> Image:return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))def convert_from_image_to_cv2(img: Image) -> np.ndarray:return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)def draw_kps(image_pil, kps, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]):stickwidth = 4limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])kps = np.array(kps)w, h = image_pil.sizeout_img = np.zeros([h, w, 3])for i in range(len(limbSeq)):index = limbSeq[i]color = color_list[index[0]]x = kps[index][:, 0]y = kps[index][:, 1]length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)out_img = (out_img * 0.6).astype(np.uint8)for idx_kp, kp in enumerate(kps):color = color_list[idx_kp]x, y = kpout_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)out_img_pil = Image.fromarray(out_img.astype(np.uint8))return out_img_pildef resize_img(input_image,max_side=1280,19 unmodified linesres = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255offset_x = (max_side - w_resize_new) // 2offset_y = (max_side - h_resize_new) // 2res[offset_y : offset_y + h_resize_new, offset_x : offset_x + w_resize_new] = np.array(input_image)input_image = Image.fromarray(res)return input_imagedef apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]:p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])return p.replace("{prompt}", positive), n + " " + negativedef check_input_image(face_image):if face_image is None:raise gr.Error("Cannot find any input face image! Please upload the face image")@spaces.GPUdef generate_image(face_image_path,1 unmodified lineprompt,negative_prompt,style_name,enhance_face_region,num_steps,identitynet_strength_ratio,adapter_strength_ratio,guidance_scale,seed,progress=gr.Progress(track_tqdm=True),):if prompt is None:prompt = "a person"1 unmodified lineprompt, negative_prompt = apply_style(style_name, prompt, negative_prompt)face_image = load_image(face_image_path)face_image = resize_img(face_image)face_image_cv2 = convert_from_image_to_cv2(face_image)height, width, _ = face_image_cv2.shape1 unmodified lineface_info = app.get(face_image_cv2)if len(face_info) == 0:raise gr.Error("Cannot find any face in the image! Please upload another person image")face_info = sorted(face_info, key=lambda x: (x["bbox"][2] - x["bbox"][0]) * x["bbox"][3] - x["bbox"][1])[-1] # only use the maximum faceface_emb = face_info["embedding"]face_kps = draw_kps(convert_from_cv2_to_image(face_image_cv2), face_info["kps"])if pose_image_path is not None:pose_image = load_image(pose_image_path)pose_image = resize_img(pose_image)pose_image_cv2 = convert_from_image_to_cv2(pose_image)face_info = app.get(pose_image_cv2)if len(face_info) == 0:raise gr.Error("Cannot find any face in the reference image! Please upload another person image")face_info = face_info[-1]face_kps = draw_kps(pose_image, face_info["kps"])9 unmodified lineselse:control_mask = Nonegenerator = torch.Generator(device=device).manual_seed(seed)print("Start inference...")4 unmodified linesprompt=prompt,negative_prompt=negative_prompt,image_embeds=face_emb,image=face_kps,control_mask=control_mask,controlnet_conditioning_scale=float(identitynet_strength_ratio),num_inference_steps=num_steps,guidance_scale=guidance_scale,height=height,3 unmodified linesreturn images[0], gr.update(visible=True)### Descriptiontitle = r"""<h1 align="center">InstantID: Zero-shot Identity-Preserving Generation in Seconds</h1>"""2 unmodified lines<b>Official 🤗 Gradio demo</b> for <a href='https://github.com/InstantID/InstantID' target='_blank'><b>InstantID: Zero-shot Identity-Preserving Generation in Seconds</b></a>.<br>How to use:<br>1. Upload a person image. For multiple person images, we will only detect the biggest face. Make sure face is not too small and not significantly blocked or blurred.2. (Optionally) upload another person image as reference pose. If not uploaded, we will use the first person image to extract landmarks. If you use a cropped face at step1, it is recommeneded to upload it to extract a new pose.3. Enter a text prompt as done in normal text-to-image models.4. Click the <b>Submit</b> button to start customizing.5. Share your customizd photo with your friends, enjoy😊!"""article = r"""---2 unmodified linesIf our work is helpful for your research or applications, please cite us via:```bibtex@article{wang2024instantid,title={InstantID: Zero-shot Identity-Preserving Generation in Seconds},author={Wang, Qixun and Bai, Xu and Wang, Haofan and Qin, Zekui and Chen, Anthony},journal={arXiv preprint arXiv:2401.07519},year={2024}}```📧 **Contact**3 unmodified linestips = r"""### Usage tips of InstantID1. If you're unsatisfied with the similarity, increase the weight of controlnet_conditioning_scale (IdentityNet) and ip_adapter_scale (Adapter).2. If the generated image is over-saturated, decrease the ip_adapter_scale. If not work, decrease controlnet_conditioning_scale.3. If text control is not as expected, decrease ip_adapter_scale.4. Find a good base model always makes a difference."""css = """6 unmodified lineswith gr.Row():with gr.Column():# upload face imageface_file = gr.Image(label="Upload a photo of your face", type="filepath")# optional: upload a reference pose imagepose_file = gr.Image(label="Upload a reference pose image (optional)", type="filepath")# promptprompt = gr.Textbox(label="Prompt",info="Give simple prompt is enough to achieve good face fedility",placeholder="A photo of a person",value="",)submit = gr.Button("Submit", variant="primary")style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)# strengthidentitynet_strength_ratio = gr.Slider(label="IdentityNet strength (for fedility)",minimum=0,maximum=1.5,step=0.05,6 unmodified linesstep=0.05,value=0.80,)with gr.Accordion(open=False, label="Advanced Options"):negative_prompt = gr.Textbox(label="Negative Prompt",placeholder="low quality",value="(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, nudity,naked, bikini, skimpy, scanty, bare skin, lingerie, swimsuit, exposed, see-through, photo, anthropomorphic cat, monochrome, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",)num_steps = gr.Slider(label="Number of sample steps",minimum=20,maximum=100,step=1,value=30,)guidance_scale = gr.Slider(label="Guidance scale",minimum=0.1,maximum=10.0,step=0.1,value=5,)seed = gr.Slider(label="Seed",2 unmodified linesstep=1,value=42,)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)enhance_face_region = gr.Checkbox(label="Enhance non-face region", value=True)with gr.Column():output_image = gr.Image(label="Generated Image")usage_tips = gr.Markdown(label="Usage tips of InstantID", value=tips, visible=False)submit.click(fn=remove_tips,outputs=usage_tips,queue=False,api_name=False,).then(fn=randomize_seed_fn,inputs=[seed, randomize_seed],1 unmodified linequeue=False,api_name=False,).then(fn=check_input_image,inputs=face_file,queue=False,api_name=False,).success(fn=generate_image,inputs=[face_file,1 unmodified lineprompt,negative_prompt,style,enhance_face_region,num_steps,identitynet_strength_ratio,adapter_strength_ratio,guidance_scale,seed,],outputs=[output_image, usage_tips],)gr.Examples(examples=get_example(),inputs=[face_file, prompt, style, negative_prompt],outputs=[output_image, usage_tips],fn=run_for_examples,cache_examples=True,)123456789101112131415161718192021222324252627282930313233349 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631 unmodified line16516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719 unmodified lines2172182192202212222232242252262272282292302312322332341 unmodified line2362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752761 unmodified line2782792802812822832841 unmodified line2862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153169 unmodified lines3263273283293303313323333343353363373383393403413423433443453463473483493503513523534 unmodified lines3583593603613623633643653663 unmodified lines3703713723733743753762 unmodified lines3793803813823833843853863873883893902 unmodified lines3933943953963973983994004014023 unmodified lines4064074084094104114124134144156 unmodified lines4224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594606 unmodified lines4674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165172 unmodified lines5205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495501 unmodified line5525535545555565571 unmodified line559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592import osimport cv2import torchimport randomimport numpy as npimport PILfrom PIL import Imageimport diffusersfrom diffusers.utils import load_imagefrom diffusers.models import ControlNetModelfrom diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModelfrom huggingface_hub import hf_hub_downloadfrom insightface.app import FaceAnalysisfrom style_template import stylesfrom pipeline_stable_diffusion_xl_instantid_full import StableDiffusionXLInstantIDPipeline, draw_kpsfrom model_util import load_models_xl, get_torch_devicefrom controlnet_util import openpose, get_depth_map, get_canny_imageimport gradio as grimport spaces# global variableMAX_SEED = np.iinfo(np.int32).maxdevice = get_torch_device()dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32STYLE_NAMES = list(styles.keys())DEFAULT_STYLE_NAME = "Watercolor"9 unmodified lineshf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints")# Load face encoderapp = FaceAnalysis(name="antelopev2",root="./",providers=["CUDAExecutionProvider", "CPUExecutionProvider"],)app.prepare(ctx_id=0, det_size=(640, 640))# Path to InstantID modelsface_adapter = f"./checkpoints/ip-adapter.bin"controlnet_path = f"./checkpoints/ControlNetModel"# Load pipeline face ControlNetModelcontrolnet_identitynet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=dtype)# controlnet-posecontrolnet_pose_model = "thibaud/controlnet-openpose-sdxl-1.0"controlnet_canny_model = "diffusers/controlnet-canny-sdxl-1.0"controlnet_depth_model = "diffusers/controlnet-depth-sdxl-1.0-small"controlnet_pose = ControlNetModel.from_pretrained(controlnet_pose_model, torch_dtype=dtype).to(device)controlnet_canny = ControlNetModel.from_pretrained(controlnet_canny_model, torch_dtype=dtype).to(device)controlnet_depth = ControlNetModel.from_pretrained(controlnet_depth_model, torch_dtype=dtype).to(device)controlnet_map = {"pose": controlnet_pose,"canny": controlnet_canny,"depth": controlnet_depth,}controlnet_map_fn = {"pose": openpose,"canny": get_canny_image,"depth": get_depth_map,}pretrained_model_name_or_path = "wangqixun/YamerMIX_v8"pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(pretrained_model_name_or_path,controlnet=[controlnet_identitynet],torch_dtype=dtype,safety_checker=None,feature_extractor=None,).to(device)pipe.scheduler = diffusers.EulerDiscreteScheduler.from_config(pipe.scheduler.config)pipe.load_ip_adapter_instantid(face_adapter)# load and disable LCMpipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")pipe.disable_lora()def toggle_lcm_ui(value):if value:return (gr.update(minimum=0, maximum=100, step=1, value=5),gr.update(minimum=0.1, maximum=20.0, step=0.1, value=1.5),)else:return (gr.update(minimum=5, maximum=100, step=1, value=30),gr.update(minimum=0.1, maximum=20.0, step=0.1, value=5),)def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:if randomize_seed:seed = random.randint(0, MAX_SEED)return seeddef remove_tips():return gr.update(visible=False)def get_example():case = [["./examples/yann-lecun_resize.jpg",None,"a man","Snow","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/musk_resize.jpeg","./examples/poses/pose2.jpg","a man flying in the sky in Mars","Mars","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/sam_resize.png","./examples/poses/pose4.jpg","a man doing a silly pose wearing a suite","Jungle","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, gree",],["./examples/schmidhuber_resize.png","./examples/poses/pose3.jpg","a man sit on a chair","Neon","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",],["./examples/kaifu_resize.png","./examples/poses/pose.jpg","a man","Vibrant Color","(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",1 unmodified line]return casedef run_for_examples(face_file, pose_file, prompt, style, negative_prompt):return generate_image(face_file,pose_file,prompt,negative_prompt,style,20, # num_steps0.8, # identitynet_strength_ratio0.8, # adapter_strength_ratio0.4, # pose_strength0.3, # canny_strength0.5, # depth_strength["pose", "canny"], # controlnet_selection5.0, # guidance_scale42, # seed"EulerDiscreteScheduler", # schedulerFalse, # enable_LCMTrue, # enable_Face_Region)def convert_from_cv2_to_image(img: np.ndarray) -> Image:return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))def convert_from_image_to_cv2(img: Image) -> np.ndarray:return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)def resize_img(input_image,max_side=1280,19 unmodified linesres = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255offset_x = (max_side - w_resize_new) // 2offset_y = (max_side - h_resize_new) // 2res[offset_y : offset_y + h_resize_new, offset_x : offset_x + w_resize_new] = np.array(input_image)input_image = Image.fromarray(res)return input_imagedef apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]:p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])return p.replace("{prompt}", positive), n + " " + negative@spaces.GPUdef generate_image(face_image_path,1 unmodified lineprompt,negative_prompt,style_name,num_steps,identitynet_strength_ratio,adapter_strength_ratio,pose_strength,canny_strength,depth_strength,controlnet_selection,guidance_scale,seed,scheduler,enable_LCM,enhance_face_region,progress=gr.Progress(track_tqdm=True),):if enable_LCM:pipe.scheduler = diffusers.LCMScheduler.from_config(pipe.scheduler.config)pipe.enable_lora()else:pipe.disable_lora()scheduler_class_name = scheduler.split("-")[0]add_kwargs = {}if len(scheduler.split("-")) > 1:add_kwargs["use_karras_sigmas"] = Trueif len(scheduler.split("-")) > 2:add_kwargs["algorithm_type"] = "sde-dpmsolver++"scheduler = getattr(diffusers, scheduler_class_name)pipe.scheduler = scheduler.from_config(pipe.scheduler.config, **add_kwargs)if face_image_path is None:raise gr.Error(f"Cannot find any input face image! Please upload the face image")if prompt is None:prompt = "a person"1 unmodified lineprompt, negative_prompt = apply_style(style_name, prompt, negative_prompt)face_image = load_image(face_image_path)face_image = resize_img(face_image, max_side=1024)face_image_cv2 = convert_from_image_to_cv2(face_image)height, width, _ = face_image_cv2.shape1 unmodified lineface_info = app.get(face_image_cv2)if len(face_info) == 0:raise gr.Error(f"Unable to detect a face in the image. Please upload a different photo with a clear face.")face_info = sorted(face_info,key=lambda x: (x["bbox"][2] - x["bbox"][0]) * x["bbox"][3] - x["bbox"][1],)[-1] # only use the maximum faceface_emb = face_info["embedding"]face_kps = draw_kps(convert_from_cv2_to_image(face_image_cv2), face_info["kps"])img_controlnet = face_imageif pose_image_path is not None:pose_image = load_image(pose_image_path)pose_image = resize_img(pose_image, max_side=1024)img_controlnet = pose_imagepose_image_cv2 = convert_from_image_to_cv2(pose_image)face_info = app.get(pose_image_cv2)if len(face_info) == 0:raise gr.Error(f"Cannot find any face in the reference image! Please upload another person image")face_info = face_info[-1]face_kps = draw_kps(pose_image, face_info["kps"])9 unmodified lineselse:control_mask = Noneif len(controlnet_selection) > 0:controlnet_scales = {"pose": pose_strength,"canny": canny_strength,"depth": depth_strength,}pipe.controlnet = MultiControlNetModel([controlnet_identitynet]+ [controlnet_map[s] for s in controlnet_selection])control_scales = [float(identitynet_strength_ratio)] + [controlnet_scales[s] for s in controlnet_selection]control_images = [face_kps] + [controlnet_map_fn[s](img_controlnet).resize((width, height))for s in controlnet_selection]else:pipe.controlnet = controlnet_identitynetcontrol_scales = float(identitynet_strength_ratio)control_images = face_kpsgenerator = torch.Generator(device=device).manual_seed(seed)print("Start inference...")4 unmodified linesprompt=prompt,negative_prompt=negative_prompt,image_embeds=face_emb,image=control_images,control_mask=control_mask,controlnet_conditioning_scale=control_scales,num_inference_steps=num_steps,guidance_scale=guidance_scale,height=height,3 unmodified linesreturn images[0], gr.update(visible=True)# Descriptiontitle = r"""<h1 align="center">InstantID: Zero-shot Identity-Preserving Generation in Seconds</h1>"""2 unmodified lines<b>Official 🤗 Gradio demo</b> for <a href='https://github.com/InstantID/InstantID' target='_blank'><b>InstantID: Zero-shot Identity-Preserving Generation in Seconds</b></a>.<br>How to use:<br>1. Upload an image with a face. For images with multiple faces, we will only detect the largest face. Ensure the face is not too small and is clearly visible without significant obstructions or blurring.2. (Optional) You can upload another image as a reference for the face pose. If you don't, we will use the first detected face image to extract facial landmarks. If you use a cropped face at step 1, it is recommended to upload it to define a new face pose.3. (Optional) You can select multiple ControlNet models to control the generation process. The default is to use the IdentityNet only. The ControlNet models include pose skeleton, canny, and depth. You can adjust the strength of each ControlNet model to control the generation process.4. Enter a text prompt, as done in normal text-to-image models.5. Click the <b>Submit</b> button to begin customization.6. Share your customized photo with your friends and enjoy! 😊"""article = r"""---2 unmodified linesIf our work is helpful for your research or applications, please cite us via:```bibtex@article{wang2024instantid,title={InstantID: Zero-shot Identity-Preserving Generation in Seconds},author={Wang, Qixun and Bai, Xu and Wang, Haofan and Qin, Zekui and Chen, Anthony},journal={arXiv preprint arXiv:2401.07519},year={2024}}```📧 **Contact**3 unmodified linestips = r"""### Usage tips of InstantID1. If you're not satisfied with the similarity, try increasing the weight of "IdentityNet Strength" and "Adapter Strength."2. If you feel that the saturation is too high, first decrease the Adapter strength. If it remains too high, then decrease the IdentityNet strength.3. If you find that text control is not as expected, decrease Adapter strength.4. If you find that realistic style is not good enough, go for our Github repo and use a more realistic base model."""css = """6 unmodified lineswith gr.Row():with gr.Column():with gr.Row(equal_height=True):# upload face imageface_file = gr.Image(label="Upload a photo of your face", type="filepath")# optional: upload a reference pose imagepose_file = gr.Image(label="Upload a reference pose image (Optional)",type="filepath",)# promptprompt = gr.Textbox(label="Prompt",info="Give simple prompt is enough to achieve good face fidelity",placeholder="A photo of a person",value="",)submit = gr.Button("Submit", variant="primary")enable_LCM = gr.Checkbox(label="Enable Fast Inference with LCM", value=enable_lcm_arg,info="LCM speeds up the inference step, the trade-off is the quality of the generated image. It performs better with portrait face images rather than distant faces",)style = gr.Dropdown(label="Style template",choices=STYLE_NAMES,value=DEFAULT_STYLE_NAME,)# strengthidentitynet_strength_ratio = gr.Slider(label="IdentityNet strength (for fidelity)",minimum=0,maximum=1.5,step=0.05,6 unmodified linesstep=0.05,value=0.80,)with gr.Accordion("Controlnet"):controlnet_selection = gr.CheckboxGroup(["pose", "canny", "depth"], label="Controlnet", value=["pose"],info="Use pose for skeleton inference, canny for edge detection, and depth for depth map estimation. You can try all three to control the generation process")pose_strength = gr.Slider(label="Pose strength",minimum=0,maximum=1.5,step=0.05,value=0.40,)canny_strength = gr.Slider(label="Canny strength",minimum=0,maximum=1.5,step=0.05,value=0.40,)depth_strength = gr.Slider(label="Depth strength",minimum=0,maximum=1.5,step=0.05,value=0.40,)with gr.Accordion(open=False, label="Advanced Options"):negative_prompt = gr.Textbox(label="Negative Prompt",placeholder="low quality",value="(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green",)num_steps = gr.Slider(label="Number of sample steps",minimum=1,maximum=100,step=1,value=5 if enable_lcm_arg else 30,)guidance_scale = gr.Slider(label="Guidance scale",minimum=0.1,maximum=20.0,step=0.1,value=0.0 if enable_lcm_arg else 5.0,)seed = gr.Slider(label="Seed",2 unmodified linesstep=1,value=42,)schedulers = ["DEISMultistepScheduler","HeunDiscreteScheduler","EulerDiscreteScheduler","DPMSolverMultistepScheduler","DPMSolverMultistepScheduler-Karras","DPMSolverMultistepScheduler-Karras-SDE",]scheduler = gr.Dropdown(label="Schedulers",choices=schedulers,value="EulerDiscreteScheduler",)randomize_seed = gr.Checkbox(label="Randomize seed", value=True)enhance_face_region = gr.Checkbox(label="Enhance non-face region", value=True)with gr.Column(scale=1):gallery = gr.Image(label="Generated Images")usage_tips = gr.Markdown(label="InstantID Usage Tips", value=tips, visible=False)submit.click(fn=remove_tips,outputs=usage_tips,).then(fn=randomize_seed_fn,inputs=[seed, randomize_seed],1 unmodified linequeue=False,api_name=False,).then(fn=generate_image,inputs=[face_file,1 unmodified lineprompt,negative_prompt,style,num_steps,identitynet_strength_ratio,adapter_strength_ratio,pose_strength,canny_strength,depth_strength,controlnet_selection,guidance_scale,seed,scheduler,enable_LCM,enhance_face_region,],outputs=[gallery, usage_tips],)enable_LCM.input(fn=toggle_lcm_ui,inputs=[enable_LCM],outputs=[num_steps, guidance_scale],queue=False,)gr.Examples(examples=get_example(),inputs=[face_file, pose_file, prompt, style, negative_prompt],fn=run_for_examples,outputs=[gallery, usage_tips],cache_examples=True,)
123456789101112131415161718192021222324252627282930313233343536373839import torchimport numpy as npfrom PIL import Imagefrom controlnet_aux import OpenposeDetectorfrom model_util import get_torch_deviceimport cv2
from transformers import DPTImageProcessor, DPTForDepthEstimation
device = get_torch_device()depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
def get_depth_map(image): image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda") with torch.no_grad(), torch.autocast("cuda"): depth_map = depth_estimator(image).predicted_depth
depth_map = torch.nn.functional.interpolate( depth_map.unsqueeze(1), size=(1024, 1024), mode="bicubic", align_corners=False, ) depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True) depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True) depth_map = (depth_map - depth_min) / (depth_max - depth_min) image = torch.cat([depth_map] * 3, dim=1)
image = image.permute(0, 2, 3, 1).cpu().numpy()[0] image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8)) return image
def get_canny_image(image, t1=100, t2=200): image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) edges = cv2.Canny(image, t1, t2) return Image.fromarray(edges, "L")123456Generated Image,Usage tips of InstantID,flag,username,timestamp
"{""path"":""gradio_cached_examples/25/Generated Image/7e6ea85f77dd925d842c/image.png"",""url"":null,""size"":null,""orig_name"":""image.png"",""mime_type"":null}","{'visible': True, '__type__': 'update'}",,,2024-01-24 08:55:38.846769
"{""path"":""gradio_cached_examples/25/Generated Image/2880a3d19ef9b42e3ed2/image.png"",""url"":null,""size"":null,""orig_name"":""image.png"",""mime_type"":null}","{'visible': True, '__type__': 'update'}",,,2024-01-24 08:56:11.432078
"{""path"":""gradio_cached_examples/25/Generated Image/38dde1388c41109c5d39/image.png"",""url"":null,""size"":null,""orig_name"":""image.png"",""mime_type"":null}","{'visible': True, '__type__': 'update'}",,,2024-01-24 08:56:45.563918
"{""path"":""gradio_cached_examples/25/Generated Image/e56b029833685ff77e6a/image.png"",""url"":null,""size"":null,""orig_name"":""image.png"",""mime_type"":null}","{'visible': True, '__type__': 'update'}",,,2024-01-24 08:57:20.321876
"{""path"":""gradio_cached_examples/25/Generated Image/6cb5a3af223906666bfd/image.png"",""url"":null,""size"":null,""orig_name"":""image.png"",""mime_type"":null}","{'visible': True, '__type__': 'update'}",,,2024-01-24 08:57:53.8717169 unmodified lines10111213141516171819202122235 unmodified lines2930313233343579 unmodified lines11511611711811912012158 unmodified lines1801811821831841851863 unmodified lines19019119219319419519636 unmodified lines23323423523623723823965 unmodified lines3053063073089 unmodified linesexcept Exception as e:xformers_available = Falseclass RegionControler(object):def __init__(self) -> None:self.prompt_image_conditioning = []region_control = RegionControler()class AttnProcessor(nn.Module):r"""Default processor for performing attention-related computations.5 unmodified lines):super().__init__()def __call__(self,attn,hidden_states,79 unmodified linesself.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)def __call__(self,attn,hidden_states,58 unmodified linesip_attention_probs = attn.get_attention_scores(query, ip_key, None)ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)# region controlif len(region_control.prompt_image_conditioning) == 1:region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)3 unmodified linesmask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])else:mask = torch.ones_like(ip_hidden_states)ip_hidden_states = ip_hidden_states * maskhidden_states = hidden_states + self.scale * ip_hidden_states36 unmodified linesif not hasattr(F, "scaled_dot_product_attention"):raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")def __call__(self,attn,hidden_states,65 unmodified lineshidden_states = hidden_states / attn.rescale_output_factorreturn hidden_states9 unmodified lines10111213141516171819205 unmodified lines2627282930313279 unmodified lines11211311411511611711858 unmodified lines1771781791801811821833 unmodified lines18718818919019119219336 unmodified lines23023123223323423523665 unmodified lines3023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454469 unmodified linesexcept Exception as e:xformers_available = Falseclass RegionControler(object):def __init__(self) -> None:self.prompt_image_conditioning = []region_control = RegionControler()class AttnProcessor(nn.Module):r"""Default processor for performing attention-related computations.5 unmodified lines):super().__init__()def forward(self,attn,hidden_states,79 unmodified linesself.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)def forward(self,attn,hidden_states,58 unmodified linesip_attention_probs = attn.get_attention_scores(query, ip_key, None)ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)# region controlif len(region_control.prompt_image_conditioning) == 1:region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)3 unmodified linesmask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])else:mask = torch.ones_like(ip_hidden_states)ip_hidden_states = ip_hidden_states * maskhidden_states = hidden_states + self.scale * ip_hidden_states36 unmodified linesif not hasattr(F, "scaled_dot_product_attention"):raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")def forward(self,attn,hidden_states,65 unmodified lineshidden_states = hidden_states / attn.rescale_output_factorreturn hidden_statesclass IPAttnProcessor2_0(torch.nn.Module):r"""Attention processor for IP-Adapater for PyTorch 2.0.Args:hidden_size (`int`):The hidden size of the attention layer.cross_attention_dim (`int`):The number of channels in the `encoder_hidden_states`.scale (`float`, defaults to 1.0):the weight scale of image prompt.num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):The context length of the image features."""def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):super().__init__()if not hasattr(F, "scaled_dot_product_attention"):raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")self.hidden_size = hidden_sizeself.cross_attention_dim = cross_attention_dimself.scale = scaleself.num_tokens = num_tokensself.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)def forward(self,attn,hidden_states,encoder_hidden_states=None,attention_mask=None,temb=None,):residual = hidden_statesif attn.spatial_norm is not None:hidden_states = attn.spatial_norm(hidden_states, temb)input_ndim = hidden_states.ndimif input_ndim == 4:batch_size, channel, height, width = hidden_states.shapehidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)batch_size, sequence_length, _ = (hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape)if attention_mask is not None:attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)# scaled_dot_product_attention expects attention_mask shape to be# (batch, heads, source_length, target_length)attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])if attn.group_norm is not None:hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)query = attn.to_q(hidden_states)if encoder_hidden_states is None:encoder_hidden_states = hidden_stateselse:# get encoder_hidden_states, ip_hidden_statesend_pos = encoder_hidden_states.shape[1] - self.num_tokensencoder_hidden_states, ip_hidden_states = (encoder_hidden_states[:, :end_pos, :],encoder_hidden_states[:, end_pos:, :],)if attn.norm_cross:encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)key = attn.to_k(encoder_hidden_states)value = attn.to_v(encoder_hidden_states)inner_dim = key.shape[-1]head_dim = inner_dim // attn.headsquery = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)# the output of sdp = (batch, num_heads, seq_len, head_dim)# TODO: add support for attn.scale when we move to Torch 2.1hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False)hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)hidden_states = hidden_states.to(query.dtype)# for ip-adapterip_key = self.to_k_ip(ip_hidden_states)ip_value = self.to_v_ip(ip_hidden_states)ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)# the output of sdp = (batch, num_heads, seq_len, head_dim)# TODO: add support for attn.scale when we move to Torch 2.1ip_hidden_states = F.scaled_dot_product_attention(query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False)with torch.no_grad():self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1)#print(self.attn_map.shape)ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)ip_hidden_states = ip_hidden_states.to(query.dtype)# region controlif len(region_control.prompt_image_conditioning) == 1:region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)if region_mask is not None:h, w = region_mask.shape[:2]ratio = (h * w / query.shape[1]) ** 0.5mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])else:mask = torch.ones_like(ip_hidden_states)ip_hidden_states = ip_hidden_states * maskhidden_states = hidden_states + self.scale * ip_hidden_states# linear projhidden_states = attn.to_out[0](hidden_states)# dropouthidden_states = attn.to_out[1](hidden_states)if input_ndim == 4:hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)if attn.residual_connection:hidden_states = hidden_states + residualhidden_states = hidden_states / attn.rescale_output_factorreturn hidden_states
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472from typing import Literal, Union, Optional, Tuple, List
import torchfrom transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjectionfrom diffusers import ( UNet2DConditionModel, SchedulerMixin, StableDiffusionPipeline, StableDiffusionXLPipeline, AutoencoderKL,)from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( convert_ldm_unet_checkpoint,)from safetensors.torch import load_filefrom diffusers.schedulers import ( DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, UniPCMultistepScheduler,)
from omegaconf import OmegaConf
# DiffUsers版StableDiffusionのモデルパラメータNUM_TRAIN_TIMESTEPS = 1000BETA_START = 0.00085BETA_END = 0.0120
UNET_PARAMS_MODEL_CHANNELS = 320UNET_PARAMS_CHANNEL_MULT = [1, 2, 4, 4]UNET_PARAMS_ATTENTION_RESOLUTIONS = [4, 2, 1]UNET_PARAMS_IMAGE_SIZE = 64 # fixed from old invalid value `32`UNET_PARAMS_IN_CHANNELS = 4UNET_PARAMS_OUT_CHANNELS = 4UNET_PARAMS_NUM_RES_BLOCKS = 2UNET_PARAMS_CONTEXT_DIM = 768UNET_PARAMS_NUM_HEADS = 8# UNET_PARAMS_USE_LINEAR_PROJECTION = False
VAE_PARAMS_Z_CHANNELS = 4VAE_PARAMS_RESOLUTION = 256VAE_PARAMS_IN_CHANNELS = 3VAE_PARAMS_OUT_CH = 3VAE_PARAMS_CH = 128VAE_PARAMS_CH_MULT = [1, 2, 4, 4]VAE_PARAMS_NUM_RES_BLOCKS = 2
# V2V2_UNET_PARAMS_ATTENTION_HEAD_DIM = [5, 10, 20, 20]V2_UNET_PARAMS_CONTEXT_DIM = 1024# V2_UNET_PARAMS_USE_LINEAR_PROJECTION = True
TOKENIZER_V1_MODEL_NAME = "CompVis/stable-diffusion-v1-4"TOKENIZER_V2_MODEL_NAME = "stabilityai/stable-diffusion-2-1"
AVAILABLE_SCHEDULERS = Literal["ddim", "ddpm", "lms", "euler_a", "euler", "uniPC"]
SDXL_TEXT_ENCODER_TYPE = Union[CLIPTextModel, CLIPTextModelWithProjection]
DIFFUSERS_CACHE_DIR = None # if you want to change the cache dir, change this
def load_checkpoint_with_text_encoder_conversion(ckpt_path: str, device="cpu"): # text encoderの格納形式が違うモデルに対応する ('text_model'がない) TEXT_ENCODER_KEY_REPLACEMENTS = [ ( "cond_stage_model.transformer.embeddings.", "cond_stage_model.transformer.text_model.embeddings.", ), ( "cond_stage_model.transformer.encoder.", "cond_stage_model.transformer.text_model.encoder.", ), ( "cond_stage_model.transformer.final_layer_norm.", "cond_stage_model.transformer.text_model.final_layer_norm.", ), ]
if ckpt_path.endswith(".safetensors"): checkpoint = None state_dict = load_file(ckpt_path) # , device) # may causes error else: checkpoint = torch.load(ckpt_path, map_location=device) if "state_dict" in checkpoint: state_dict = checkpoint["state_dict"] else: state_dict = checkpoint checkpoint = None
key_reps = [] for rep_from, rep_to in TEXT_ENCODER_KEY_REPLACEMENTS: for key in state_dict.keys(): if key.startswith(rep_from): new_key = rep_to + key[len(rep_from) :] key_reps.append((key, new_key))
for key, new_key in key_reps: state_dict[new_key] = state_dict[key] del state_dict[key]
return checkpoint, state_dict
def create_unet_diffusers_config(v2, use_linear_projection_in_v2=False): """ Creates a config for the diffusers based on the config of the LDM model. """ # unet_params = original_config.model.params.unet_config.params
block_out_channels = [ UNET_PARAMS_MODEL_CHANNELS * mult for mult in UNET_PARAMS_CHANNEL_MULT ]
down_block_types = [] resolution = 1 for i in range(len(block_out_channels)): block_type = ( "CrossAttnDownBlock2D" if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS else "DownBlock2D" ) down_block_types.append(block_type) if i != len(block_out_channels) - 1: resolution *= 2
up_block_types = [] for i in range(len(block_out_channels)): block_type = ( "CrossAttnUpBlock2D" if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS else "UpBlock2D" ) up_block_types.append(block_type) resolution //= 2
config = dict( sample_size=UNET_PARAMS_IMAGE_SIZE, in_channels=UNET_PARAMS_IN_CHANNELS, out_channels=UNET_PARAMS_OUT_CHANNELS, down_block_types=tuple(down_block_types), up_block_types=tuple(up_block_types), block_out_channels=tuple(block_out_channels), layers_per_block=UNET_PARAMS_NUM_RES_BLOCKS, cross_attention_dim=UNET_PARAMS_CONTEXT_DIM if not v2 else V2_UNET_PARAMS_CONTEXT_DIM, attention_head_dim=UNET_PARAMS_NUM_HEADS if not v2 else V2_UNET_PARAMS_ATTENTION_HEAD_DIM, # use_linear_projection=UNET_PARAMS_USE_LINEAR_PROJECTION if not v2 else V2_UNET_PARAMS_USE_LINEAR_PROJECTION, ) if v2 and use_linear_projection_in_v2: config["use_linear_projection"] = True
return config
def load_diffusers_model( pretrained_model_name_or_path: str, v2: bool = False, clip_skip: Optional[int] = None, weight_dtype: torch.dtype = torch.float32,) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel,]: if v2: tokenizer = CLIPTokenizer.from_pretrained( TOKENIZER_V2_MODEL_NAME, subfolder="tokenizer", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ) text_encoder = CLIPTextModel.from_pretrained( pretrained_model_name_or_path, subfolder="text_encoder", # default is clip skip 2 num_hidden_layers=24 - (clip_skip - 1) if clip_skip is not None else 23, torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ) else: tokenizer = CLIPTokenizer.from_pretrained( TOKENIZER_V1_MODEL_NAME, subfolder="tokenizer", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ) text_encoder = CLIPTextModel.from_pretrained( pretrained_model_name_or_path, subfolder="text_encoder", num_hidden_layers=12 - (clip_skip - 1) if clip_skip is not None else 12, torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, )
unet = UNet2DConditionModel.from_pretrained( pretrained_model_name_or_path, subfolder="unet", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, )
vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
return tokenizer, text_encoder, unet, vae
def load_checkpoint_model( checkpoint_path: str, v2: bool = False, clip_skip: Optional[int] = None, weight_dtype: torch.dtype = torch.float32,) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel,]: pipe = StableDiffusionPipeline.from_single_file( checkpoint_path, upcast_attention=True if v2 else False, torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, )
_, state_dict = load_checkpoint_with_text_encoder_conversion(checkpoint_path) unet_config = create_unet_diffusers_config(v2, use_linear_projection_in_v2=v2) unet_config["class_embed_type"] = None unet_config["addition_embed_type"] = None converted_unet_checkpoint = convert_ldm_unet_checkpoint(state_dict, unet_config) unet = UNet2DConditionModel(**unet_config) unet.load_state_dict(converted_unet_checkpoint)
tokenizer = pipe.tokenizer text_encoder = pipe.text_encoder vae = pipe.vae if clip_skip is not None: if v2: text_encoder.config.num_hidden_layers = 24 - (clip_skip - 1) else: text_encoder.config.num_hidden_layers = 12 - (clip_skip - 1)
del pipe
return tokenizer, text_encoder, unet, vae
def load_models( pretrained_model_name_or_path: str, scheduler_name: str, v2: bool = False, v_pred: bool = False, weight_dtype: torch.dtype = torch.float32,) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel, SchedulerMixin,]: if pretrained_model_name_or_path.endswith( ".ckpt" ) or pretrained_model_name_or_path.endswith(".safetensors"): tokenizer, text_encoder, unet, vae = load_checkpoint_model( pretrained_model_name_or_path, v2=v2, weight_dtype=weight_dtype ) else: # diffusers tokenizer, text_encoder, unet, vae = load_diffusers_model( pretrained_model_name_or_path, v2=v2, weight_dtype=weight_dtype )
if scheduler_name: scheduler = create_noise_scheduler( scheduler_name, prediction_type="v_prediction" if v_pred else "epsilon", ) else: scheduler = None
return tokenizer, text_encoder, unet, scheduler, vae
def load_diffusers_model_xl( pretrained_model_name_or_path: str, weight_dtype: torch.dtype = torch.float32,) -> Tuple[List[CLIPTokenizer], List[SDXL_TEXT_ENCODER_TYPE], UNet2DConditionModel,]: # returns tokenizer, tokenizer_2, text_encoder, text_encoder_2, unet
tokenizers = [ CLIPTokenizer.from_pretrained( pretrained_model_name_or_path, subfolder="tokenizer", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ), CLIPTokenizer.from_pretrained( pretrained_model_name_or_path, subfolder="tokenizer_2", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, pad_token_id=0, # same as open clip ), ]
text_encoders = [ CLIPTextModel.from_pretrained( pretrained_model_name_or_path, subfolder="text_encoder", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ), CLIPTextModelWithProjection.from_pretrained( pretrained_model_name_or_path, subfolder="text_encoder_2", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ), ]
unet = UNet2DConditionModel.from_pretrained( pretrained_model_name_or_path, subfolder="unet", torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, ) vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae") return tokenizers, text_encoders, unet, vae
def load_checkpoint_model_xl( checkpoint_path: str, weight_dtype: torch.dtype = torch.float32,) -> Tuple[List[CLIPTokenizer], List[SDXL_TEXT_ENCODER_TYPE], UNet2DConditionModel,]: pipe = StableDiffusionXLPipeline.from_single_file( checkpoint_path, torch_dtype=weight_dtype, cache_dir=DIFFUSERS_CACHE_DIR, )
unet = pipe.unet vae = pipe.vae tokenizers = [pipe.tokenizer, pipe.tokenizer_2] text_encoders = [pipe.text_encoder, pipe.text_encoder_2] if len(text_encoders) == 2: text_encoders[1].pad_token_id = 0
del pipe
return tokenizers, text_encoders, unet, vae
def load_models_xl( pretrained_model_name_or_path: str, scheduler_name: str, weight_dtype: torch.dtype = torch.float32, noise_scheduler_kwargs=None,) -> Tuple[ List[CLIPTokenizer], List[SDXL_TEXT_ENCODER_TYPE], UNet2DConditionModel, SchedulerMixin,]: if pretrained_model_name_or_path.endswith( ".ckpt" ) or pretrained_model_name_or_path.endswith(".safetensors"): (tokenizers, text_encoders, unet, vae) = load_checkpoint_model_xl( pretrained_model_name_or_path, weight_dtype ) else: # diffusers (tokenizers, text_encoders, unet, vae) = load_diffusers_model_xl( pretrained_model_name_or_path, weight_dtype ) if scheduler_name: scheduler = create_noise_scheduler(scheduler_name, noise_scheduler_kwargs) else: scheduler = None
return tokenizers, text_encoders, unet, scheduler, vae
def create_noise_scheduler( scheduler_name: AVAILABLE_SCHEDULERS = "ddpm", noise_scheduler_kwargs=None, prediction_type: Literal["epsilon", "v_prediction"] = "epsilon",) -> SchedulerMixin: name = scheduler_name.lower().replace(" ", "_") if name.lower() == "ddim": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/ddim scheduler = DDIMScheduler(**OmegaConf.to_container(noise_scheduler_kwargs)) elif name.lower() == "ddpm": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/ddpm scheduler = DDPMScheduler(**OmegaConf.to_container(noise_scheduler_kwargs)) elif name.lower() == "lms": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/lms_discrete scheduler = LMSDiscreteScheduler( **OmegaConf.to_container(noise_scheduler_kwargs) ) elif name.lower() == "euler_a": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/euler_ancestral scheduler = EulerAncestralDiscreteScheduler( **OmegaConf.to_container(noise_scheduler_kwargs) ) elif name.lower() == "euler": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/euler_ancestral scheduler = EulerDiscreteScheduler( **OmegaConf.to_container(noise_scheduler_kwargs) ) elif name.lower() == "unipc": # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/unipc scheduler = UniPCMultistepScheduler( **OmegaConf.to_container(noise_scheduler_kwargs) ) else: raise ValueError(f"Unknown scheduler name: {name}")
return scheduler
def torch_gc(): import gc
gc.collect() if torch.cuda.is_available(): with torch.cuda.device("cuda"): torch.cuda.empty_cache() torch.cuda.ipc_collect()
from enum import Enum
class CPUState(Enum): GPU = 0 CPU = 1 MPS = 2
cpu_state = CPUState.GPUxpu_available = Falsedirectml_enabled = False
def is_intel_xpu(): global cpu_state global xpu_available if cpu_state == CPUState.GPU: if xpu_available: return True return False
try: import intel_extension_for_pytorch as ipex
if torch.xpu.is_available(): xpu_available = Trueexcept: pass
try: if torch.backends.mps.is_available(): cpu_state = CPUState.MPS import torch.mpsexcept: pass
def get_torch_device(): global directml_enabled global cpu_state if directml_enabled: global directml_device return directml_device if cpu_state == CPUState.MPS: return torch.device("mps") if cpu_state == CPUState.CPU: return torch.device("cpu") else: if is_intel_xpu(): return torch.device("xpu") else: return torch.device(torch.cuda.current_device())21 unmodified lines2223242526272812 unmodified lines414243444546474853 unmodified lines102103104105106107108373 unmodified lines48248348448548648779 unmodified lines5675685695705715725739 unmodified lines58358458558658758834 unmodified lines623624625626627628629128 unmodified lines75875976076176276325 unmodified lines78979079179279379456 unmodified lines851852853854855856174 unmodified lines10311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105421 unmodified linesimport PIL.Imageimport torchimport torch.nn.functional as Ffrom transformers import CLIPTokenizerfrom diffusers.image_processor import PipelineImageInput12 unmodified linesfrom diffusers.utils.import_utils import is_xformers_availablefrom ip_adapter.resampler import Resamplerfrom ip_adapter.attention_processor import AttnProcessor, IPAttnProcessorfrom ip_adapter.attention_processor import region_controllogger = logging.get_logger(__name__) # pylint: disable=invalid-name53 unmodified lines```"""from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineclass LongPromptWeight(object):373 unmodified linesprompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)return prompt_embedsclass StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline):79 unmodified linesif isinstance(attn_processor, IPAttnProcessor):attn_processor.scale = scaledef _encode_prompt_image_emb(self, prompt_image_emb, device, dtype, do_classifier_free_guidance):if isinstance(prompt_image_emb, torch.Tensor):prompt_image_emb = prompt_image_emb.clone().detach()9 unmodified linesprompt_image_emb = torch.cat([prompt_image_emb], dim=0)prompt_image_emb = self.image_proj_model(prompt_image_emb)return prompt_image_emb@torch.no_grad()34 unmodified linesclip_skip: Optional[int] = None,callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,callback_on_step_end_tensor_inputs: List[str] = ["latents"],control_mask = None,**kwargs,):r"""128 unmodified linesIf `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,otherwise a `tuple` is returned containing the output images."""lpw = LongPromptWeight()callback = kwargs.pop("callback", None)25 unmodified linesmult * [control_guidance_start],mult * [control_guidance_end],)# 1. Check inputs. Raise error if not correctself.check_inputs(56 unmodified lines# 3.2 Encode image promptprompt_image_emb = self._encode_prompt_image_emb(image_embeds,device,self.unet.dtype,self.do_classifier_free_guidance)174 unmodified linescontrolnet_cond_scale = controlnet_cond_scale[0]cond_scale = controlnet_cond_scale * controlnet_keep[i]down_block_res_samples, mid_block_res_sample = self.controlnet(control_model_input,t,encoder_hidden_states=prompt_image_emb,controlnet_cond=image,conditioning_scale=cond_scale,guess_mode=guess_mode,added_cond_kwargs=controlnet_added_cond_kwargs,return_dict=False,)# controlnet maskif control_mask_wight_image_list is not None:down_block_res_samples = [down_block_res_sample * mask_weightfor down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)]mid_block_res_sample *= control_mask_wight_image_list[-1]if guess_mode and self.do_classifier_free_guidance:# Infered ControlNet only for the conditional batch.21 unmodified lines22232425262712 unmodified lines40414243444546474849505153 unmodified lines105106107108109110111373 unmodified lines48548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751879 unmodified lines5985996006016026036049 unmodified lines61461561661761861962062162262362434 unmodified lines659660661662663664665666667668669670671128 unmodified lines80080180280380480580625 unmodified lines83283383483583683783883984084156 unmodified lines898899900901902903904174 unmodified lines10791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113521 unmodified linesimport PIL.Imageimport torchimport torch.nn.functional as Ffrom diffusers.image_processor import PipelineImageInput12 unmodified linesfrom diffusers.utils.import_utils import is_xformers_availablefrom ip_adapter.resampler import Resamplerfrom ip_adapter.utils import is_torch2_availableif is_torch2_available():from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessorelse:from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessorfrom ip_adapter.attention_processor import region_controllogger = logging.get_logger(__name__) # pylint: disable=invalid-name53 unmodified lines```"""from transformers import CLIPTokenizerfrom diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineclass LongPromptWeight(object):373 unmodified linesprompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)return prompt_embedsdef draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):stickwidth = 4limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])kps = np.array(kps)w, h = image_pil.sizeout_img = np.zeros([h, w, 3])for i in range(len(limbSeq)):index = limbSeq[i]color = color_list[index[0]]x = kps[index][:, 0]y = kps[index][:, 1]length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)out_img = (out_img * 0.6).astype(np.uint8)for idx_kp, kp in enumerate(kps):color = color_list[idx_kp]x, y = kpout_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))return out_img_pilclass StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline):79 unmodified linesif isinstance(attn_processor, IPAttnProcessor):attn_processor.scale = scaledef _encode_prompt_image_emb(self, prompt_image_emb, device, num_images_per_prompt, dtype, do_classifier_free_guidance):if isinstance(prompt_image_emb, torch.Tensor):prompt_image_emb = prompt_image_emb.clone().detach()9 unmodified linesprompt_image_emb = torch.cat([prompt_image_emb], dim=0)prompt_image_emb = self.image_proj_model(prompt_image_emb)bs_embed, seq_len, _ = prompt_image_emb.shapeprompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)return prompt_image_emb@torch.no_grad()34 unmodified linesclip_skip: Optional[int] = None,callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,callback_on_step_end_tensor_inputs: List[str] = ["latents"],# IP adapterip_adapter_scale=None,# Enhance Face Regioncontrol_mask = None,**kwargs,):r"""128 unmodified linesIf `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,otherwise a `tuple` is returned containing the output images."""lpw = LongPromptWeight()callback = kwargs.pop("callback", None)25 unmodified linesmult * [control_guidance_start],mult * [control_guidance_end],)# 0. set ip_adapter_scaleif ip_adapter_scale is not None:self.set_ip_adapter_scale(ip_adapter_scale)# 1. Check inputs. Raise error if not correctself.check_inputs(56 unmodified lines# 3.2 Encode image promptprompt_image_emb = self._encode_prompt_image_emb(image_embeds,device,num_images_per_prompt,self.unet.dtype,self.do_classifier_free_guidance)174 unmodified linescontrolnet_cond_scale = controlnet_cond_scale[0]cond_scale = controlnet_cond_scale * controlnet_keep[i]if isinstance(self.controlnet, MultiControlNetModel):down_block_res_samples_list, mid_block_res_sample_list = [], []for control_index in range(len(self.controlnet.nets)):controlnet = self.controlnet.nets[control_index]if control_index == 0:# assume fhe first controlnet is IdentityNetcontrolnet_prompt_embeds = prompt_image_embelse:controlnet_prompt_embeds = prompt_embedsdown_block_res_samples, mid_block_res_sample = controlnet(control_model_input,t,encoder_hidden_states=controlnet_prompt_embeds,controlnet_cond=image[control_index],conditioning_scale=cond_scale[control_index],guess_mode=guess_mode,added_cond_kwargs=controlnet_added_cond_kwargs,return_dict=False)# controlnet maskif control_index == 0 and control_mask_wight_image_list is not None:down_block_res_samples = [down_block_res_sample * mask_weightfor down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)]mid_block_res_sample *= control_mask_wight_image_list[-1]down_block_res_samples_list.append(down_block_res_samples)mid_block_res_sample_list.append(mid_block_res_sample)mid_block_res_sample = torch.stack(mid_block_res_sample_list).sum(dim=0)down_block_res_samples = [torch.stack(down_block_res_samples).sum(dim=0) for down_block_res_samples inzip(*down_block_res_samples_list)]else:down_block_res_samples, mid_block_res_sample = self.controlnet(control_model_input,t,encoder_hidden_states=prompt_image_emb,controlnet_cond=image,conditioning_scale=cond_scale,guess_mode=guess_mode,added_cond_kwargs=controlnet_added_cond_kwargs,return_dict=False,)# controlnet maskif control_mask_wight_image_list is not None:down_block_res_samples = [down_block_res_sample * mask_weightfor down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)]mid_block_res_sample *= control_mask_wight_image_list[-1]if guess_mode and self.do_classifier_free_guidance:# Infered ControlNet only for the conditional batch.
12345673 unmodified lines11121314diffusers==0.25.0torch==2.0.0torchvision==0.15.1transformers==4.36.2acceleratesafetensorseinops3 unmodified linespefthuggingface-hub==0.20.2opencv-pythoninsightface12345673 unmodified lines1112131415161718diffusers==0.25.1torch==2.0.0torchvision==0.15.1transformers==4.37.1acceleratesafetensorseinops3 unmodified linespefthuggingface-hub==0.20.2opencv-pythoninsightfacegradiocontrolnet_auxgdownpeft
app.py+284-128
controlnet_util.pyAdded+39
gradio_cached_examples/25/Generated Image/2880a3d19ef9b42e3ed2/image.pngDeleted

Large File Pointer Details
- SHA256: 573444e88e4bf4ab7bf4a693cf53cea3988366f4ca35b41523bf7c027802d0a6
- Pointer size: 132 Bytes
- Size of remote file: 2.57 MB
gradio_cached_examples/25/Generated Image/38dde1388c41109c5d39/image.pngDeleted

Large File Pointer Details
- SHA256: c4e80ada96212f1acd058324b25602dc611de920de9e710c26286e751a5f1a9a
- Pointer size: 132 Bytes
- Size of remote file: 2.31 MB
gradio_cached_examples/25/Generated Image/6cb5a3af223906666bfd/image.pngDeleted

Large File Pointer Details
- SHA256: f4b7543b3b1fd8ae301ee77c8479a7b3170e2ee063cd501a04e5e8ecc38417f6
- Pointer size: 132 Bytes
- Size of remote file: 2.28 MB
gradio_cached_examples/25/Generated Image/7e6ea85f77dd925d842c/image.pngDeleted

Large File Pointer Details
- SHA256: abde3e97dc47d0b95f9909b2575834d6792db49816e5b40b0c8474a48fe467b2
- Pointer size: 132 Bytes
- Size of remote file: 2.38 MB
gradio_cached_examples/25/Generated Image/e56b029833685ff77e6a/image.pngDeleted

Large File Pointer Details
- SHA256: 2f0992f67fe4839bffb56cf3c527e08c652406c55729257374ee8d630ac21501
- Pointer size: 132 Bytes
- Size of remote file: 2.69 MB
gradio_cached_examples/25/log.csvDeleted-6
ip_adapter/attention_processor.py+146-8
model_util.pyAdded+472
pipeline_stable_diffusion_xl_instantid.py → pipeline_stable_diffusion_xl_instantid_full.pyRenamed+102-21
requirements.txt+7-3