# Stable unCLIP

## Stable unCLIP

Stable unCLIP checkpoints are finetuned from [Stable Diffusion 2.1](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_2) 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

```
import torch
from diffusers import UnCLIPScheduler, DDPMScheduler, StableUnCLIPPipeline
from diffusers.models import PriorTransformer
from transformers import CLIPTokenizer, CLIPTextModelWithProjection

prior_model_id = "kakaobrain/karlo-v1-alpha"
data_type = torch.float16
prior = PriorTransformer.from_pretrained(prior_model_id, subfolder="prior", torch_dtype=data_type)

prior_text_model_id = "openai/clip-vit-large-patch14"
prior_tokenizer = CLIPTokenizer.from_pretrained(prior_text_model_id)
prior_text_model = CLIPTextModelWithProjection.from_pretrained(prior_text_model_id, torch_dtype=data_type)
prior_scheduler = UnCLIPScheduler.from_pretrained(prior_model_id, subfolder="prior_scheduler")
prior_scheduler = DDPMScheduler.from_config(prior_scheduler.config)

stable_unclip_model_id = "stabilityai/stable-diffusion-2-1-unclip-small"

pipe = StableUnCLIPPipeline.from_pretrained(
    stable_unclip_model_id,
    torch_dtype=data_type,
    variant="fp16",
    prior_tokenizer=prior_tokenizer,
    prior_text_encoder=prior_text_model,
    prior=prior,
    prior_scheduler=prior_scheduler,
)

pipe = pipe.to("cuda")
wave_prompt = "dramatic wave, the Oceans roar, Strong wave spiral across the oceans as the waves unfurl into roaring crests; perfect wave form; perfect wave shape; dramatic wave shape; wave shape unbelievable; wave; wave shape spectacular"

images = pipe(prompt=wave_prompt).images
images[0].save("waves.png")
```

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](https://hf.co/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

```
from diffusers import StableUnCLIPImg2ImgPipeline
from diffusers.utils import load_image
import torch

pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
    "stabilityai/stable-diffusion-2-1-unclip", torch_dtype=torch.float16, variation="fp16"
)
pipe = pipe.to("cuda")

url = "https://boincai.com/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/tarsila_do_amaral.png"
init_image = load_image(url)

images = pipe(init_image).images
images[0].save("variation_image.png")
```

Optionally, you can also pass a prompt to `pipe` such as:

Copied

```
prompt = "A fantasy landscape, trending on artstation"

images = pipe(init_image, prompt=prompt).images
images[0].save("variation_image_two.png")
```

### StableUnCLIPPipeline

#### class diffusers.StableUnCLIPPipeline

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L58)

( prior\_tokenizer: CLIPTokenizerprior\_text\_encoder: CLIPTextModelWithProjectionprior: PriorTransformerprior\_scheduler: KarrasDiffusionSchedulersimage\_normalizer: StableUnCLIPImageNormalizerimage\_noising\_scheduler: KarrasDiffusionSchedulerstokenizer: CLIPTokenizertext\_encoder: CLIPTextModelWithProjectionunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulersvae: AutoencoderKL )

Parameters

