zsxkib / instant-id

Make realistic images of real people instantly

  • Public
  • 828.5K runs
  • L40S
  • GitHub
  • Paper
  • License

Input

*file
Preview
image

Input face image

file
Preview
pose_image

(Optional) reference pose image

string
Shift + Return to add a new line

Input prompt

Default: "a person"

string
Shift + Return to add a new line

Input Negative Prompt

Default: ""

string

Pick which base weights you want to use

Default: "stable-diffusion-xl-base-1.0"

integer
(minimum: 640, maximum: 4096)

Width of the input image for face detection

Default: 640

integer
(minimum: 640, maximum: 4096)

Height of the input image for face detection

Default: 640

string

Scheduler

Default: "EulerDiscreteScheduler"

integer
(minimum: 1, maximum: 500)

Number of denoising steps

Default: 30

number
(minimum: 1, maximum: 50)

Scale for classifier-free guidance

Default: 7.5

number
(minimum: 0, maximum: 1.5)

Scale for image adapter strength (for detail)

Default: 0.8

number
(minimum: 0, maximum: 1.5)

Scale for IdentityNet strength (for fidelity)

Default: 0.8

boolean

Enable Openpose ControlNet, overrides strength if set to false

Default: true

number
(minimum: 0, maximum: 1)

Openpose ControlNet strength, effective only if `enable_pose_controlnet` is true

Default: 0.4

boolean

Enable Canny ControlNet, overrides strength if set to false

Default: false

number
(minimum: 0, maximum: 1)

Canny ControlNet strength, effective only if `enable_canny_controlnet` is true

Default: 0.3

boolean

Enable Depth ControlNet, overrides strength if set to false

Default: false

number
(minimum: 0, maximum: 1)

Depth ControlNet strength, effective only if `enable_depth_controlnet` is true

Default: 0.5

boolean

Enable Fast Inference with LCM (Latent Consistency Models) - speeds up inference steps, trade-off is the quality of the generated image. Performs better with close-up portrait face images

Default: false

integer
(minimum: 1, maximum: 10)

Only used when `enable_lcm` is set to True, Number of denoising steps when using LCM

Default: 5

number
(minimum: 1, maximum: 20)

Only used when `enable_lcm` is set to True, Scale for classifier-free guidance when using LCM

Default: 1.5

boolean

Enhance non-face region

Default: true

string

Format of the output images

Default: "webp"

integer
(minimum: 0, maximum: 100)

Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality.

Default: 80

integer

Random seed. Leave blank to randomize the seed

integer
(minimum: 1, maximum: 8)

Number of images to output

Default: 1

boolean

This model’s safety checker can’t be disabled when running on the website. Learn more about platform safety on Replicate.

Disable safety checker for generated images

Default: false

Output

output
Generated in

This example was created by a different version, zsxkib/instant-id:f1ca369d.

Run time and cost

This model costs approximately $0.034 to run on Replicate, or 29 runs per $1, but this varies depending on your inputs. It is also open source and you can run it on your own computer with Docker.

This model runs on Nvidia L40S GPU hardware. Predictions typically complete within 36 seconds. The predict time for this model varies significantly based on the inputs.

Readme

InstantID

InstantID : Zero-shot Identity-Preserving Generation in Seconds

InstantID is a new state-of-the-art tuning-free method to achieve ID-Preserving generation with only single image, supporting various downstream tasks.

Release

Demos

Replicate ModelScope

Stylized Synthesis

Comparison with Previous Works

Comparison with existing tuning-free state-of-the-art techniques. InstantID achieves better fidelity and retain good text editability (faces and styles blend better).

Comparison with pre-trained character LoRAs. We don’t need multiple images and still can achieve competitive results as LoRAs without any training.

Comparison with InsightFace Swapper (also known as ROOP or Refactor). However, in non-realistic style, our work is more flexible on the integration of face and background.

Download

You can directly download the model from Huggingface. You also can download the model in python script:

