text
stringlengths
0
5.54k
</hfoptions>
ControlNet ⚠️ ControlNet is only supported for Kandinsky 2.2! ControlNet enables conditioning large pretrained diffusion models with additional inputs such as a depth map or edge detection. For example, you can condition Kandinsky 2.2 with a depth map so the model understands and preserves the structure of the depth i...
img = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/cat.png"
).resize((768, 768))
img Then you can use the depth-estimation Pipeline from 🤗 Transformers to process the image and retrieve the depth map: Copied import torch
import numpy as np
from transformers import pipeline
def make_hint(image, depth_estimator):
image = depth_estimator(image)["depth"]
image = np.array(image)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
detected_map = torch.from_numpy(image).float() / 255.0
hint = detected_map.permute(2, 0, 1)
return hint
depth_estimator = pipeline("depth-estimation")
hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda") Text-to-image Load the prior pipeline and the KandinskyV22ControlnetPipeline: Copied from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
prior_pipeline = KandinskyV22PriorPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True
).to("cuda")
pipeline = KandinskyV22ControlnetPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
).to("cuda") Generate the image embeddings from a prompt and negative prompt: Copied prompt = "A robot, 4k photo"
negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfig...
generator = torch.Generator(device="cuda").manual_seed(43)
image_emb, zero_image_emb = prior_pipeline(
prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
).to_tuple() Finally, pass the image embeddings and the depth image to the KandinskyV22ControlnetPipeline to generate an image: Copied image = pipeline(image_embeds=image_emb, negative_image_embeds=zero_image_emb, hint=hint, num_inference_steps=50, generator=generator, height=768, width=768).images[0]
image Image-to-image For image-to-image with ControlNet, you’ll need to use the: KandinskyV22PriorEmb2EmbPipeline to generate the image embeddings from a text prompt and an image KandinskyV22ControlnetImg2ImgPipeline to generate an image from the initial image and the image embeddings Process and extract a depth map ...
import numpy as np
from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
from diffusers.utils import load_image
from transformers import pipeline
img = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/kandinskyv22/cat.png"
).resize((768, 768))
def make_hint(image, depth_estimator):
image = depth_estimator(image)["depth"]
image = np.array(image)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
detected_map = torch.from_numpy(image).float() / 255.0
hint = detected_map.permute(2, 0, 1)
return hint
depth_estimator = pipeline("depth-estimation")
hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda") Load the prior pipeline and the KandinskyV22ControlnetImg2ImgPipeline: Copied prior_pipeline = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16, use_safetensors=True
).to("cuda")
pipeline = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
"kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
).to("cuda") Pass a text prompt and the initial image to the prior pipeline to generate the image embeddings: Copied prompt = "A robot, 4k photo"
negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfig...
generator = torch.Generator(device="cuda").manual_seed(43)
img_emb = prior_pipeline(prompt=prompt, image=img, strength=0.85, generator=generator)
negative_emb = prior_pipeline(prompt=negative_prior_prompt, image=img, strength=1, generator=generator) Now you can run the KandinskyV22ControlnetImg2ImgPipeline to generate an image from the initial image and the image embeddings: Copied image = pipeline(image=img, strength=0.5, image_embeds=img_emb.image_embeds, ne...
make_image_grid([img.resize((512, 512)), image.resize((512, 512))], rows=1, cols=2) Optimizations Kandinsky is unique because it requires a prior pipeline to generate the mappings, and a second pipeline to decode the latents into an image. Optimization efforts should be focused on the second pipeline because that is ...
import torch
pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16)
+ pipe.enable_xformers_memory_efficient_attention() Enable torch.compile if you’re using PyTorch >= 2.0 to automatically use scaled dot-product attention (SDPA): Copied pipe.unet.to(memory_format=torch.channels_last)
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) This is the same as explicitly setting the attention processor to use AttnAddedKVProcessor2_0: Copied from diffusers.models.attention_processor import AttnAddedKVProcessor2_0
pipe.unet.set_attn_processor(AttnAddedKVProcessor2_0()) Offload the model to the CPU with enable_model_cpu_offload() to avoid out-of-memory errors: Copied from diffusers import DiffusionPipeline
import torch
pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", torch_dtype=torch.float16)
+ pipe.enable_model_cpu_offload() By default, the text-to-image pipeline uses the DDIMScheduler but you can replace it with another scheduler like DDPMScheduler to see how that affects the tradeoff between inference speed and image quality: Copied from diffusers import DDPMScheduler
from diffusers import DiffusionPipeline
scheduler = DDPMScheduler.from_pretrained("kandinsky-community/kandinsky-2-1", subfolder="ddpm_scheduler")
pipe = DiffusionPipeline.from_pretrained("kandinsky-community/kandinsky-2-1", scheduler=scheduler, torch_dtype=torch.float16, use_safetensors=True).to("cuda")
Attention Processor An attention processor is a class for applying different types of attention mechanisms. AttnProcessor class diffusers.models.attention_processor.AttnProcessor < source > ( ) Default processor for performing attention-related computations. AttnProcessor2_0 class diffusers.models.attention_pro...
encoder. AttnAddedKVProcessor2_0 class diffusers.models.attention_processor.AttnAddedKVProcessor2_0 < source > ( ) Processor for performing scaled dot-product attention (enabled by default if you’re using PyTorch 2.0), with extra
learnable key and value matrices for the text encoder. CrossFrameAttnProcessor class diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.CrossFrameAttnProcessor < source > ( batch_size = 2 ) Cross frame attention processor. Each frame attends the first frame. CustomDiffusionAttnProcessor cl...
Whether to newly train the key and value matrices corresponding to the text features. train_q_out (bool, defaults to True) —
Whether to newly train query matrices corresponding to the latent image features. hidden_size (int, optional, defaults to None) —
The hidden size of the attention layer. cross_attention_dim (int, optional, defaults to None) —
The number of channels in the encoder_hidden_states. out_bias (bool, defaults to True) —
Whether to include the bias parameter in train_q_out. dropout (float, optional, defaults to 0.0) —
The dropout probability to use. Processor for implementing attention for the Custom Diffusion method. CustomDiffusionAttnProcessor2_0 class diffusers.models.attention_processor.CustomDiffusionAttnProcessor2_0 < source > ( train_kv: bool = True train_q_out: bool = True hidden_size: Optional = None cross_attention_...
Whether to newly train the key and value matrices corresponding to the text features. train_q_out (bool, defaults to True) —
Whether to newly train query matrices corresponding to the latent image features. hidden_size (int, optional, defaults to None) —
The hidden size of the attention layer. cross_attention_dim (int, optional, defaults to None) —
The number of channels in the encoder_hidden_states. out_bias (bool, defaults to True) —