* **prior\_tokenizer** (`CLIPTokenizer`) — A `CLIPTokenizer`.
* **prior\_text\_encoder** (`CLIPTextModelWithProjection`) — Frozen `CLIPTextModelWithProjection` text-encoder.
* **prior** ([PriorTransformer](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/prior_transformer#diffusers.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 the `noise_level`.
* **tokenizer** (`CLIPTokenizer`) — A `CLIPTokenizer`.
* **text\_encoder** (`CLIPTextModel`) — Frozen `CLIPTextModel` text-encoder.
* **unet** ([UNet2DConditionModel](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) — A [UNet2DConditionModel](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/unet2d-cond#diffusers.UNet2DConditionModel) to denoise the encoded image latents.
* **scheduler** (`KarrasDiffusionSchedulers`) — A scheduler to be used in combination with `unet` to denoise the encoded image latents.
* **vae** ([AutoencoderKL](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/autoencoderkl#diffusers.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](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/overview#diffusers.DiffusionPipeline). Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L625)

( 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](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.ImagePipelineOutput) or `tuple`

Parameters

* **prompt** (`str` or `List[str]`, _optional_) — The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
* **height** (`int`, _optional_, defaults to `self.unet.config.sample_size * self.vae_scale_factor`) — The height in pixels of the generated image.
* **width** (`int`, _optional_, defaults to `self.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 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`).
* **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 [DDIMScheduler](https://huggingface.co/docs/diffusers/v0.21.0/en/api/schedulers/ddim#diffusers.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.
* **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 [ImagePipelineOutput](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.ImagePipelineOutput) instead of a plain tuple.
* **callback** (`Callable`, _optional_) — A function that calls every `callback_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 the `callback` 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 the `AttentionProcessor` as defined in [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
* **noise\_level** (`int`, _optional_, defaults to `0`) — The amount of noise to add to the image embeddings. A higher `noise_level` increases the variance in the final un-noised images. See [StableUnCLIPPipeline.noise\_image\_embeddings()](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/stable_unclip#diffusers.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 text `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_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 random `generator`.

Returns

[ImagePipelineOutput](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.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

```
>>> import torch
>>> from diffusers import StableUnCLIPPipeline

>>> pipe = StableUnCLIPPipeline.from_pretrained(
...     "fusing/stable-unclip-2-1-l", torch_dtype=torch.float16
... )  # TODO update model path
>>> pipe = pipe.to("cuda")

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> images = pipe(prompt).images
>>> images[0].save("astronaut_horse.png")
```

**enable\_attention\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1780)

( slice\_size: typing.Union\[str, int, NoneType] = 'auto' )

Parameters

* **slice\_size** (`str` or `int`, _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 as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_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

```
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

**disable\_attention\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1820)

( )

Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is computed in one step.

**enable\_vae\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L151)

( )

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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L159)

( )

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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1719)

( attention\_op: typing.Optional\[typing.Callable] = None )

Parameters

* **attention\_op** (`Callable`, _optional_) — Override the default `None` operator for use as `op` argument to the [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) function of xFormers.

Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/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

```
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

**disable\_xformers\_memory\_efficient\_attention**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1754)

( )

Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).

**encode\_prompt**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L300)

( 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` or `List[str]`, _optional_) — prompt to be encoded device — (`torch.device`): torch device
* **num\_images\_per\_prompt** (`int`) — number of images that should be generated per prompt
* **do\_classifier\_free\_guidance** (`bool`) — whether to use classifier free guidance or not
* **negative\_prompt** (`str` or `List[str]`, _optional_) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **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 from `prompt` 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 from `negative_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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py#L579)

( 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:

1. A noise schedule is applied directly to the embeddings.
2. 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

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L65)

( 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 the `noise_level`.
* **tokenizer** (`~transformers.CLIPTokenizer`) — A \[`~transformers.CLIPTokenizer`)].
* **text\_encoder** (`CLIPTextModel`) — Frozen `CLIPTextModel` text-encoder.
* **unet** ([UNet2DConditionModel](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/unet2d-cond#diffusers.UNet2DConditionModel)) — A [UNet2DConditionModel](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/unet2d-cond#diffusers.UNet2DConditionModel) to denoise the encoded image latents.
* **scheduler** (`KarrasDiffusionSchedulers`) — A scheduler to be used in combination with `unet` to denoise the encoded image latents.
* **vae** ([AutoencoderKL](https://huggingface.co/docs/diffusers/v0.21.0/en/api/models/autoencoderkl#diffusers.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](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/overview#diffusers.DiffusionPipeline). Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

**\_\_call\_\_**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L587)

( 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](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.ImagePipelineOutput) or `tuple`

Parameters

* **prompt** (`str` or `List[str]`, _optional_) — The prompt or prompts to guide the image generation. If not defined, either `prompt_embeds` will be used or prompt is initialized to `""`.
* **image** (`torch.FloatTensor` or `PIL.Image.Image`) — `Image` or tensor representing an image batch. The image is encoded to its CLIP embedding which the `unet` is conditioned on. The image is _not_ encoded by the `vae` 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 to `self.unet.config.sample_size * self.vae_scale_factor`) — The height in pixels of the generated image.
* **width** (`int`, _optional_, defaults to `self.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 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`).
* **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 [DDIMScheduler](https://huggingface.co/docs/diffusers/v0.21.0/en/api/schedulers/ddim#diffusers.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.
* **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 [ImagePipelineOutput](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.ImagePipelineOutput) instead of a plain tuple.
* **callback** (`Callable`, _optional_) — A function that calls every `callback_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 the `callback` 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 the `AttentionProcessor` as defined in [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
* **noise\_level** (`int`, _optional_, defaults to `0`) — The amount of noise to add to the image embeddings. A higher `noise_level` increases the variance in the final un-noised images. See [StableUnCLIPPipeline.noise\_image\_embeddings()](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/stable_unclip#diffusers.StableUnCLIPPipeline.noise_image_embeddings) for more details.
* **image\_embeds** (`torch.FloatTensor`, _optional_) — Pre-generated CLIP embeddings to condition the `unet` on. These latents are not used in the denoising process. If you want to provide pre-generated latents, pass them to `__call__` as `latents`.

Returns

[ImagePipelineOutput](https://huggingface.co/docs/diffusers/v0.21.0/en/api/pipelines/latent_diffusion_uncond#diffusers.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

```
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO

>>> from diffusers import StableUnCLIPImg2ImgPipeline

>>> pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
...     "fusing/stable-unclip-2-1-l-img2img", torch_dtype=torch.float16
... )  # TODO update model path
>>> pipe = pipe.to("cuda")

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))

>>> prompt = "A fantasy landscape, trending on artstation"

>>> images = pipe(prompt, init_image).images
>>> images[0].save("fantasy_landscape.png")
```

**enable\_attention\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1780)

( slice\_size: typing.Union\[str, int, NoneType] = 'auto' )

Parameters

* **slice\_size** (`str` or `int`, _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 as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_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

```
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "runwayml/stable-diffusion-v1-5",
...     torch_dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

**disable\_attention\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1820)

( )

Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is computed in one step.

**enable\_vae\_slicing**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L148)

( )

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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L156)

( )

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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1719)

( attention\_op: typing.Optional\[typing.Callable] = None )

Parameters

* **attention\_op** (`Callable`, _optional_) — Override the default `None` operator for use as `op` argument to the [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) function of xFormers.

Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/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

```
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

**disable\_xformers\_memory\_efficient\_attention**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L1754)

( )

Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).

**encode\_prompt**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L250)

( 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` or `List[str]`, _optional_) — prompt to be encoded device — (`torch.device`): torch device
* **num\_images\_per\_prompt** (`int`) — number of images that should be generated per prompt
* **do\_classifier\_free\_guidance** (`bool`) — whether to use classifier free guidance or not
* **negative\_prompt** (`str` or `List[str]`, _optional_) — The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
* **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 from `prompt` 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 from `negative_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**

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py#L541)

( 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:

1. A noise schedule is applied directly to the embeddings.
2. 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

[\<source>](https://github.com/huggingface/diffusers/blob/v0.21.0/src/diffusers/pipelines/pipeline_utils.py#L112)

( images: typing.Union\[typing.List\[PIL.Image.Image], numpy.ndarray] )

Parameters

* **images** (`List[PIL.Image.Image]` or `np.ndarray`) — List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width, num_channels)`.

Output class for image pipelines.