from huggingface_hub import hf_hub_download
hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/config.json", local_dir="./checkpoints")
hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/diffusion_pytorch_model.safetensors", local_dir="./checkpoints")
hf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints")

If you cannot access to Huggingface, you can use hf-mirror to download models.

export HF_ENDPOINT=https://hf-mirror.com
huggingface-cli download --resume-download InstantX/InstantID --local-dir checkpoints

For face encoder, you need to manually download via this URL to models/antelopev2 as the default link is invalid. Once you have prepared all models, the folder tree should be like:

  .
  β”œβ”€β”€ models
  β”œβ”€β”€ checkpoints
  β”œβ”€β”€ ip_adapter
  β”œβ”€β”€ pipeline_stable_diffusion_xl_instantid.py
  └── README.md

Usage

# !pip install opencv-python transformers accelerate insightface
import diffusers
from diffusers.utils import load_image
from diffusers.models import ControlNetModel

import cv2
import torch
import numpy as np
from PIL import Image

from insightface.app import FaceAnalysis
from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps

# prepare 'antelopev2' under ./models
app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))

# prepare models under ./checkpoints
face_adapter = f'./checkpoints/ip-adapter.bin'
controlnet_path = f'./checkpoints/ControlNetModel'

# load IdentityNet
controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)

base_model = 'wangqixun/YamerMIX_v8'  # from https://civitai.com/models/84040?modelVersionId=196039
pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
    base_model,
    controlnet=controlnet,
    torch_dtype=torch.float16
)
pipe.cuda()

# load adapter
pipe.load_ip_adapter_instantid(face_adapter)

Then, you can customized your own face images

# load an image
face_image = load_image("./examples/yann-lecun_resize.jpg")

# prepare face emb
face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))
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 face
face_emb = face_info['embedding']
face_kps = draw_kps(face_image, face_info['kps'])

# prompt
prompt = "film noir style, ink sketch|vector, male man, highly detailed, sharp focus, ultra sharpness, monochrome, high contrast, dramatic shadows, 1940s style, mysterious, cinematic"
negative_prompt = "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, vibrant, colorful"

# generate image
image = pipe(
    prompt,
    image_embeds=face_emb,
    image=face_kps,
    controlnet_conditioning_scale=0.8,
    ip_adapter_scale=0.8,
).images[0]

Speed Up with LCM-LoRA

Our work is compatible with LCM-LoRA. First, download the model.

from huggingface_hub import hf_hub_download
hf_hub_download(repo_id="latent-consistency/lcm-lora-sdxl", filename="pytorch_lora_weights.safetensors", local_dir="./checkpoints")

To use it, you just need to load it and infer with a small num_inference_steps. Note that it is recommendated to set guidance_scale between [0, 1].

from diffusers import LCMScheduler

lcm_lora_path = "./checkpoints/pytorch_lora_weights.safetensors"

pipe.load_lora_weights(lcm_lora_path)
pipe.fuse_lora()
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)

num_inference_steps = 10
guidance_scale = 0

Start a local gradio demo

Run the following command:

python gradio_demo/app.py

Usage Tips

  • For higher similarity, increase the weight of controlnet_conditioning_scale (IdentityNet) and ip_adapter_scale (Adapter).
  • For over-saturation, decrease the ip_adapter_scale. If not work, decrease controlnet_conditioning_scale.
  • For higher text control ability, decrease ip_adapter_scale.
  • For specific styles, choose corresponding base model makes differences.
  • We have not supported multi-person yet, will only use the largest face as reference pose.

Community Resources

Gradio Demo

Replicate Demo

ComfyUI

Windows

Acknowledgements

Disclaimer

The code of InstantID is released under Apache License for both academic and commercial usage. However, both manual-downloading and auto-downloading face models from insightface are for non-commercial research purposes only accoreding to their license. Users are granted the freedom to create images using this tool, but they are obligated to comply with local laws and utilize it responsibly. The developers will not assume any responsibility for potential misuse by users.

Star History

Star History Chart

Cite

If you find InstantID useful for your research and applications, please cite us using this 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}
}