Instructions to use Aitrepreneur/InstantID-Controlnet with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use Aitrepreneur/InstantID-Controlnet with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("Aitrepreneur/InstantID-Controlnet", dtype=torch.bfloat16, device_map="cuda") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
Upload 128 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+4
- README.mdAdded+14
- app.pyAdded+675
- checkpoints/ControlNetModel/config.jsonAdded+57
- checkpoints/ControlNetModel/diffusion_pytorch_model.safetensorsAdded+3
- checkpoints/ip-adapter.binAdded+3
- depth_anything/__pycache__/blocks.cpython-310.pycAdded
- depth_anything/__pycache__/dpt.cpython-310.pycAdded
- depth_anything/blocks.pyAdded+153
- depth_anything/dpt.pyAdded+187
- depth_anything/util/__pycache__/transform.cpython-310.pycAdded
- depth_anything/util/transform.pyAdded+248
- examples/.DS_StoreAdded
- examples/kaifu_resize.pngAdded
- examples/musk_resize.jpegAdded
- examples/poses/pose.jpgAdded
- examples/poses/pose2.jpgAdded
- examples/poses/pose3.jpgAdded
- examples/poses/pose4.jpgAdded
- examples/sam_resize.pngAdded
- examples/schmidhuber_resize.pngAdded
- examples/yann-lecun_resize.jpgAdded
- ip_adapter/__pycache__/attention_processor.cpython-310.pycAdded
- ip_adapter/__pycache__/resampler.cpython-310.pycAdded
- ip_adapter/__pycache__/utils.cpython-310.pycAdded
- ip_adapter/attention_processor.pyAdded+446
- ip_adapter/resampler.pyAdded+121
- ip_adapter/utils.pyAdded+5
- models/antelopev2/1k3d68.onnxAdded+3
- models/antelopev2/2d106det.onnxAdded+3
- models/antelopev2/genderage.onnxAdded+3
- models/antelopev2/glintr100.onnxAdded+3
- models/antelopev2/scrfd_10g_bnkps.onnxAdded+3
- pipeline_stable_diffusion_xl_instantid_full.pyAdded+1204
- requirements.txtAdded+16
- style_template.pyAdded+155
- torchhub/README.mdAdded+3
- torchhub/facebookresearch_dinov2_main/CODE_OF_CONDUCT.mdAdded+80
- torchhub/facebookresearch_dinov2_main/CONTRIBUTING.mdAdded+31
- torchhub/facebookresearch_dinov2_main/LICENSEAdded+400
- torchhub/facebookresearch_dinov2_main/MODEL_CARD.mdAdded+201
- torchhub/facebookresearch_dinov2_main/README.mdAdded+277
- torchhub/facebookresearch_dinov2_main/__pycache__/hubconf.cpython-310.pycAdded
- torchhub/facebookresearch_dinov2_main/__pycache__/vision_transformer.cpython-310.pycAdded
- torchhub/facebookresearch_dinov2_main/conda.yamlAdded+22
- torchhub/facebookresearch_dinov2_main/dinov2/__init__.pyAdded+7
- torchhub/facebookresearch_dinov2_main/dinov2/__pycache__/__init__.cpython-310.pycAdded
- torchhub/facebookresearch_dinov2_main/dinov2/configs/__init__.pyAdded+23
- torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitb14_pretrain.yamlAdded+6
- torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitg14_pretrain.yamlAdded+7
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/kaifu_resize.png filter=lfs diff=lfs merge=lfs -textexamples/sam_resize.png filter=lfs diff=lfs merge=lfs -textexamples/schmidhuber_resize.png filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text
1234567891011121314---title: InstantIDemoji: 😻colorFrom: graycolorTo: graysdk: gradiosdk_version: 4.15.0app_file: app.pypinned: falselicense: apache-2.0disable_embedding: true---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675import osimport cv2import math#import spacesimport torchimport randomimport numpy as npimport argparse
import PILfrom PIL import Imagefrom typing import Tuple
import diffusersfrom diffusers.utils import load_imagefrom diffusers.models import ControlNetModelfrom diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
from huggingface_hub import hf_hub_download
import insightfacefrom insightface.app import FaceAnalysis
from style_template import stylesfrom pipeline_stable_diffusion_xl_instantid_full import StableDiffusionXLInstantIDPipeline, draw_kps
from controlnet_aux import OpenposeDetector
import gradio as gr
from depth_anything.dpt import DepthAnythingfrom depth_anything.util.transform import Resize, NormalizeImage, PrepareForNet
import torch.nn.functional as Ffrom torchvision.transforms import Compose
# global variableMAX_SEED = np.iinfo(np.int32).maxdevice = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32STYLE_NAMES = list(styles.keys())DEFAULT_STYLE_NAME = "Spring Festival"enable_lcm_arg = False
# download checkpointsfrom 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")
# Load face encoderapp = FaceAnalysis( name="antelopev2", root="./", providers=["CPUExecutionProvider"],)app.prepare(ctx_id=0, det_size=(640, 640))
openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
depth_anything = DepthAnything.from_pretrained('LiheYoung/depth_anything_vitl14').to(device).eval()
transform = Compose([ Resize( width=518, height=518, resize_target=False, keep_aspect_ratio=True, ensure_multiple_of=14, resize_method='lower_bound', image_interpolation_method=cv2.INTER_CUBIC, ), NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), PrepareForNet(),])
# 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-pose/canny/depthcontrolnet_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)
def get_depth_map(image): image = np.array(image) / 255.0
h, w = image.shape[:2]
image = transform({'image': image})['image'] image = torch.from_numpy(image).unsqueeze(0).to("cuda")
with torch.no_grad(): depth = depth_anything(image)
depth = F.interpolate(depth[None], (h, w), mode='bilinear', align_corners=False)[0, 0] depth = (depth - depth.min()) / (depth.max() - depth.min()) * 255.0
depth = depth.cpu().numpy().astype(np.uint8)
depth_image = Image.fromarray(depth)
return depth_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")
controlnet_map = { "pose": controlnet_pose, "canny": controlnet_canny, "depth": controlnet_depth,}controlnet_map_fn = { "pose": openpose, "canny": get_canny_image, "depth": get_depth_map,}
#base_model_path = "wangqixun/YamerMIX_v8"
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--inbrowser', action='store_true', help='Open in browser') parser.add_argument('--server_port', type=int, default=7860, help='Server port') parser.add_argument('--share', action='store_true', help='Share the Gradio UI') parser.add_argument('--model_path', type=str, default='stablediffusionapi/juggernaut-xl-v8', help='Base model path') parser.add_argument('--medvram', action='store_true', help='Medium VRAM settings') parser.add_argument('--lowvram', action='store_true', help='Low VRAM settings')
args = parser.parse_args()
base_model_path = args.model_path
pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( base_model_path, controlnet=[controlnet_identitynet], torch_dtype=dtype, safety_checker=None, feature_extractor=None,).to(device)
pipe.scheduler = diffusers.EulerDiscreteScheduler.from_config( pipe.scheduler.config)
# load and disable LCMpipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")pipe.disable_lora()
pipe.cuda()pipe.load_ip_adapter_instantid(face_adapter)pipe.image_proj_model.to("cuda")pipe.unet.to("cuda")
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 seed
def remove_tips(): return gr.update(visible=False)
def get_example(): case = [ [ "./examples/yann-lecun_resize.jpg", None, "a man", "Spring Festival", "(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", ], ] return case
def run_for_examples(face_file, pose_file, prompt, style, negative_prompt): return generate_image( face_file, pose_file, prompt, negative_prompt, style, 20, # num_steps 0.8, # identitynet_strength_ratio 0.8, # adapter_strength_ratio 0.4, # pose_strength 0.3, # canny_strength 0.5, # depth_strength ["pose", "canny"], # controlnet_selection 5.0, # guidance_scale 42, # seed "EulerDiscreteScheduler", # scheduler False, # enable_LCM True, # 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, min_side=1024, size=None, pad_to_max_side=False, mode=PIL.Image.BILINEAR, base_pixel_number=64,): w, h = input_image.size if size is not None: w_resize_new, h_resize_new = size else: ratio = min_side / min(h, w) w, h = round(ratio * w), round(ratio * h) ratio = max_side / max(h, w) input_image = input_image.resize([round(ratio * w), round(ratio * h)], mode) w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number input_image = input_image.resize([w_resize_new, h_resize_new], mode)
if pad_to_max_side: res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255 offset_x = (max_side - w_resize_new) // 2 offset_y = (max_side - h_resize_new) // 2 res[ 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_image
def 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, pose_image_path, prompt, 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"] = True if 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"
# apply the style template prompt, 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.shape
# Extract face features face_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 face face_emb = face_info["embedding"] face_kps = draw_kps(convert_from_cv2_to_image(face_image_cv2), face_info["kps"]) img_controlnet = face_image if 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_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( 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"])
width, height = face_kps.size
if enhance_face_region: control_mask = np.zeros([height, width, 3]) x1, y1, x2, y2 = face_info["bbox"] x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) control_mask[y1:y2, x1:x2] = 255 control_mask = Image.fromarray(control_mask.astype(np.uint8)) else: control_mask = None
if 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_identitynet control_scales = float(identitynet_strength_ratio) control_images = face_kps
generator = torch.Generator(device=device).manual_seed(seed)
print("Start inference...") print(f"[Debug] Prompt: {prompt}, \n[Debug] Neg Prompt: {negative_prompt}")
pipe.set_ip_adapter_scale(adapter_strength_ratio) images = pipe( prompt=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, width=width, generator=generator, ).images
return images[0], gr.update(visible=True) def clear_cuda_cache(): if torch.cuda.is_available(): torch.cuda.empty_cache() # Descriptiontitle = r"""<h1 align="center">InstantID: Zero-shot Identity-Preserving Generation in Seconds</h1>"""
description = r"""<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>
We are organizing a Spring Festival event with HuggingFace from 2.7 to 2.25, and you can now generate pictures of Spring Festival costumes. Happy Dragon Year 🐲 ! Share the joy with your family.<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"""---📝 **Citation**<br>If 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**<br>If you have any questions, please feel free to open an issue or directly reach us out at <b>haofanwang.ai@gmail.com</b>."""
tips = 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 = """.gradio-container {width: 85% !important}"""with gr.Blocks(css=css) as demo: # description gr.Markdown(title) gr.Markdown(description)
with gr.Row(): with gr.Column(): with gr.Row(equal_height=True): # upload face image face_file = gr.Image( label="Upload a photo of your face", type="filepath" ) # optional: upload a reference pose image pose_file = gr.Image( label="Upload a reference pose image (Optional)", type="filepath", )
# prompt prompt = 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, )
# strength identitynet_strength_ratio = gr.Slider( label="IdentityNet strength (for fidelity)", minimum=0, maximum=1.5, step=0.05, value=0.80, ) adapter_strength_ratio = gr.Slider( label="Image adapter strength (for detail)", minimum=0, maximum=1.5, step=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", minimum=0, maximum=MAX_SEED, step=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], outputs=seed, queue=False, api_name=False, ).then( fn=generate_image, inputs=[ face_file, pose_file, prompt, 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], ).then( fn=clear_cuda_cache )
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=False, )
gr.Markdown(article)
demo.launch(inbrowser=args.inbrowser, server_port=args.server_port, share=args.share)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657{ "_class_name": "ControlNetModel", "_diffusers_version": "0.21.2", "_name_or_path": "/mnt/nj-aigc/usr/guiwan/workspace/diffusion_output/face_xl_ipc_v4_2_XiezhenAnimeForeigner/checkpoint-150000/ControlNetModel", "act_fn": "silu", "addition_embed_type": "text_time", "addition_embed_type_num_heads": 64, "addition_time_embed_dim": 256, "attention_head_dim": [ 5, 10, 20 ], "block_out_channels": [ 320, 640, 1280 ], "class_embed_type": null, "conditioning_channels": 3, "conditioning_embedding_out_channels": [ 16, 32, 96, 256 ], "controlnet_conditioning_channel_order": "rgb", "cross_attention_dim": 2048, "down_block_types": [ "DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D" ], "downsample_padding": 1, "encoder_hid_dim": null, "encoder_hid_dim_type": null, "flip_sin_to_cos": true, "freq_shift": 0, "global_pool_conditions": false, "in_channels": 4, "layers_per_block": 2, "mid_block_scale_factor": 1, "norm_eps": 1e-05, "norm_num_groups": 32, "num_attention_heads": null, "num_class_embeds": null, "only_cross_attention": false, "projection_class_embeddings_input_dim": 2816, "resnet_time_scale_shift": "default", "transformer_layers_per_block": [ 1, 2, 10 ], "upcast_attention": null, "use_linear_projection": true}123version https://git-lfs.github.com/spec/v1oid sha256:c8127be9f174101ebdafee9964d856b49b634435cf6daa396d3f593cf0bbbb05size 2502139136123version https://git-lfs.github.com/spec/v1oid sha256:02b3618e36d803784166660520098089a81388e61a93ef8002aa79a5b1c546e1size 1691134141123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import torch.nn as nn
def _make_scratch(in_shape, out_shape, groups=1, expand=False): scratch = nn.Module()
out_shape1 = out_shape out_shape2 = out_shape out_shape3 = out_shape if len(in_shape) >= 4: out_shape4 = out_shape
if expand: out_shape1 = out_shape out_shape2 = out_shape*2 out_shape3 = out_shape*4 if len(in_shape) >= 4: out_shape4 = out_shape*8
scratch.layer1_rn = nn.Conv2d( in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer2_rn = nn.Conv2d( in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) scratch.layer3_rn = nn.Conv2d( in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups ) if len(in_shape) >= 4: scratch.layer4_rn = nn.Conv2d( in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups )
return scratch
class ResidualConvUnit(nn.Module): """Residual convolution module. """
def __init__(self, features, activation, bn): """Init.
Args: features (int): number of features """ super().__init__()
self.bn = bn
self.groups=1
self.conv1 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups ) self.conv2 = nn.Conv2d( features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups )
if self.bn==True: self.bn1 = nn.BatchNorm2d(features) self.bn2 = nn.BatchNorm2d(features)
self.activation = activation
self.skip_add = nn.quantized.FloatFunctional()
def forward(self, x): """Forward pass.
Args: x (tensor): input
Returns: tensor: output """ out = self.activation(x) out = self.conv1(out) if self.bn==True: out = self.bn1(out) out = self.activation(out) out = self.conv2(out) if self.bn==True: out = self.bn2(out)
if self.groups > 1: out = self.conv_merge(out)
return self.skip_add.add(out, x)
class FeatureFusionBlock(nn.Module): """Feature fusion block. """
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None): """Init.
Args: features (int): number of features """ super(FeatureFusionBlock, self).__init__()
self.deconv = deconv self.align_corners = align_corners
self.groups=1
self.expand = expand out_features = features if self.expand==True: out_features = features//2 self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
self.resConfUnit1 = ResidualConvUnit(features, activation, bn) self.resConfUnit2 = ResidualConvUnit(features, activation, bn) self.skip_add = nn.quantized.FloatFunctional()
self.size=size
def forward(self, *xs, size=None): """Forward pass.
Returns: tensor: output """ output = xs[0]
if len(xs) == 2: res = self.resConfUnit1(xs[1]) output = self.skip_add.add(output, res)
output = self.resConfUnit2(output)
if (size is None) and (self.size is None): modifier = {"scale_factor": 2} elif size is None: modifier = {"size": self.size} else: modifier = {"size": size}
output = nn.functional.interpolate( output, **modifier, mode="bilinear", align_corners=self.align_corners )
output = self.out_conv(output)
return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187import argparseimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom huggingface_hub import PyTorchModelHubMixin, hf_hub_download
from depth_anything.blocks import FeatureFusionBlock, _make_scratch
def _make_fusion_block(features, use_bn, size = None): return FeatureFusionBlock( features, nn.ReLU(False), deconv=False, bn=use_bn, expand=False, align_corners=True, size=size, )
class DPTHead(nn.Module): def __init__(self, nclass, in_channels, features=256, use_bn=False, out_channels=[256, 512, 1024, 1024], use_clstoken=False): super(DPTHead, self).__init__() self.nclass = nclass self.use_clstoken = use_clstoken self.projects = nn.ModuleList([ nn.Conv2d( in_channels=in_channels, out_channels=out_channel, kernel_size=1, stride=1, padding=0, ) for out_channel in out_channels ]) self.resize_layers = nn.ModuleList([ nn.ConvTranspose2d( in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0), nn.ConvTranspose2d( in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0), nn.Identity(), nn.Conv2d( in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1) ]) if use_clstoken: self.readout_projects = nn.ModuleList() for _ in range(len(self.projects)): self.readout_projects.append( nn.Sequential( nn.Linear(2 * in_channels, in_channels), nn.GELU())) self.scratch = _make_scratch( out_channels, features, groups=1, expand=False, )
self.scratch.stem_transpose = None self.scratch.refinenet1 = _make_fusion_block(features, use_bn) self.scratch.refinenet2 = _make_fusion_block(features, use_bn) self.scratch.refinenet3 = _make_fusion_block(features, use_bn) self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
head_features_1 = features head_features_2 = 32 if nclass > 1: self.scratch.output_conv = nn.Sequential( nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(head_features_1, nclass, kernel_size=1, stride=1, padding=0), ) else: self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1) self.scratch.output_conv2 = nn.Sequential( nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0), nn.ReLU(True), nn.Identity(), ) def forward(self, out_features, patch_h, patch_w): out = [] for i, x in enumerate(out_features): if self.use_clstoken: x, cls_token = x[0], x[1] readout = cls_token.unsqueeze(1).expand_as(x) x = self.readout_projects[i](torch.cat((x, readout), -1)) else: x = x[0] x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) x = self.projects[i](x) x = self.resize_layers[i](x) out.append(x) layer_1, layer_2, layer_3, layer_4 = out layer_1_rn = self.scratch.layer1_rn(layer_1) layer_2_rn = self.scratch.layer2_rn(layer_2) layer_3_rn = self.scratch.layer3_rn(layer_3) layer_4_rn = self.scratch.layer4_rn(layer_4) path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:]) path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:]) path_1 = self.scratch.refinenet1(path_2, layer_1_rn) out = self.scratch.output_conv1(path_1) out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True) out = self.scratch.output_conv2(out) return out class DPT_DINOv2(nn.Module): def __init__(self, encoder='vitl', features=256, out_channels=[256, 512, 1024, 1024], use_bn=False, use_clstoken=False, localhub=True): super(DPT_DINOv2, self).__init__() assert encoder in ['vits', 'vitb', 'vitl'] # in case the Internet connection is not stable, please load the DINOv2 locally if localhub: self.pretrained = torch.hub.load('torchhub/facebookresearch_dinov2_main', 'dinov2_{:}14'.format(encoder), source='local', pretrained=False) else: self.pretrained = torch.hub.load('facebookresearch/dinov2', 'dinov2_{:}14'.format(encoder)) dim = self.pretrained.blocks[0].attn.qkv.in_features self.depth_head = DPTHead(1, dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken) def forward(self, x): h, w = x.shape[-2:] features = self.pretrained.get_intermediate_layers(x, 4, return_class_token=True) patch_h, patch_w = h // 14, w // 14
depth = self.depth_head(features, patch_h, patch_w) depth = F.interpolate(depth, size=(h, w), mode="bilinear", align_corners=True) depth = F.relu(depth)
return depth.squeeze(1)
class DepthAnything(DPT_DINOv2, PyTorchModelHubMixin): def __init__(self, config): super().__init__(**config)
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--encoder", default="vits", type=str, choices=["vits", "vitb", "vitl"], ) args = parser.parse_args() model = DepthAnything.from_pretrained("LiheYoung/depth_anything_{:}14".format(args.encoder)) print(model) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248import randomfrom PIL import Image, ImageOps, ImageFilterimport torchfrom torchvision import transformsimport torch.nn.functional as F
import numpy as npimport cv2import math
def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA): """Rezise the sample to ensure the given size. Keeps aspect ratio.
Args: sample (dict): sample size (tuple): image size
Returns: tuple: new size """ shape = list(sample["disparity"].shape)
if shape[0] >= size[0] and shape[1] >= size[1]: return sample
scale = [0, 0] scale[0] = size[0] / shape[0] scale[1] = size[1] / shape[1]
scale = max(scale)
shape[0] = math.ceil(scale * shape[0]) shape[1] = math.ceil(scale * shape[1])
# resize sample["image"] = cv2.resize( sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method )
sample["disparity"] = cv2.resize( sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST ) sample["mask"] = cv2.resize( sample["mask"].astype(np.float32), tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST, ) sample["mask"] = sample["mask"].astype(bool)
return tuple(shape)
class Resize(object): """Resize sample to given size (width, height). """
def __init__( self, width, height, resize_target=True, keep_aspect_ratio=False, ensure_multiple_of=1, resize_method="lower_bound", image_interpolation_method=cv2.INTER_AREA, ): """Init.
Args: width (int): desired output width height (int): desired output height resize_target (bool, optional): True: Resize the full sample (image, mask, target). False: Resize image only. Defaults to True. keep_aspect_ratio (bool, optional): True: Keep the aspect ratio of the input sample. Output sample might not have the given width and height, and resize behaviour depends on the parameter 'resize_method'. Defaults to False. ensure_multiple_of (int, optional): Output width and height is constrained to be multiple of this parameter. Defaults to 1. resize_method (str, optional): "lower_bound": Output will be at least as large as the given size. "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.) "minimal": Scale as least as possible. (Output size might be smaller than given size.) Defaults to "lower_bound". """ self.__width = width self.__height = height
self.__resize_target = resize_target self.__keep_aspect_ratio = keep_aspect_ratio self.__multiple_of = ensure_multiple_of self.__resize_method = resize_method self.__image_interpolation_method = image_interpolation_method
def constrain_to_multiple_of(self, x, min_val=0, max_val=None): y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
if max_val is not None and y > max_val: y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
if y < min_val: y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
return y
def get_size(self, width, height): # determine new height and width scale_height = self.__height / height scale_width = self.__width / width
if self.__keep_aspect_ratio: if self.__resize_method == "lower_bound": # scale such that output size is lower bound if scale_width > scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "upper_bound": # scale such that output size is upper bound if scale_width < scale_height: # fit width scale_height = scale_width else: # fit height scale_width = scale_height elif self.__resize_method == "minimal": # scale as least as possbile if abs(1 - scale_width) < abs(1 - scale_height): # fit width scale_height = scale_width else: # fit height scale_width = scale_height else: raise ValueError( f"resize_method {self.__resize_method} not implemented" )
if self.__resize_method == "lower_bound": new_height = self.constrain_to_multiple_of( scale_height * height, min_val=self.__height ) new_width = self.constrain_to_multiple_of( scale_width * width, min_val=self.__width ) elif self.__resize_method == "upper_bound": new_height = self.constrain_to_multiple_of( scale_height * height, max_val=self.__height ) new_width = self.constrain_to_multiple_of( scale_width * width, max_val=self.__width ) elif self.__resize_method == "minimal": new_height = self.constrain_to_multiple_of(scale_height * height) new_width = self.constrain_to_multiple_of(scale_width * width) else: raise ValueError(f"resize_method {self.__resize_method} not implemented")
return (new_width, new_height)
def __call__(self, sample): width, height = self.get_size( sample["image"].shape[1], sample["image"].shape[0] )
# resize sample sample["image"] = cv2.resize( sample["image"], (width, height), interpolation=self.__image_interpolation_method, )
if self.__resize_target: if "disparity" in sample: sample["disparity"] = cv2.resize( sample["disparity"], (width, height), interpolation=cv2.INTER_NEAREST, )
if "depth" in sample: sample["depth"] = cv2.resize( sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST )
if "semseg_mask" in sample: # sample["semseg_mask"] = cv2.resize( # sample["semseg_mask"], (width, height), interpolation=cv2.INTER_NEAREST # ) sample["semseg_mask"] = F.interpolate(torch.from_numpy(sample["semseg_mask"]).float()[None, None, ...], (height, width), mode='nearest').numpy()[0, 0] if "mask" in sample: sample["mask"] = cv2.resize( sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST, ) # sample["mask"] = sample["mask"].astype(bool)
# print(sample['image'].shape, sample['depth'].shape) return sample
class NormalizeImage(object): """Normlize image by given mean and std. """
def __init__(self, mean, std): self.__mean = mean self.__std = std
def __call__(self, sample): sample["image"] = (sample["image"] - self.__mean) / self.__std
return sample
class PrepareForNet(object): """Prepare sample for usage as network input. """
def __init__(self): pass
def __call__(self, sample): image = np.transpose(sample["image"], (2, 0, 1)) sample["image"] = np.ascontiguousarray(image).astype(np.float32)
if "mask" in sample: sample["mask"] = sample["mask"].astype(np.float32) sample["mask"] = np.ascontiguousarray(sample["mask"]) if "depth" in sample: depth = sample["depth"].astype(np.float32) sample["depth"] = np.ascontiguousarray(depth) if "semseg_mask" in sample: sample["semseg_mask"] = sample["semseg_mask"].astype(np.float32) sample["semseg_mask"] = np.ascontiguousarray(sample["semseg_mask"])
return sample123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.pyimport torchimport torch.nn as nnimport torch.nn.functional as F
try: import xformers import xformers.ops xformers_available = Trueexcept Exception as e: xformers_available = False
class 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. """ def __init__( self, hidden_size=None, cross_attention_dim=None, ): super().__init__()
def forward( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_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 ) attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
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_states elif 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)
query = attn.head_to_batch_dim(query) key = attn.head_to_batch_dim(key) value = attn.head_to_batch_dim(value)
attention_probs = attn.get_attention_scores(query, key, attention_mask) hidden_states = torch.bmm(attention_probs, value) hidden_states = attn.batch_to_head_dim(hidden_states)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_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 + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states class IPAttnProcessor(nn.Module): r""" Attention processor for IP-Adapater. 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__()
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.scale = scale self.num_tokens = num_tokens
self.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_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_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 ) attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
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_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_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)
query = attn.head_to_batch_dim(query) key = attn.head_to_batch_dim(key) value = attn.head_to_batch_dim(value)
if xformers_available: hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask) else: attention_probs = attn.get_attention_scores(query, key, attention_mask) hidden_states = torch.bmm(attention_probs, value) hidden_states = attn.batch_to_head_dim(hidden_states) # for ip-adapter ip_key = self.to_k_ip(ip_hidden_states) ip_value = self.to_v_ip(ip_hidden_states) ip_key = attn.head_to_batch_dim(ip_key) ip_value = attn.head_to_batch_dim(ip_value) if xformers_available: ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None) else: ip_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 control if 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.5 mask = 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 * mask
hidden_states = hidden_states + self.scale * ip_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_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 + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
def _memory_efficient_attention_xformers(self, query, key, value, attention_mask): # TODO attention_mask query = query.contiguous() key = key.contiguous() value = value.contiguous() hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask) # hidden_states = self.reshape_batch_dim_to_heads(hidden_states) return hidden_states
class AttnProcessor2_0(torch.nn.Module): r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). """ def __init__( self, hidden_size=None, cross_attention_dim=None, ): 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.")
def forward( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_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_states elif 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.heads
query = 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.1 hidden_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)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_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 + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class 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_size self.cross_attention_dim = cross_attention_dim self.scale = scale self.num_tokens = num_tokens
self.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_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_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_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_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.heads
query = 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.1 hidden_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-adapter ip_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.1 ip_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 control if 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.5 mask = 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 * mask
hidden_states = hidden_states + self.scale * ip_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_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 + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.pyimport math
import torchimport torch.nn as nn
# FFNdef FeedForward(dim, mult=4): inner_dim = int(dim * mult) return nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, inner_dim, bias=False), nn.GELU(), nn.Linear(inner_dim, dim, bias=False), ) def reshape_tensor(x, heads): bs, length, width = x.shape #(bs, length, width) --> (bs, length, n_heads, dim_per_head) x = x.view(bs, length, heads, -1) # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) x = x.transpose(1, 2) # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) x = x.reshape(bs, heads, length, -1) return x
class PerceiverAttention(nn.Module): def __init__(self, *, dim, dim_head=64, heads=8): super().__init__() self.scale = dim_head**-0.5 self.dim_head = dim_head self.heads = heads inner_dim = dim_head * heads
self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim)
self.to_q = nn.Linear(dim, inner_dim, bias=False) self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, dim, bias=False)
def forward(self, x, latents): """ Args: x (torch.Tensor): image features shape (b, n1, D) latent (torch.Tensor): latent features shape (b, n2, D) """ x = self.norm1(x) latents = self.norm2(latents) b, l, _ = latents.shape
q = self.to_q(latents) kv_input = torch.cat((x, latents), dim=-2) k, v = self.to_kv(kv_input).chunk(2, dim=-1) q = reshape_tensor(q, self.heads) k = reshape_tensor(k, self.heads) v = reshape_tensor(v, self.heads)
# attention scale = 1 / math.sqrt(math.sqrt(self.dim_head)) weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) out = weight @ v out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
return self.to_out(out)
class Resampler(nn.Module): def __init__( self, dim=1024, depth=8, dim_head=64, heads=16, num_queries=8, embedding_dim=768, output_dim=1024, ff_mult=4, ): super().__init__() self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5) self.proj_in = nn.Linear(embedding_dim, dim)
self.proj_out = nn.Linear(dim, output_dim) self.norm_out = nn.LayerNorm(output_dim) self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append( nn.ModuleList( [ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), FeedForward(dim=dim, mult=ff_mult), ] ) )
def forward(self, x): latents = self.latents.repeat(x.size(0), 1, 1) x = self.proj_in(x) for attn, ff in self.layers: latents = attn(x, latents) + latents latents = ff(latents) + latents latents = self.proj_out(latents) return self.norm_out(latents)12345import torch.nn.functional as F
def is_torch2_available(): return hasattr(F, "scaled_dot_product_attention")123version https://git-lfs.github.com/spec/v1oid sha256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45ccsize 143607619123version https://git-lfs.github.com/spec/v1oid sha256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbfsize 5030888123version https://git-lfs.github.com/spec/v1oid sha256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fbsize 1322532123version https://git-lfs.github.com/spec/v1oid sha256:4ab1d6435d639628a6f3e5008dd4f929edf4c4124b1a7169e1048f9fef534cdfsize 260665334123version https://git-lfs.github.com/spec/v1oid sha256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91size 169238271234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204# Copyright 2024 The InstantX Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import cv2import math
import numpy as npimport PIL.Imageimport torchimport torch.nn.functional as F
from diffusers.image_processor import PipelineImageInput
from diffusers.models import ControlNetModel
from diffusers.utils import ( deprecate, logging, replace_example_docstring,)from diffusers.utils.torch_utils import is_compiled_module, is_torch_versionfrom diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
from diffusers import StableDiffusionXLControlNetPipelinefrom diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModelfrom diffusers.utils.import_utils import is_xformers_available
from ip_adapter.resampler import Resamplerfrom ip_adapter.utils import is_torch2_available
from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessorfrom ip_adapter.attention_processor import region_control
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
EXAMPLE_DOC_STRING = """ Examples: ```py >>> # !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
>>> # download 'antelopev2' under ./models >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) >>> app.prepare(ctx_id=0, det_size=(640, 640)) >>> # download 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) >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16 ... ) >>> pipe.cuda() >>> # load adapter >>> pipe.load_ip_adapter_instantid(face_adapter)
>>> prompt = "analog film photo of a man. faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage, masterpiece, best quality" >>> negative_prompt = "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured (lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch,deformed, mutated, cross-eyed, ugly, disfigured"
>>> # load an image >>> image = load_image("your-example.jpg") >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1] >>> face_emb = face_info['embedding'] >>> face_kps = draw_kps(face_image, face_info['kps']) >>> pipe.set_ip_adapter_scale(0.8)
>>> # generate image >>> image = pipe( ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8 ... ).images[0] ```"""
from transformers import CLIPTokenizerfrom diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineclass LongPromptWeight(object): """ Copied from https://github.com/huggingface/diffusers/blob/main/examples/community/lpw_stable_diffusion_xl.py """ def __init__(self) -> None: pass
def parse_prompt_attention(self, text): """ Parses a string with attention tokens and returns a list of pairs: text and its associated weight. Accepted tokens are: (abc) - increases attention to abc by a multiplier of 1.1 (abc:3.12) - increases attention to abc by a multiplier of 3.12 [abc] - decreases attention to abc by a multiplier of 1.1 \( - literal character '(' \[ - literal character '[' \) - literal character ')' \] - literal character ']' \\ - literal character '\' anything else - just text
>>> parse_prompt_attention('normal text') [['normal text', 1.0]] >>> parse_prompt_attention('an (important) word') [['an ', 1.0], ['important', 1.1], [' word', 1.0]] >>> parse_prompt_attention('(unbalanced') [['unbalanced', 1.1]] >>> parse_prompt_attention('\(literal\]') [['(literal]', 1.0]] >>> parse_prompt_attention('(unnecessary)(parens)') [['unnecessaryparens', 1.1]] >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).') [['a ', 1.0], ['house', 1.5730000000000004], [' ', 1.1], ['on', 1.0], [' a ', 1.1], ['hill', 0.55], [', sun, ', 1.1], ['sky', 1.4641000000000006], ['.', 1.1]] """ import re
re_attention = re.compile( r""" \\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)| \)|]|[^\\()\[\]:]+|: """, re.X, )
re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
res = [] round_brackets = [] square_brackets = []
round_bracket_multiplier = 1.1 square_bracket_multiplier = 1 / 1.1
def multiply_range(start_position, multiplier): for p in range(start_position, len(res)): res[p][1] *= multiplier
for m in re_attention.finditer(text): text = m.group(0) weight = m.group(1)
if text.startswith("\\"): res.append([text[1:], 1.0]) elif text == "(": round_brackets.append(len(res)) elif text == "[": square_brackets.append(len(res)) elif weight is not None and len(round_brackets) > 0: multiply_range(round_brackets.pop(), float(weight)) elif text == ")" and len(round_brackets) > 0: multiply_range(round_brackets.pop(), round_bracket_multiplier) elif text == "]" and len(square_brackets) > 0: multiply_range(square_brackets.pop(), square_bracket_multiplier) else: parts = re.split(re_break, text) for i, part in enumerate(parts): if i > 0: res.append(["BREAK", -1]) res.append([part, 1.0])
for pos in round_brackets: multiply_range(pos, round_bracket_multiplier)
for pos in square_brackets: multiply_range(pos, square_bracket_multiplier)
if len(res) == 0: res = [["", 1.0]]
# merge runs of identical weights i = 0 while i + 1 < len(res): if res[i][1] == res[i + 1][1]: res[i][0] += res[i + 1][0] res.pop(i + 1) else: i += 1
return res
def get_prompts_tokens_with_weights(self, clip_tokenizer: CLIPTokenizer, prompt: str): """ Get prompt token ids and weights, this function works for both prompt and negative prompt
Args: pipe (CLIPTokenizer) A CLIPTokenizer prompt (str) A prompt string with weights
Returns: text_tokens (list) A list contains token ids text_weight (list) A list contains the correspodent weight of token ids
Example: import torch from transformers import CLIPTokenizer
clip_tokenizer = CLIPTokenizer.from_pretrained( "stablediffusionapi/deliberate-v2" , subfolder = "tokenizer" , dtype = torch.float16 )
token_id_list, token_weight_list = get_prompts_tokens_with_weights( clip_tokenizer = clip_tokenizer ,prompt = "a (red:1.5) cat"*70 ) """ texts_and_weights = self.parse_prompt_attention(prompt) text_tokens, text_weights = [], [] for word, weight in texts_and_weights: # tokenize and discard the starting and the ending token token = clip_tokenizer(word, truncation=False).input_ids[1:-1] # so that tokenize whatever length prompt # the returned token is a 1d list: [320, 1125, 539, 320]
# merge the new tokens to the all tokens holder: text_tokens text_tokens = [*text_tokens, *token]
# each token chunk will come with one weight, like ['red cat', 2.0] # need to expand weight for each token. chunk_weights = [weight] * len(token)
# append the weight back to the weight holder: text_weights text_weights = [*text_weights, *chunk_weights] return text_tokens, text_weights
def group_tokens_and_weights(self, token_ids: list, weights: list, pad_last_block=False): """ Produce tokens and weights in groups and pad the missing tokens
Args: token_ids (list) The token ids from tokenizer weights (list) The weights list from function get_prompts_tokens_with_weights pad_last_block (bool) Control if fill the last token list to 75 tokens with eos Returns: new_token_ids (2d list) new_weights (2d list)
Example: token_groups,weight_groups = group_tokens_and_weights( token_ids = token_id_list , weights = token_weight_list ) """ bos, eos = 49406, 49407
# this will be a 2d list new_token_ids = [] new_weights = [] while len(token_ids) >= 75: # get the first 75 tokens head_75_tokens = [token_ids.pop(0) for _ in range(75)] head_75_weights = [weights.pop(0) for _ in range(75)]
# extract token ids and weights temp_77_token_ids = [bos] + head_75_tokens + [eos] temp_77_weights = [1.0] + head_75_weights + [1.0]
# add 77 token and weights chunk to the holder list new_token_ids.append(temp_77_token_ids) new_weights.append(temp_77_weights)
# padding the left if len(token_ids) >= 0: padding_len = 75 - len(token_ids) if pad_last_block else 0
temp_77_token_ids = [bos] + token_ids + [eos] * padding_len + [eos] new_token_ids.append(temp_77_token_ids)
temp_77_weights = [1.0] + weights + [1.0] * padding_len + [1.0] new_weights.append(temp_77_weights)
return new_token_ids, new_weights
def get_weighted_text_embeddings_sdxl( self, pipe: StableDiffusionXLPipeline, prompt: str = "", prompt_2: str = None, neg_prompt: str = "", neg_prompt_2: str = None, prompt_embeds=None, negative_prompt_embeds=None, pooled_prompt_embeds=None, negative_pooled_prompt_embeds=None, extra_emb=None, extra_emb_alpha=0.6, ): """ This function can process long prompt with weights, no length limitation for Stable Diffusion XL
Args: pipe (StableDiffusionPipeline) prompt (str) prompt_2 (str) neg_prompt (str) neg_prompt_2 (str) Returns: prompt_embeds (torch.Tensor) neg_prompt_embeds (torch.Tensor) """ # if prompt_embeds is not None and \ negative_prompt_embeds is not None and \ pooled_prompt_embeds is not None and \ negative_pooled_prompt_embeds is not None: return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
if prompt_2: prompt = f"{prompt} {prompt_2}"
if neg_prompt_2: neg_prompt = f"{neg_prompt} {neg_prompt_2}"
eos = pipe.tokenizer.eos_token_id
# tokenizer 1 prompt_tokens, prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt) neg_prompt_tokens, neg_prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
# tokenizer 2 # prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, prompt) # neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, neg_prompt) # tokenizer 2 遇到 !! !!!! 等多感叹号和tokenizer 1的效果不一致 prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt) neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
# padding the shorter one for prompt set 1 prompt_token_len = len(prompt_tokens) neg_prompt_token_len = len(neg_prompt_tokens)
if prompt_token_len > neg_prompt_token_len: # padding the neg_prompt with eos token neg_prompt_tokens = neg_prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len) neg_prompt_weights = neg_prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len) else: # padding the prompt prompt_tokens = prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len) prompt_weights = prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
# padding the shorter one for token set 2 prompt_token_len_2 = len(prompt_tokens_2) neg_prompt_token_len_2 = len(neg_prompt_tokens_2)
if prompt_token_len_2 > neg_prompt_token_len_2: # padding the neg_prompt with eos token neg_prompt_tokens_2 = neg_prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2) neg_prompt_weights_2 = neg_prompt_weights_2 + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2) else: # padding the prompt prompt_tokens_2 = prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2) prompt_weights_2 = prompt_weights + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
embeds = [] neg_embeds = []
prompt_token_groups, prompt_weight_groups = self.group_tokens_and_weights(prompt_tokens.copy(), prompt_weights.copy())
neg_prompt_token_groups, neg_prompt_weight_groups = self.group_tokens_and_weights( neg_prompt_tokens.copy(), neg_prompt_weights.copy() )
prompt_token_groups_2, prompt_weight_groups_2 = self.group_tokens_and_weights( prompt_tokens_2.copy(), prompt_weights_2.copy() )
neg_prompt_token_groups_2, neg_prompt_weight_groups_2 = self.group_tokens_and_weights( neg_prompt_tokens_2.copy(), neg_prompt_weights_2.copy() )
# get prompt embeddings one by one is not working. for i in range(len(prompt_token_groups)): # get positive prompt embeddings with weights token_tensor = torch.tensor([prompt_token_groups[i]], dtype=torch.long, device=pipe.device) weight_tensor = torch.tensor(prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
token_tensor_2 = torch.tensor([prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
# use first text encoder prompt_embeds_1 = pipe.text_encoder(token_tensor.to(pipe.device), output_hidden_states=True) prompt_embeds_1_hidden_states = prompt_embeds_1.hidden_states[-2]
# use second text encoder prompt_embeds_2 = pipe.text_encoder_2(token_tensor_2.to(pipe.device), output_hidden_states=True) prompt_embeds_2_hidden_states = prompt_embeds_2.hidden_states[-2] pooled_prompt_embeds = prompt_embeds_2[0]
prompt_embeds_list = [prompt_embeds_1_hidden_states, prompt_embeds_2_hidden_states] token_embedding = torch.concat(prompt_embeds_list, dim=-1).squeeze(0)
for j in range(len(weight_tensor)): if weight_tensor[j] != 1.0: token_embedding[j] = ( token_embedding[-1] + (token_embedding[j] - token_embedding[-1]) * weight_tensor[j] )
token_embedding = token_embedding.unsqueeze(0) embeds.append(token_embedding)
# get negative prompt embeddings with weights neg_token_tensor = torch.tensor([neg_prompt_token_groups[i]], dtype=torch.long, device=pipe.device) neg_token_tensor_2 = torch.tensor([neg_prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device) neg_weight_tensor = torch.tensor(neg_prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
# use first text encoder neg_prompt_embeds_1 = pipe.text_encoder(neg_token_tensor.to(pipe.device), output_hidden_states=True) neg_prompt_embeds_1_hidden_states = neg_prompt_embeds_1.hidden_states[-2]
# use second text encoder neg_prompt_embeds_2 = pipe.text_encoder_2(neg_token_tensor_2.to(pipe.device), output_hidden_states=True) neg_prompt_embeds_2_hidden_states = neg_prompt_embeds_2.hidden_states[-2] negative_pooled_prompt_embeds = neg_prompt_embeds_2[0]
neg_prompt_embeds_list = [neg_prompt_embeds_1_hidden_states, neg_prompt_embeds_2_hidden_states] neg_token_embedding = torch.concat(neg_prompt_embeds_list, dim=-1).squeeze(0)
for z in range(len(neg_weight_tensor)): if neg_weight_tensor[z] != 1.0: neg_token_embedding[z] = ( neg_token_embedding[-1] + (neg_token_embedding[z] - neg_token_embedding[-1]) * neg_weight_tensor[z] )
neg_token_embedding = neg_token_embedding.unsqueeze(0) neg_embeds.append(neg_token_embedding)
prompt_embeds = torch.cat(embeds, dim=1) negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
if extra_emb is not None: extra_emb = extra_emb.to(prompt_embeds.device, dtype=prompt_embeds.dtype) * extra_emb_alpha prompt_embeds = torch.cat([prompt_embeds, extra_emb], 1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, torch.zeros_like(extra_emb)], 1) print(f'fix prompt_embeds, extra_emb_alpha={extra_emb_alpha}')
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
def get_prompt_embeds(self, *args, **kwargs): prompt_embeds, negative_prompt_embeds, _, _ = self.get_weighted_text_embeddings_sdxl(*args, **kwargs) prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) return prompt_embeds
def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]): stickwidth = 4 limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]]) kps = np.array(kps)
w, h = image_pil.size out_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.5 angle = 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 = kp out_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_pil class StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline): def cuda(self, dtype=torch.float16, use_xformers=False): self.to('cuda', dtype) if hasattr(self, 'image_proj_model'): self.image_proj_model.to(self.unet.device).to(self.unet.dtype) if use_xformers: if is_xformers_available(): import xformers from packaging import version
xformers_version = version.parse(xformers.__version__) if xformers_version == version.parse("0.0.16"): logger.warn( "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details." ) self.enable_xformers_memory_efficient_attention() else: raise ValueError("xformers is not available. Make sure it is installed correctly") def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=0.5): self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens) self.set_ip_adapter(model_ckpt, num_tokens, scale) def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16): image_proj_model = Resampler( dim=1280, depth=4, dim_head=64, heads=20, num_queries=num_tokens, embedding_dim=image_emb_dim, output_dim=self.unet.config.cross_attention_dim, ff_mult=4, )
image_proj_model.eval() self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype) state_dict = torch.load(model_ckpt, map_location="cpu") if 'image_proj' in state_dict: state_dict = state_dict["image_proj"] self.image_proj_model.load_state_dict(state_dict) self.image_proj_model_in_features = image_emb_dim def set_ip_adapter(self, model_ckpt, num_tokens, scale): unet = self.unet attn_procs = {} 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] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif 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().to(unet.device, dtype=unet.dtype) else: attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=scale, num_tokens=num_tokens).to(unet.device, dtype=unet.dtype) unet.set_attn_processor(attn_procs) state_dict = torch.load(model_ckpt, map_location="cpu") ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values()) if 'ip_adapter' in state_dict: state_dict = state_dict['ip_adapter'] ip_layers.load_state_dict(state_dict) def set_ip_adapter_scale(self, scale): unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet for attn_processor in unet.attn_processors.values(): if isinstance(attn_processor, IPAttnProcessor): attn_processor.scale = scale
def _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() else: prompt_image_emb = torch.tensor(prompt_image_emb) prompt_image_emb = prompt_image_emb.to(device=device, dtype=dtype) prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features]) if do_classifier_free_guidance: prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0) else: prompt_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.shape prompt_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() @replace_example_docstring(EXAMPLE_DOC_STRING) def __call__( self, prompt: Union[str, List[str]] = None, prompt_2: Optional[Union[str, List[str]]] = None, image: PipelineImageInput = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 5.0, negative_prompt: Optional[Union[str, List[str]]] = None, negative_prompt_2: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, pooled_prompt_embeds: Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, image_embeds: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, cross_attention_kwargs: Optional[Dict[str, Any]] = None, controlnet_conditioning_scale: Union[float, List[float]] = 1.0, guess_mode: bool = False, control_guidance_start: Union[float, List[float]] = 0.0, control_guidance_end: Union[float, List[float]] = 1.0, original_size: Tuple[int, int] = None, crops_coords_top_left: Tuple[int, int] = (0, 0), target_size: Tuple[int, int] = None, negative_original_size: Optional[Tuple[int, int]] = None, negative_crops_coords_top_left: Tuple[int, int] = (0, 0), negative_target_size: Optional[Tuple[int, int]] = None, clip_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 adapter ip_adapter_scale=None,
# Enhance Face Region control_mask = None,
**kwargs, ): r""" The call function to the pipeline for generation.
Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. prompt_2 (`str` or `List[str]`, *optional*): The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is used in both text-encoders. image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): The ControlNet input condition to provide guidance to the `unet` for generation. If the type is specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`, images must be passed as a list such that each element of the list can be correctly batched for input to a single ControlNet. height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): The height in pixels of the generated image. Anything below 512 pixels won't work well for [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) and checkpoints that are not specifically fine-tuned on low resolutions. width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): The width in pixels of the generated image. Anything below 512 pixels won't work well for [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) and checkpoints that are not specifically fine-tuned on low resolutions. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. guidance_scale (`float`, *optional*, defaults to 5.0): A higher guidance scale value encourages the model to generate images closely linked to the text `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide what to not include in image generation. If not defined, you need to pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). negative_prompt_2 (`str` or `List[str]`, *optional*): The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2` and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders. num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. eta (`float`, *optional*, defaults to 0.0): Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.FloatTensor`, *optional*): Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random `generator`. prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the `prompt` input argument. negative_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. pooled_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, pooled text embeddings are generated from `prompt` input argument. negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input argument. image_embeds (`torch.FloatTensor`, *optional*): Pre-generated image embeddings. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generated image. Choose between `PIL.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a plain tuple. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set the corresponding scale as a list. guess_mode (`bool`, *optional*, defaults to `False`): The ControlNet encoder tries to recognize the content of the input image even if you remove all prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended. control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): The percentage of total steps at which the ControlNet starts applying. control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): The percentage of total steps at which the ControlNet stops applying. original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled. `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): For most cases, `target_size` should be set to the desired height and width of the generated image. If not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): To negatively condition the generation process based on a specific image resolution. Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): To negatively condition the generation process based on a target image resolution. It should be as same as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. clip_skip (`int`, *optional*): Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings. callback_on_step_end (`Callable`, *optional*): A function that calls at the end of each denoising steps during the inference. The function is called with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`List`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the `._callback_tensor_inputs` attribute of your pipeine class.
Examples:
Returns: [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: If `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) callback_steps = kwargs.pop("callback_steps", None)
if callback is not None: deprecate( "callback", "1.0.0", "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`", ) if callback_steps is not None: deprecate( "callback_steps", "1.0.0", "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`", )
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
# align format for control guidance if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): control_guidance_start = len(control_guidance_end) * [control_guidance_start] elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): control_guidance_end = len(control_guidance_start) * [control_guidance_end] elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1 control_guidance_start, control_guidance_end = ( mult * [control_guidance_start], mult * [control_guidance_end], ) # 0. set ip_adapter_scale if ip_adapter_scale is not None: self.set_ip_adapter_scale(ip_adapter_scale)
# 1. Check inputs. Raise error if not correct self.check_inputs( prompt, prompt_2, image, callback_steps, negative_prompt, negative_prompt_2, prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, controlnet_conditioning_scale, control_guidance_start, control_guidance_end, callback_on_step_end_tensor_inputs, )
self._guidance_scale = guidance_scale self._clip_skip = clip_skip self._cross_attention_kwargs = cross_attention_kwargs
# 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0]
device = self._execution_device
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
global_pool_conditions = ( controlnet.config.global_pool_conditions if isinstance(controlnet, ControlNetModel) else controlnet.nets[0].config.global_pool_conditions ) guess_mode = guess_mode or global_pool_conditions
# 3.1 Encode input prompt ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = lpw.get_weighted_text_embeddings_sdxl( pipe=self, prompt=prompt, neg_prompt=negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, ) # 3.2 Encode image prompt prompt_image_emb = self._encode_prompt_image_emb(image_embeds, device, num_images_per_prompt, self.unet.dtype, self.do_classifier_free_guidance) # 4. Prepare image if isinstance(controlnet, ControlNetModel): image = self.prepare_image( image=image, width=width, height=height, batch_size=batch_size * num_images_per_prompt, num_images_per_prompt=num_images_per_prompt, device=device, dtype=controlnet.dtype, do_classifier_free_guidance=self.do_classifier_free_guidance, guess_mode=guess_mode, ) height, width = image.shape[-2:] elif isinstance(controlnet, MultiControlNetModel): images = []
for image_ in image: image_ = self.prepare_image( image=image_, width=width, height=height, batch_size=batch_size * num_images_per_prompt, num_images_per_prompt=num_images_per_prompt, device=device, dtype=controlnet.dtype, do_classifier_free_guidance=self.do_classifier_free_guidance, guess_mode=guess_mode, )
images.append(image_)
image = images height, width = image[0].shape[-2:] else: assert False
# 4.1 Region control if control_mask is not None: mask_weight_image = control_mask mask_weight_image = np.array(mask_weight_image) mask_weight_image_tensor = torch.from_numpy(mask_weight_image).to(device=device, dtype=prompt_embeds.dtype) mask_weight_image_tensor = mask_weight_image_tensor[:, :, 0] / 255. mask_weight_image_tensor = mask_weight_image_tensor[None, None] h, w = mask_weight_image_tensor.shape[-2:] control_mask_wight_image_list = [] for scale in [8, 8, 8, 16, 16, 16, 32, 32, 32]: scale_mask_weight_image_tensor = F.interpolate( mask_weight_image_tensor,(h // scale, w // scale), mode='bilinear') control_mask_wight_image_list.append(scale_mask_weight_image_tensor) region_mask = torch.from_numpy(np.array(control_mask)[:, :, 0]).to(self.unet.device, dtype=self.unet.dtype) / 255. region_control.prompt_image_conditioning = [dict(region_mask=region_mask)] else: control_mask_wight_image_list = None region_control.prompt_image_conditioning = [dict(region_mask=None)]
# 5. Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps self._num_timesteps = len(timesteps)
# 6. Prepare latent variables num_channels_latents = self.unet.config.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, )
# 6.5 Optionally get Guidance Scale Embedding timestep_cond = None if self.unet.config.time_cond_proj_dim is not None: guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt) timestep_cond = self.get_guidance_scale_embedding( guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim ).to(device=device, dtype=latents.dtype)
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
# 7.1 Create tensor stating which controlnets to keep controlnet_keep = [] for i in range(len(timesteps)): keeps = [ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) for s, e in zip(control_guidance_start, control_guidance_end) ] controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
# 7.2 Prepare added time ids & embeddings if isinstance(image, list): original_size = original_size or image[0].shape[-2:] else: original_size = original_size or image.shape[-2:] target_size = target_size or (height, width)
add_text_embeds = pooled_prompt_embeds if self.text_encoder_2 is None: text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1]) else: text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
add_time_ids = self._get_add_time_ids( original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype, text_encoder_projection_dim=text_encoder_projection_dim, )
if negative_original_size is not None and negative_target_size is not None: negative_add_time_ids = self._get_add_time_ids( negative_original_size, negative_crops_coords_top_left, negative_target_size, dtype=prompt_embeds.dtype, text_encoder_projection_dim=text_encoder_projection_dim, ) else: negative_add_time_ids = add_time_ids
if self.do_classifier_free_guidance: prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0) add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
prompt_embeds = prompt_embeds.to(device) add_text_embeds = add_text_embeds.to(device) add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1) encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
# 8. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order is_unet_compiled = is_compiled_module(self.unet) is_controlnet_compiled = is_compiled_module(self.controlnet) is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1") with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # Relevant thread: # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428 if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1: torch._inductor.cudagraph_mark_step_begin() # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
# controlnet(s) inference if guess_mode and self.do_classifier_free_guidance: # Infer ControlNet only for the conditional batch. control_model_input = latents control_model_input = self.scheduler.scale_model_input(control_model_input, t) controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] controlnet_added_cond_kwargs = { "text_embeds": add_text_embeds.chunk(2)[1], "time_ids": add_time_ids.chunk(2)[1], } else: control_model_input = latent_model_input controlnet_prompt_embeds = prompt_embeds controlnet_added_cond_kwargs = added_cond_kwargs if isinstance(controlnet_keep[i], list): cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] else: controlnet_cond_scale = controlnet_conditioning_scale if isinstance(controlnet_cond_scale, list): controlnet_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 IdentityNet controlnet_prompt_embeds = prompt_image_emb else: controlnet_prompt_embeds = prompt_embeds down_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 mask if control_index == 0 and control_mask_wight_image_list is not None: down_block_res_samples = [ down_block_res_sample * mask_weight for 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 in zip(*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 mask if control_mask_wight_image_list is not None: down_block_res_samples = [ down_block_res_sample * mask_weight for 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. # To apply the output of ControlNet to both the unconditional and conditional batches, # add 0 to the unconditional batch to keep it unchanged. down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
# predict the noise residual noise_pred = self.unet( latent_model_input, t, encoder_hidden_states=encoder_hidden_states, timestep_cond=timestep_cond, cross_attention_kwargs=self.cross_attention_kwargs, down_block_additional_residuals=down_block_res_samples, mid_block_additional_residual=mid_block_res_sample, added_cond_kwargs=added_cond_kwargs, return_dict=False, )[0]
# perform guidance if self.do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
if callback_on_step_end is not None: callback_kwargs = {} for k in callback_on_step_end_tensor_inputs: callback_kwargs[k] = locals()[k] callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = callback_outputs.pop("latents", latents) prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
# call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: step_idx = i // getattr(self.scheduler, "order", 1) callback(step_idx, t, latents) if not output_type == "latent": # make sure the VAE is in float32 mode, as it overflows in float16 needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast if needs_upcasting: self.upcast_vae() latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype) image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
# cast back to fp16 if needed if needs_upcasting: self.vae.to(dtype=torch.float16) else: image = latents
if not output_type == "latent": # apply watermark if available if self.watermark is not None: image = self.watermark.apply_watermark(image)
image = self.image_processor.postprocess(image, output_type=output_type)
# Offload all models self.maybe_free_model_hooks()
if not return_dict: return (image,)
return StableDiffusionXLPipelineOutput(images=image)12345678910111213141516diffusers==0.25.1transformers==4.37.1acceleratesafetensorseinopsonnxruntimespaces==0.19.4omegaconfpefthuggingface-hub==0.20.2opencv-pythoninsightfacegradiocontrolnet_auxgdownpeft123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155style_list = [ { "name": "(No style)", "prompt": "{prompt}", "negative_prompt": "", }, { "name": "Spring Festival", "prompt": "Flat illustration, a Chinese {prompt}, ancient style, wearing a red cloth, smile face, white skin, clean background, fireworks blooming, red lanterns", "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast, realistic, cropped, worst quality, missing fingers, extra digit, jpeg artifacts, signature, multiple, (lowres, low quality, worst quality:1.2)", }, { "name": "Watercolor", "prompt": "watercolor painting, {prompt}. vibrant, beautiful, painterly, detailed, textural, artistic", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", }, { "name": "Film Noir", "prompt": "film noir style, ink sketch|vector, {prompt} highly detailed, sharp focus, ultra sharpness, monochrome, high contrast, dramatic shadows, 1940s style, mysterious, cinematic", "negative_prompt": "(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", }, { "name": "Neon", "prompt": "masterpiece painting, buildings in the backdrop, kaleidoscope, lilac orange blue cream fuchsia bright vivid gradient colors, the scene is cinematic, {prompt}, emotional realism, double exposure, watercolor ink pencil, graded wash, color layering, magic realism, figurative painting, intricate motifs, organic tracery, polished", "negative_prompt": "(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", }, { "name": "Jungle", "prompt": 'waist-up "{prompt} in a Jungle" by Syd Mead, tangerine cold color palette, muted colors, detailed, 8k,photo r3al,dripping paint,3d toon style,3d style,Movie Still', "negative_prompt": "(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", }, { "name": "Mars", "prompt": "{prompt}, Post-apocalyptic. Mars Colony, Scavengers roam the wastelands searching for valuable resources, rovers, bright morning sunlight shining, (detailed) (intricate) (8k) (HDR) (cinematic lighting) (sharp focus)", "negative_prompt": "(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", }, { "name": "Vibrant Color", "prompt": "vibrant colorful, ink sketch|vector|2d colors, at nightfall, sharp focus, {prompt}, highly detailed, sharp focus, the clouds,colorful,ultra sharpness", "negative_prompt": "(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", }, { "name": "Snow", "prompt": "cinema 4d render, {prompt}, high contrast, vibrant and saturated, sico style, surrounded by magical glow,floating ice shards, snow crystals, cold, windy background, frozen natural landscape in background cinematic atmosphere,highly detailed, sharp focus, intricate design, 3d, unreal engine, octane render, CG best quality, highres, photorealistic, dramatic lighting, artstation, concept art, cinematic, epic Steven Spielberg movie still, sharp focus, smoke, sparks, art by pascal blanche and greg rutkowski and repin, trending on artstation, hyperrealism painting, matte painting, 4k resolution", "negative_prompt": "(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", }, { "name": "Line art", "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics", "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic", }, { "name": "Art Nouveau", "prompt": "Art Nouveau style, {prompt}, organic forms, curvilinear lines, elegant, nature-inspired, intricate patterns, flowing designs, soft colors", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, brutalism, geometric, harsh lines, noisy", }, { "name": "Cubism", "prompt": "cubist painting, {prompt}, abstract, geometric shapes, fragmented objects, multiple viewpoints, bold lines, reduced colors, Pablo Picasso inspired", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, smooth, flowing, noisy", }, { "name": "Minimalism", "prompt": "minimalist art, {prompt}, simple, clean lines, monochrome, negative space, minimal detail, geometric shapes, modern, sophisticated", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, baroque, cluttered, over-detailed, noisy", }, { "name": "Baroque", "prompt": "baroque style, {prompt}, grandeur, drama, contrast, rich colors, intense lighting, ornate, Caravaggio inspired, emotional, detailed", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, minimalist, flat, dull, noisy", }, { "name": "Expressionism", "prompt": "expressionist art, {prompt}, emotional, distorted, exaggerated, vivid colors, dynamic brushstrokes, subjective perspective, impactful", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealism, bland, underwhelming, noisy", }, { "name": "Digital Glitch", "prompt": "digital glitch art, {prompt}, corrupted image, tech-inspired, vibrant, surreal, abstract, pixelated, data moshing, futuristic", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, classical, realistic, smooth, noiseless", }, { "name": "Psychedelic", "prompt": "psychedelic art, {prompt}, vivid colors, hallucinatory patterns, surreal, fluid shapes, trippy, 1960s style, kaleidoscopic, vibrant", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, monochrome, simplistic, noiseless", }, { "name": "Victorian", "prompt": "Victorian style, {prompt}, elegant, ornate, romantic, historical, detailed patterns, rich textures, sophisticated, vintage", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, modern, minimalist, plain, noisy", }, { "name": "Graffiti", "prompt": "graffiti art, {prompt}, urban, street style, bold colors, spray paint, tagging, hip-hop culture, dynamic, expressive, contemporary", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, classical, fine art, noiseless, smooth", }, { "name": "Ukiyo-e", "prompt": "Ukiyo-e style, {prompt}, Japanese woodblock print, flat color areas, bold outlines, historical scenes, nature, Edo period, traditional", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, 3D, photorealistic, modern, noisy", }, { "name": "Retro Futurism", "prompt": "retro futurism, {prompt}, vibrant colors, geometric shapes, streamline design, 1950s and 1960s style, optimistic, space-age, visionary, neon lighting, bold typography", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, medieval, deformed, glitch, blurry, noisy", }, { "name": "Steampunk", "prompt": "steampunk style, {prompt}, Victorian era, industrial, mechanical gears, brass and copper, steam engines, intricate details, fantastical machines, sepia tones", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, neon, futuristic, blurry, noisy", }, { "name": "Cyberpunk", "prompt": "cyberpunk aesthetic, {prompt}, neon lights, urban dystopia, futuristic, high-tech, low-life, cybernetics, dark and gritty, vivid colors, digital world", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, medieval, steampunk, blurry, noisy", }, { "name": "Impressionist", "prompt": "impressionist style painting, {prompt}, vibrant, light brushstrokes, open composition, emphasis on light in its changing qualities, movement, ordinary subject matter", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", }, { "name": "Art Deco", "prompt": "art deco style, {prompt}, glamorous, elegant, functional, geometric patterns, bold colors, sleek lines, chrome, glass, shiny fabrics", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, rustic, medieval, deformed, glitch, noisy", }, { "name": "Fantasy", "prompt": "fantasy style, {prompt}, mythical creatures, enchanted forests, magic elements, dreamlike landscapes, vibrant colors, detailed, imaginative", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", }, { "name": "Gothic", "prompt": "gothic style, {prompt}, dark and moody, gothic architecture, medieval elements, dramatic lighting, somber tones, intricate details, mysterious atmosphere", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, neon, futuristic, blurry, noisy", }, { "name": "Pop Art", "prompt": "pop art style, {prompt}, bold colors, mass culture, comic style, ironic, whimsical, repetition of images, bright, high contrast", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, medieval, steampunk, blurry, noisy", }, { "name": "Surrealism", "prompt": "surrealist style, {prompt}, dreamlike, bizarre, irrational, abstract, imaginative, distorted reality, vivid, unexpected juxtapositions", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", }, { "name": "Abstract", "prompt": "abstract style, {prompt}, non-representational, shapes, forms, colors, lines, dynamic, modern, expressive, non-figurative, bold", "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", },]
styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}123# Local PyTorch Hub
This directory is for loading the DINOv2 encoder locally in case of no Internet connection.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we ascontributors and maintainers pledge to make participation in our project andour community a harassment-free experience for everyone, regardless of age, bodysize, disability, ethnicity, sex characteristics, gender identity and expression,level of experience, education, socio-economic status, nationality, personalappearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environmentinclude:
* Using welcoming and inclusive language* Being respectful of differing viewpoints and experiences* Gracefully accepting constructive criticism* Focusing on what is best for the community* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention oradvances* Trolling, insulting/derogatory comments, and personal or political attacks* Public or private harassment* Publishing others' private information, such as a physical or electronicaddress, without explicit permission* Other conduct which could reasonably be considered inappropriate in aprofessional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptablebehavior and are expected to take appropriate and fair corrective action inresponse to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, orreject comments, commits, code, wiki edits, issues, and other contributionsthat are not aligned to this Code of Conduct, or to ban temporarily orpermanently any contributor for other behaviors that they deem inappropriate,threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies whenan individual is representing the project or its community in public spaces.Examples of representing a project or community include using an officialproject e-mail address, posting via an official social media account, or actingas an appointed representative at an online or offline event. Representation ofa project may be further defined and clarified by project maintainers.
This Code of Conduct also applies outside the project spaces when there is areasonable belief that an individual's behavior may have a negative impact onthe project or its community.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may bereported by contacting the project team at <opensource-conduct@meta.com>. Allcomplaints will be reviewed and investigated and will result in a response thatis deemed necessary and appropriate to the circumstances. The project team isobligated to maintain confidentiality with regard to the reporter of an incident.Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in goodfaith may face temporary or permanent repercussions as determined by othermembers of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, seehttps://www.contributor-covenant.org/faq12345678910111213141516171819202122232425262728293031# Contributing to DINOv2We want to make contributing to this project as easy and transparent aspossible.
## Pull RequestsWe actively welcome your pull requests.
1. Fork the repo and create your branch from `main`.2. If you've added code that should be tested, add tests.3. If you've changed APIs, update the documentation.4. Ensure the test suite passes.5. Make sure your code lints.6. If you haven't already, complete the Contributor License Agreement ("CLA").
## Contributor License Agreement ("CLA")In order to accept your pull request, we need you to submit a CLA. You only needto do this once to work on any of Meta's open source projects.
Complete your CLA here: <https://code.facebook.com/cla>
## IssuesWe use GitHub issues to track public bugs. Please ensure your description isclear and has sufficient instructions to be able to reproduce the issue.
Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safedisclosure of security bugs. In those cases, please go through the processoutlined on that page and do not file a public issue.
## LicenseBy contributing to DINOv2, you agree that your contributions will be licensedunder the LICENSE file in the root directory of this source tree.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More_considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International PublicLicense
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial 4.0 International Public License ("PublicLicense"). To the extent this Public License may be interpreted as acontract, You are granted the Licensed Rights in consideration of Youracceptance of these terms and conditions, and the Licensor grants Yousuch rights in consideration of benefits the Licensor receives frommaking the Licensed Material available under these terms andconditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201# Model Card for DINOv2-S/B/L/g
These are Vision Transformer models trained following the method described in the paper:"DINOv2: Learning Robust Visual Features without Supervision"
We provide 4 models: 1 ViT-g trained from scratch, and 3 ViT-S/B/L models distilled from the ViT-g.
## Model DetailsThe model takes an image as input and returns a class token and patch tokens.
The embedding dimension is: - 384 for ViT-S.- 768 for ViT-B.- 1024 for ViT-L.- 1536 for ViT-g.
The models follow a Transformer architecture, with a patch size of 14.
For a 224x224 image, this results in 1 class token + 256 patch tokens.
The models can accept larger images provided the image shapes are multiples of the patch size (14). If this condition is not verified, the model will crop to the closest smaller multiple of the patch size.
### Model Description
- **Developed by:** Meta AI- **Model type:** Vision Transformer- **License:** CC-BY-NC
- **Repository:** https://github.com/facebookresearch/dinov2- **Paper:** https://arxiv.org/abs/2304.07193- **Demo:** https://dinov2.metademolab.com/
## Uses
The models are vision backbones providing multi-purpose features for downstream tasks.
### Direct Use
The models can be used without fine-tuning, with downstream classifiers as simple as linear layers, to obtain competitive results:- on depth estimation, semantic segmentation, using linear layers.- on image classification, using k-NN classifiers on the class token.- on image classification, with logistic regression classifiers applied on the class token.- on image classification, with a linear layer applied on the class token and the average of the patch tokens.- on image retrieval using nearest neighbors.
### Downstream Use
It is technically possible to perform fine-tuning on the models, for small gains (we measured +2% on ImageNet-1k classification). We recommend keeping this as a very last step and only when necessary, as the features already provide good performance out-of-the-box.
## Bias, Risks, and Limitations
Despite improvements thanks to the training method not using annotations, we still observe significant biases in our models toward rich households from Western countries.
### Recommendations
We expect fine-tuning will increase the biases in the features produced by the model as they will be tuned to the fine-tuning labels.
## How to Get Started with the Model
Use the code below to get started with the model.
```pythonimport torchdinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')```
## Training Details
### Training Data
- **Training data:** LVD-142M (see paper)- **Training regime:** fp16 using PyTorch-FSDP mixed-precision.
### Training Procedure
- **Training objective:** - DINO self-distillation loss with multi-crop - iBOT masked-image modeling loss - KoLeo regularization on [CLS] tokens- **Architectures:** - ViT-S (21M params): Patch size 14, embedding dimension 384, 6 heads, MLP FFN - ViT-B (86M params): Patch size 14, embedding dimension 768, 12 heads, MLP FFN - ViT-L (0.3B params): Patch size 14, embedding dimension 1024, 16 heads, MLP FFN - ViT-g (1.1B params): Patch size 14, embedding dimension 1536, 24 heads, SwiGLU FFN- **Distillation:** - Distillation follows the standard DINOv2 pretraining procedure, except the teacher is a pretrained ViT-g, frozen.
## Evaluation
We refer users to the associated paper for the evaluation protocols.
<table> <tr> <th>model</th> <th colspan="3">ImageNet-1k</th> <th>NYU-Depth v2</th> <th>SUN-RGBD</th> <th>ADE20k</th> <th>iNaturalist 2018</th> <th>Oxford-H</th> </tr> <tr> <th rowspan="2">task</th> <th>classif. (acc)</th> <th>classif. (acc)</th> <th>classif. V2 (acc)</th> <th>depth (RMSE)</th> <th>depth (RMSE)</th> <th>segm. (mAP)</th> <th>classif. (acc)</th> <th>retrieval (mAP)</th> </tr> <tr> <!-- <th>^</th> --> <th>k-NN</th> <th>linear</th> <th>linear</th> <th>linear<br />4 layers</th> <th>NYU-D transfer</th> <th>multiscale</th> <th>linear</th> <th>nearest neighbor</th> </tr> <tr> <td>ViT-S/14</td> <td align="right">79.0%</td> <td align="right">81.1%</td> <td align="right">70.8%</td> <td align="right">0.417</td> <td align="right">0.431</td> <td align="right">47.2</td> <td align="right">69.5%</td> <td align="right">43.2</td> </tr> <tr> <td>ViT-B/14</td> <td align="right">82.1%</td> <td align="right">84.5%</td> <td align="right">74.9%</td> <td align="right">0.362</td> <td align="right">0.400</td> <td align="right">51.3</td> <td align="right">76.3%</td> <td align="right">49.5</td> </tr> <tr> <td>ViT-L/14</td> <td align="right">83.5%</td> <td align="right">86.3%</td> <td align="right">77.6%</td> <td align="right">0.333</td> <td align="right">0.396</td> <td align="right">53.1</td> <td align="right">79.8%</td> <td align="right">54.0</td> </tr> <tr> <td>ViT-g/14</td> <td align="right">83.5%</td> <td align="right">86.5%</td> <td align="right">78.4%</td> <td align="right">0.298</td> <td align="right">0.362</td> <td align="right">53.0</td> <td align="right">81.6%</td> <td align="right">52.3</td> </tr></table>
## Environmental Impact
- **Hardware Type:** Nvidia A100- **Hours used:** 22,000 for ViT-g, 4,500 for ViT-S distillation, 5,300 for ViT-B distillation, 8,000 for ViT-L distillation- **Cloud Provider:** Private infra- **Compute Region:** USA- **Carbon Emitted:** 7t CO2eq
#### Hardware
Nvidia A100 GPUs
#### Software
PyTorch 2.0,xFormers 0.0.18
**BibTeX**
```@misc{oquab2023dinov2, title={DINOv2: Learning Robust Visual Features without Supervision}, author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr}, journal={arXiv:2304.07193}, year={2023}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277# DINOv2: Learning Robust Visual Features without Supervision
**[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
Maxime Oquab,Timothée Darcet,Théo Moutakanni,Huy V. Vo,Marc Szafraniec,Vasil Khalidov,Patrick Labatut,Armand Joulin,Piotr Bojanowski
[[`Paper`](https://arxiv.org/abs/2304.07193)] [[`Blog`](https://ai.facebook.com/blog/dino-v2-computer-vision-self-supervised-learning/)] [[`Demo`](https://dinov2.metademolab.com)] [[`BibTeX`](#citing-dinov2)]
PyTorch implementation and pretrained models for DINOv2. For details, see the paper: **[DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/abs/2304.07193)**.
DINOv2 models produce high-performance visual features that can be directly employed with classifiers as simple as linear layers on a variety of computer vision tasks; these visual features are robust and perform well across domains without any requirement for fine-tuning. The models were pretrained on a dataset of 142 M images without using any labels or annotations.
https://github.com/facebookresearch/dinov2/assets/60359573/f168823e-7922-415a-b429-578badf5c356
<div align="center"> Visualization of the three first principal components of the patch features of all frames, mapped to RGB values.</div>
## Pretrained models
<table style="margin: auto"> <tr> <th>model</th> <th># of<br />params</th> <th>ImageNet<br />k-NN</th> <th>ImageNet<br />linear</th> <th>download</th> </tr> <tr> <td>ViT-S/14 distilled</td> <td align="right">21 M</td> <td align="right">79.0%</td> <td align="right">81.1%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth">backbone only</a></td> </tr> <tr> <td>ViT-B/14 distilled</td> <td align="right">86 M</td> <td align="right">82.1%</td> <td align="right">84.5%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_pretrain.pth">backbone only</a></td> </tr> <tr> <td>ViT-L/14 distilled</td> <td align="right">300 M</td> <td align="right">83.5%</td> <td align="right">86.3%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth">backbone only</a></td> </tr> <tr> <td>ViT-g/14</td> <td align="right">1,100 M</td> <td align="right">83.5%</td> <td align="right">86.5%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth">backbone only</a></td> </tr></table>
### Pretrained models via PyTorch Hub
Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install PyTorch (the only required dependency for loading the model). Installing PyTorch with CUDA support is strongly recommended.
A corresponding [model card](MODEL_CARD.md) is included in the repository.
```pythonimport torch
dinov2_vits14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14')dinov2_vitb14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')dinov2_vitl14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitl14')dinov2_vitg14 = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitg14')```
## Installation
The training and evaluation code requires PyTorch 2.0 and [xFormers](https://github.com/facebookresearch/xformers) 0.0.18 as well as a number of other 3rd party packages. Note that the code has only been tested with the specified versions and also expects a Linux environment. To setup all the required dependencies for training and evaluation, please follow the instructions below:
*[conda](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html)* **(Recommended)** - Clone the repository and then create and activate a `dinov2` conda environment using the provided environment definition:
```shellconda env create -f conda.yamlconda activate dinov2```
*[pip](https://pip.pypa.io/en/stable/getting-started/)* - Clone the repository and then use the provided `requirements.txt` to install the dependencies:
```shellpip install -r requirements.txt```
## Data preparation
### ImageNet-1k
The root directory of the dataset should hold the following contents:
- `<ROOT>/test/ILSVRC2012_test_00000001.JPEG`- `<ROOT>/test/[..]`- `<ROOT>/test/ILSVRC2012_test_00100000.JPEG`- `<ROOT>/train/n01440764/n01440764_10026.JPEG`- `<ROOT>/train/[...]`- `<ROOT>/train/n15075141/n15075141_9993.JPEG`- `<ROOT>/val/n01440764/ILSVRC2012_val_00000293.JPEG`- `<ROOT>/val/[...]`- `<ROOT>/val/n15075141/ILSVRC2012_val_00049174.JPEG`- `<ROOT>/labels.txt`
The provided dataset implementation expects a few additional metadata files to be present under the extra directory:
- `<EXTRA>/class-ids-TRAIN.npy`- `<EXTRA>/class-ids-VAL.npy`- `<EXTRA>/class-names-TRAIN.npy`- `<EXTRA>/class-names-VAL.npy`- `<EXTRA>/entries-TEST.npy`- `<EXTRA>/entries-TRAIN.npy`- `<EXTRA>/entries-VAL.npy`
These metadata files can be generated (once) with the following lines of Python code:
```pythonfrom dinov2.data.datasets import ImageNet
for split in ImageNet.Split: dataset = ImageNet(split=split, root="<ROOT>", extra="<EXTRA>") dataset.dump_extra()```
Note that the root and extra directories do not have to be distinct directories.
### ImageNet-22k
Please adapt the [dataset class](dinov2/data/datasets/image_net_22k.py) to match your local setup.
<br />
:warning: To execute the commands provided in the next sections for training and evaluation, the `dinov2` package should be included in the Python module search path, i.e. simply prefix the command to run with `PYTHONPATH=.`.
## Training
### Fast setup: training DINOv2 ViT-L/16 on ImageNet-1k
Run DINOv2 training on 4 A100-80GB nodes (32 GPUs) in a SLURM cluster environment with submitit:
```shellpython dinov2/run/train/train.py \ --nodes 4 \ --config-file dinov2/configs/train/vitl16_short.yaml \ --output-dir <PATH/TO/OUTPUT/DIR> \ train.dataset_path=ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
Training time is approximately 1 day and the resulting checkpoint should reach 81.6% on k-NN eval and 82.9% on linear eval.
The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
### Long setup: training DINOv2 ViT-L/14 on ImageNet-22k
Run DINOv2 training on 12 A100-80GB nodes (96 GPUs) in a SLURM cluster environment with submitit:
```shellpython dinov2/run/train/train.py \ --nodes 12 \ --config-file dinov2/configs/train/vitl14.yaml \ --output-dir <PATH/TO/OUTPUT/DIR> \ train.dataset_path=ImageNet22k:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
Training time is approximately 3.3 days and the resulting checkpoint should reach 82.0% on k-NN eval and 84.5% on linear eval.
The training code saves the weights of the teacher in the `eval` folder every 12500 iterations for evaluation.
## Evaluation
The training code regularly saves the teacher weights. In order to evaluate the model, run the following evaluation on a single node:
### k-NN classification on ImageNet-1k
```shellpython dinov2/run/eval/knn.py \ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/knn \ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
### Logistic regression classification on ImageNet-1k
```shellpython dinov2/run/eval/log_regression.py \ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/logreg \ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
### Linear classification with data augmentation on ImageNet-1k
```shellpython dinov2/run/eval/linear.py \ --config-file <PATH/TO/OUTPUT/DIR>/config.yaml \ --pretrained-weights <PATH/TO/OUTPUT/DIR>/eval/training_24999/teacher_checkpoint.pth \ --output-dir <PATH/TO/OUTPUT/DIR>/eval/training_24999/linear \ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
We release the weights from evaluating the different models:
<table style="margin: auto"> <tr> <th>model</th> <th>ImageNet<br />top-1</th> <th>linear evaluation</th> </tr> <tr> <td>ViT-S/14 distilled</td> <td align="right">81.1%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_linear_head.pth">linear head weights</a></td> </tr> <tr> <td>ViT-B/14 distilled</td> <td align="right">84.5%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_linear_head.pth">linear head weights</a></td> </tr> <tr> <td>ViT-L/14 distilled</td> <td align="right">86.3%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_linear_head.pth">linear head weights</a></td> </tr> <tr> <td>ViT-g/14</td> <td align="right">86.5%</td> <td><a href="https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_linear_head.pth">linear head weights</a></td> </tr></table>
The performance of the provided pretrained model weights can be evaluated as follows on ImageNet-1k:
```shellpython dinov2/run/eval/linear.py \ --config-file dinov2/configs/eval/vitg14_pretrain.yaml \ --pretrained-weights https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_pretrain.pth \ --train-dataset ImageNet:split=TRAIN:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET> \ --val-dataset ImageNet:split=VAL:root=<PATH/TO/DATASET>:extra=<PATH/TO/DATASET>```
## License
DINOv2 code and model weights are released under the CC-BY-NC 4.0 license. See [LICENSE](LICENSE) for additional details.
## Contributing
See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
## Citing DINOv2
If you find this repository useful, please consider giving a star :star: and citation :t-rex::
```@misc{oquab2023dinov2, title={DINOv2: Learning Robust Visual Features without Supervision}, author={Oquab, Maxime and Darcet, Timothée and Moutakanni, Theo and Vo, Huy V. and Szafraniec, Marc and Khalidov, Vasil and Fernandez, Pierre and Haziza, Daniel and Massa, Francisco and El-Nouby, Alaaeldin and Howes, Russell and Huang, Po-Yao and Xu, Hu and Sharma, Vasu and Li, Shang-Wen and Galuba, Wojciech and Rabbat, Mike and Assran, Mido and Ballas, Nicolas and Synnaeve, Gabriel and Misra, Ishan and Jegou, Herve and Mairal, Julien and Labatut, Patrick and Joulin, Armand and Bojanowski, Piotr}, journal={arXiv:2304.07193}, year={2023}}```12345678910111213141516171819202122name: dinov2channels: - defaults - pytorch - nvidia - xformers - conda-forgedependencies: - python=3.9 - pytorch::pytorch=2.0.0 - pytorch::pytorch-cuda=11.7.0 - pytorch::torchvision=0.15.0 - omegaconf - torchmetrics=0.10.3 - fvcore - iopath - xformers::xformers=0.0.18 - pip - pip: - git+https://github.com/facebookincubator/submitit - --extra-index-url https://pypi.nvidia.com - cuml-cu111234567# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
__version__ = "0.0.1"1234567891011121314151617181920212223# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import pathlib
from omegaconf import OmegaConf
def load_config(config_name: str): config_filename = config_name + ".yaml" return OmegaConf.load(pathlib.Path(__file__).parent.resolve() / config_filename)
dinov2_default_config = load_config("ssl_default_config")
def load_and_merge_config(config_name: str): default_config = OmegaConf.create(dinov2_default_config) loaded_config = load_config(config_name) return OmegaConf.merge(default_config, loaded_config)123456student: arch: vit_base patch_size: 14crops: global_crops_size: 518 # this is to set up the position embeddings properly local_crops_size: 981234567student: arch: vit_giant2 patch_size: 14 ffn_layer: swiglufusedcrops: global_crops_size: 518 # this is to set up the position embeddings properly local_crops_size: 98.gitattributes+4
README.mdAdded+14
app.pyAdded+675
checkpoints/ControlNetModel/config.jsonAdded+57
checkpoints/ControlNetModel/diffusion_pytorch_model.safetensorsAdded+3
checkpoints/ip-adapter.binAdded+3
depth_anything/__pycache__/blocks.cpython-310.pycAdded
depth_anything/__pycache__/dpt.cpython-310.pycAdded
depth_anything/blocks.pyAdded+153
depth_anything/dpt.pyAdded+187
depth_anything/util/__pycache__/transform.cpython-310.pycAdded
depth_anything/util/transform.pyAdded+248
examples/.DS_StoreAdded
examples/kaifu_resize.pngAdded

Large File Pointer Details
- SHA256: b7302f0f7d0ff61be67bf13d172ad2393b6cb2bc985f048089f4e901145324d7
- Pointer size: 132 Bytes
- Size of remote file: 1.06 MB
examples/musk_resize.jpegAdded

examples/poses/pose.jpgAdded

examples/poses/pose2.jpgAdded

examples/poses/pose3.jpgAdded

examples/poses/pose4.jpgAdded

examples/sam_resize.pngAdded

Large File Pointer Details
- SHA256: 1390d8a9a1be7b8f5388c0bc8483b2d5cca6c0f0adeb6eecd970a4413b1f1deb
- Pointer size: 132 Bytes
- Size of remote file: 2.36 MB
examples/schmidhuber_resize.pngAdded

Large File Pointer Details
- SHA256: 51beaa72d1eb9f56118118fae8775bda818bcb56b03220f3cd39daa425f57a9a
- Pointer size: 132 Bytes
- Size of remote file: 3.23 MB
examples/yann-lecun_resize.jpgAdded

ip_adapter/__pycache__/attention_processor.cpython-310.pycAdded
ip_adapter/__pycache__/resampler.cpython-310.pycAdded
ip_adapter/__pycache__/utils.cpython-310.pycAdded
ip_adapter/attention_processor.pyAdded+446
ip_adapter/resampler.pyAdded+121
ip_adapter/utils.pyAdded+5
models/antelopev2/1k3d68.onnxAdded+3
models/antelopev2/2d106det.onnxAdded+3
models/antelopev2/genderage.onnxAdded+3
models/antelopev2/glintr100.onnxAdded+3
models/antelopev2/scrfd_10g_bnkps.onnxAdded+3
pipeline_stable_diffusion_xl_instantid_full.pyAdded+1204
requirements.txtAdded+16
style_template.pyAdded+155
torchhub/README.mdAdded+3
torchhub/facebookresearch_dinov2_main/CODE_OF_CONDUCT.mdAdded+80
torchhub/facebookresearch_dinov2_main/CONTRIBUTING.mdAdded+31
torchhub/facebookresearch_dinov2_main/LICENSEAdded+400
torchhub/facebookresearch_dinov2_main/MODEL_CARD.mdAdded+201
torchhub/facebookresearch_dinov2_main/README.mdAdded+277
torchhub/facebookresearch_dinov2_main/__pycache__/hubconf.cpython-310.pycAdded
torchhub/facebookresearch_dinov2_main/__pycache__/vision_transformer.cpython-310.pycAdded
torchhub/facebookresearch_dinov2_main/conda.yamlAdded+22
torchhub/facebookresearch_dinov2_main/dinov2/__init__.pyAdded+7
torchhub/facebookresearch_dinov2_main/dinov2/__pycache__/__init__.cpython-310.pycAdded
torchhub/facebookresearch_dinov2_main/dinov2/configs/__init__.pyAdded+23
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitb14_pretrain.yamlAdded+6
torchhub/facebookresearch_dinov2_main/dinov2/configs/eval/vitg14_pretrain.yamlAdded+7