Stable unCLIP
Stable unCLIP
Stable unCLIP checkpoints are finetuned from Stable Diffusion 2.1 checkpoints to condition on CLIP image embeddings. Stable unCLIP still conditions on text embeddings. Given the two separate conditionings, stable unCLIP can be used for text guided image variation. When combined with an unCLIP prior, it can also be used for full text to image generation.
The abstract from the paper is:
Contrastive models like CLIP have been shown to learn robust representations of images that capture both semantics and style. To leverage these representations for image generation, we propose a two-stage model: a prior that generates a CLIP image embedding given a text caption, and a decoder that generates an image conditioned on the image embedding. We show that explicitly generating image representations improves image diversity with minimal loss in photorealism and caption similarity. Our decoders conditioned on image representations can also produce variations of an image that preserve both its semantics and style, while varying the non-essential details absent from the image representation. Moreover, the joint embedding space of CLIP enables language-guided image manipulations in a zero-shot fashion. We use diffusion models for the decoder and experiment with both autoregressive and diffusion models for the prior, finding that the latter are computationally more efficient and produce higher-quality samples.
Tips
Stable unCLIP takes noise_level
as input during inference which determines how much noise is added to the image embeddings. A higher noise_level
increases variation in the final un-noised images. By default, we do not add any additional noise to the image embeddings (noise_level = 0
).
Text-to-Image Generation
Stable unCLIP can be leveraged for text-to-image generation by pipelining it with the prior model of KakaoBrain's open source DALL-E 2 replication [Karlo](https://boincai.com/kakaobrain/karlo-v1-alpha)Copied
For text-to-image we use stabilityai/stable-diffusion-2-1-unclip-small
as it was trained on CLIP ViT-L/14 embedding, the same as the Karlo model prior. stabilityai/stable-diffusion-2-1-unclip was trained on OpenCLIP ViT-H, so we don’t recommend its use.
Text guided Image-to-Image Variation
Copied
Optionally, you can also pass a prompt to pipe
such as:
Copied
StableUnCLIPPipeline
class diffusers.StableUnCLIPPipeline
( prior_tokenizer: CLIPTokenizerprior_text_encoder: CLIPTextModelWithProjectionprior: PriorTransformerprior_scheduler: KarrasDiffusionSchedulersimage_normalizer: StableUnCLIPImageNormalizerimage_noising_scheduler: KarrasDiffusionSchedulerstokenizer: CLIPTokenizertext_encoder: CLIPTextModelWithProjectionunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvae: AutoencoderKL )
Parameters
prior_tokenizer (
CLIPTokenizer
) — ACLIPTokenizer
.prior_text_encoder (
CLIPTextModelWithProjection
) — FrozenCLIPTextModelWithProjection
text-encoder.prior (PriorTransformer) — The canonincal unCLIP prior to approximate the image embedding from the text embedding.
prior_scheduler (
KarrasDiffusionSchedulers
) — Scheduler used in the prior denoising process.image_normalizer (
StableUnCLIPImageNormalizer
) — Used to normalize the predicted image embeddings before the noise is applied and un-normalize the image embeddings after the noise has been applied.image_noising_scheduler (
KarrasDiffusionSchedulers
) — Noise schedule for adding noise to the predicted image embeddings. The amount of noise to add is determined by thenoise_level
.tokenizer (
CLIPTokenizer
) — ACLIPTokenizer
.text_encoder (
CLIPTextModel
) — FrozenCLIPTextModel
text-encoder.unet (UNet2DConditionModel) — A UNet2DConditionModel to denoise the encoded image latents.
scheduler (
KarrasDiffusionSchedulers
) — A scheduler to be used in combination withunet
to denoise the encoded image latents.vae (AutoencoderKL) — Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
Pipeline for text-to-image generation using stable unCLIP.
This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).
__call__
( prompt: typing.Union[str, typing.List[str], NoneType] = Noneheight: typing.Optional[int] = Nonewidth: typing.Optional[int] = Nonenum_inference_steps: int = 20guidance_scale: float = 10.0negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonenum_images_per_prompt: typing.Optional[int] = 1eta: float = 0.0generator: typing.Optional[torch._C.Generator] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: typing.Optional[str] = 'pil'return_dict: bool = Truecallback: typing.Union[typing.Callable[[int, int, torch.FloatTensor], NoneType], NoneType] = Nonecallback_steps: int = 1cross_attention_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = Nonenoise_level: int = 0prior_num_inference_steps: int = 25prior_guidance_scale: float = 4.0prior_latents: typing.Optional[torch.FloatTensor] = None ) → ImagePipelineOutput or tuple
Parameters
prompt (
str
orList[str]
, optional) — The prompt or prompts to guide image generation. If not defined, you need to passprompt_embeds
.height (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — The height in pixels of the generated image.width (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — The width in pixels of the generated image.num_inference_steps (
int
, optional, defaults to 20) — 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 10.0) — A higher guidance scale value encourages the model to generate images closely linked to the textprompt
at the expense of lower image quality. Guidance scale is enabled whenguidance_scale > 1
.negative_prompt (
str
orList[str]
, optional) — The prompt or prompts to guide what to not include in image generation. If not defined, you need to passnegative_prompt_embeds
instead. Ignored when not using guidance (guidance_scale < 1
).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 paper. Only applies to the DDIMScheduler, and is ignored in other schedulers.generator (
torch.Generator
orList[torch.Generator]
, optional) — Atorch.Generator
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 randomgenerator
.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 theprompt
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 thenegative_prompt
input argument.output_type (
str
, optional, defaults to"pil"
) — The output format of the generated image. Choose betweenPIL.Image
ornp.array
.return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a ImagePipelineOutput instead of a plain tuple.callback (
Callable
, optional) — A function that calls everycallback_steps
steps during inference. The function is called with the following arguments:callback(step: int, timestep: int, latents: torch.FloatTensor)
.callback_steps (
int
, optional, defaults to 1) — The frequency at which thecallback
function is called. If not specified, the callback is called at every step.cross_attention_kwargs (
dict
, optional) — A kwargs dictionary that if specified is passed along to theAttentionProcessor
as defined inself.processor
.noise_level (
int
, optional, defaults to0
) — The amount of noise to add to the image embeddings. A highernoise_level
increases the variance in the final un-noised images. See StableUnCLIPPipeline.noise_image_embeddings() for more details.prior_num_inference_steps (
int
, optional, defaults to 25) — The number of denoising steps in the prior denoising process. More denoising steps usually lead to a higher quality image at the expense of slower inference.prior_guidance_scale (
float
, optional, defaults to 4.0) — A higher guidance scale value encourages the model to generate images closely linked to the textprompt
at the expense of lower image quality. Guidance scale is enabled whenguidance_scale > 1
.prior_latents (
torch.FloatTensor
, optional) — Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image embedding generation in the prior denoising process. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied randomgenerator
.
Returns
ImagePipelineOutput or tuple
~ pipeline_utils.ImagePipelineOutput
if return_dict
is True, otherwise a tuple
. When returning a tuple, the first element is a list with the generated images.
The call function to the pipeline for generation.
Examples:
Copied
enable_attention_slicing
( slice_size: typing.Union[str, int, NoneType] = 'auto' )
Parameters
slice_size (
str
orint
, optional, defaults to"auto"
) — When"auto"
, halves the input to the attention heads, so attention will be computed in two steps. If"max"
, maximum amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices asattention_head_dim // slice_size
. In this case,attention_head_dim
must be a multiple ofslice_size
.
Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. For more than one attention head, the computation is performed sequentially over each head. This is useful to save some memory in exchange for a small speed decrease.
⚠️ Don’t enable attention slicing if you’re already using scaled_dot_product_attention
(SDPA) from PyTorch 2.0 or xFormers. These attention computations are already very memory efficient so you won’t need to enable this function. If you enable attention slicing with SDPA or xFormers, it can lead to serious slow downs!
Examples:
Copied
disable_attention_slicing
( )
Disable sliced attention computation. If enable_attention_slicing
was previously called, attention is computed in one step.
enable_vae_slicing
( )
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
disable_vae_slicing
( )
Disable sliced VAE decoding. If enable_vae_slicing
was previously enabled, this method will go back to computing decoding in one step.
enable_xformers_memory_efficient_attention
( attention_op: typing.Optional[typing.Callable] = None )
Parameters
attention_op (
Callable
, optional) — Override the defaultNone
operator for use asop
argument to thememory_efficient_attention()
function of xFormers.
Enable memory efficient attention from xFormers. When this option is enabled, you should observe lower GPU memory usage and a potential speed up during inference. Speed up during training is not guaranteed.
⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes precedent.
Examples:
Copied
disable_xformers_memory_efficient_attention
( )
Disable memory efficient attention from xFormers.
encode_prompt
( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonelora_scale: typing.Optional[float] = None )
Parameters
prompt (
str
orList[str]
, optional) — prompt to be encoded device — (torch.device
): torch devicenum_images_per_prompt (
int
) — number of images that should be generated per promptdo_classifier_free_guidance (
bool
) — whether to use classifier free guidance or notnegative_prompt (
str
orList[str]
, optional) — The prompt or prompts not to guide the image generation. If not defined, one has to passnegative_prompt_embeds
instead. Ignored when not using guidance (i.e., ignored ifguidance_scale
is less than1
).prompt_embeds (
torch.FloatTensor
, optional) — Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated fromprompt
input argument.negative_prompt_embeds (
torch.FloatTensor
, optional) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated fromnegative_prompt
input argument.lora_scale (
float
, optional) — A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
Encodes the prompt into text encoder hidden states.
noise_image_embeddings
( image_embeds: Tensornoise_level: intnoise: typing.Optional[torch.FloatTensor] = Nonegenerator: typing.Optional[torch._C.Generator] = None )
Add noise to the image embeddings. The amount of noise is controlled by a noise_level
input. A higher noise_level
increases the variance in the final un-noised images.
The noise is applied in two ways:
A noise schedule is applied directly to the embeddings.
A vector of sinusoidal time embeddings are appended to the output.
In both cases, the amount of noise is controlled by the same noise_level
.
The embeddings are normalized before the noise is applied and un-normalized after the noise is applied.
StableUnCLIPImg2ImgPipeline
class diffusers.StableUnCLIPImg2ImgPipeline
( feature_extractor: CLIPImageProcessorimage_encoder: CLIPVisionModelWithProjectionimage_normalizer: StableUnCLIPImageNormalizerimage_noising_scheduler: KarrasDiffusionSchedulerstokenizer: CLIPTokenizertext_encoder: CLIPTextModelunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvae: AutoencoderKL )
Parameters
feature_extractor (
CLIPImageProcessor
) — Feature extractor for image pre-processing before being encoded.image_encoder (
CLIPVisionModelWithProjection
) — CLIP vision model for encoding images.image_normalizer (
StableUnCLIPImageNormalizer
) — Used to normalize the predicted image embeddings before the noise is applied and un-normalize the image embeddings after the noise has been applied.image_noising_scheduler (
KarrasDiffusionSchedulers
) — Noise schedule for adding noise to the predicted image embeddings. The amount of noise to add is determined by thenoise_level
.tokenizer (
~transformers.CLIPTokenizer
) — A [~transformers.CLIPTokenizer
)].text_encoder (
CLIPTextModel
) — FrozenCLIPTextModel
text-encoder.unet (UNet2DConditionModel) — A UNet2DConditionModel to denoise the encoded image latents.
scheduler (
KarrasDiffusionSchedulers
) — A scheduler to be used in combination withunet
to denoise the encoded image latents.vae (AutoencoderKL) — Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
Pipeline for text-guided image-to-image generation using stable unCLIP.
This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).
__call__
( image: typing.Union[torch.FloatTensor, PIL.Image.Image] = Noneprompt: typing.Union[str, typing.List[str]] = Noneheight: typing.Optional[int] = Nonewidth: typing.Optional[int] = Nonenum_inference_steps: int = 20guidance_scale: float = 10negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonenum_images_per_prompt: typing.Optional[int] = 1eta: float = 0.0generator: typing.Optional[torch._C.Generator] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: typing.Optional[str] = 'pil'return_dict: bool = Truecallback: typing.Union[typing.Callable[[int, int, torch.FloatTensor], NoneType], NoneType] = Nonecallback_steps: int = 1cross_attention_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = Nonenoise_level: int = 0image_embeds: typing.Optional[torch.FloatTensor] = None ) → ImagePipelineOutput or tuple
Parameters
prompt (
str
orList[str]
, optional) — The prompt or prompts to guide the image generation. If not defined, eitherprompt_embeds
will be used or prompt is initialized to""
.image (
torch.FloatTensor
orPIL.Image.Image
) —Image
or tensor representing an image batch. The image is encoded to its CLIP embedding which theunet
is conditioned on. The image is not encoded by thevae
and then used as the latents in the denoising process like it is in the standard Stable Diffusion text-guided image variation process.height (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — The height in pixels of the generated image.width (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — The width in pixels of the generated image.num_inference_steps (
int
, optional, defaults to 20) — 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 10.0) — A higher guidance scale value encourages the model to generate images closely linked to the textprompt
at the expense of lower image quality. Guidance scale is enabled whenguidance_scale > 1
.negative_prompt (
str
orList[str]
, optional) — The prompt or prompts to guide what to not include in image generation. If not defined, you need to passnegative_prompt_embeds
instead. Ignored when not using guidance (guidance_scale < 1
).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 paper. Only applies to the DDIMScheduler, and is ignored in other schedulers.generator (
torch.Generator
orList[torch.Generator]
, optional) — Atorch.Generator
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 randomgenerator
.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 theprompt
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 thenegative_prompt
input argument.output_type (
str
, optional, defaults to"pil"
) — The output format of the generated image. Choose betweenPIL.Image
ornp.array
.return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a ImagePipelineOutput instead of a plain tuple.callback (
Callable
, optional) — A function that calls everycallback_steps
steps during inference. The function is called with the following arguments:callback(step: int, timestep: int, latents: torch.FloatTensor)
.callback_steps (
int
, optional, defaults to 1) — The frequency at which thecallback
function is called. If not specified, the callback is called at every step.cross_attention_kwargs (
dict
, optional) — A kwargs dictionary that if specified is passed along to theAttentionProcessor
as defined inself.processor
.noise_level (
int
, optional, defaults to0
) — The amount of noise to add to the image embeddings. A highernoise_level
increases the variance in the final un-noised images. See StableUnCLIPPipeline.noise_image_embeddings() for more details.image_embeds (
torch.FloatTensor
, optional) — Pre-generated CLIP embeddings to condition theunet
on. These latents are not used in the denoising process. If you want to provide pre-generated latents, pass them to__call__
aslatents
.
Returns
ImagePipelineOutput or tuple
~ pipeline_utils.ImagePipelineOutput
if return_dict
is True, otherwise a tuple
. When returning a tuple, the first element is a list with the generated images.
The call function to the pipeline for generation.
Examples:
Copied
enable_attention_slicing
( slice_size: typing.Union[str, int, NoneType] = 'auto' )
Parameters
slice_size (
str
orint
, optional, defaults to"auto"
) — When"auto"
, halves the input to the attention heads, so attention will be computed in two steps. If"max"
, maximum amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices asattention_head_dim // slice_size
. In this case,attention_head_dim
must be a multiple ofslice_size
.
Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. For more than one attention head, the computation is performed sequentially over each head. This is useful to save some memory in exchange for a small speed decrease.
⚠️ Don’t enable attention slicing if you’re already using scaled_dot_product_attention
(SDPA) from PyTorch 2.0 or xFormers. These attention computations are already very memory efficient so you won’t need to enable this function. If you enable attention slicing with SDPA or xFormers, it can lead to serious slow downs!
Examples:
Copied
disable_attention_slicing
( )
Disable sliced attention computation. If enable_attention_slicing
was previously called, attention is computed in one step.
enable_vae_slicing
( )
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
disable_vae_slicing
( )
Disable sliced VAE decoding. If enable_vae_slicing
was previously enabled, this method will go back to computing decoding in one step.
enable_xformers_memory_efficient_attention
( attention_op: typing.Optional[typing.Callable] = None )
Parameters
attention_op (
Callable
, optional) — Override the defaultNone
operator for use asop
argument to thememory_efficient_attention()
function of xFormers.
Enable memory efficient attention from xFormers. When this option is enabled, you should observe lower GPU memory usage and a potential speed up during inference. Speed up during training is not guaranteed.
⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes precedent.
Examples:
Copied
disable_xformers_memory_efficient_attention
( )
Disable memory efficient attention from xFormers.
encode_prompt
( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Nonelora_scale: typing.Optional[float] = None )
Parameters
prompt (
str
orList[str]
, optional) — prompt to be encoded device — (torch.device
): torch devicenum_images_per_prompt (
int
) — number of images that should be generated per promptdo_classifier_free_guidance (
bool
) — whether to use classifier free guidance or notnegative_prompt (
str
orList[str]
, optional) — The prompt or prompts not to guide the image generation. If not defined, one has to passnegative_prompt_embeds
instead. Ignored when not using guidance (i.e., ignored ifguidance_scale
is less than1
).prompt_embeds (
torch.FloatTensor
, optional) — Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated fromprompt
input argument.negative_prompt_embeds (
torch.FloatTensor
, optional) — Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated fromnegative_prompt
input argument.lora_scale (
float
, optional) — A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
Encodes the prompt into text encoder hidden states.
noise_image_embeddings
( image_embeds: Tensornoise_level: intnoise: typing.Optional[torch.FloatTensor] = Nonegenerator: typing.Optional[torch._C.Generator] = None )
Add noise to the image embeddings. The amount of noise is controlled by a noise_level
input. A higher noise_level
increases the variance in the final un-noised images.
The noise is applied in two ways:
A noise schedule is applied directly to the embeddings.
A vector of sinusoidal time embeddings are appended to the output.
In both cases, the amount of noise is controlled by the same noise_level
.
The embeddings are normalized before the noise is applied and un-normalized after the noise is applied.
ImagePipelineOutput
class diffusers.ImagePipelineOutput
( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )
Parameters
images (
List[PIL.Image.Image]
ornp.ndarray
) — List of denoised PIL images of lengthbatch_size
or NumPy array of shape(batch_size, height, width, num_channels)
.
Output class for image pipelines.
Last updated