Diffusers BOINC AI docs
  • 🌍GET STARTED
    • Diffusers
    • Quicktour
    • Effective and efficient diffusion
    • Installation
  • 🌍TUTORIALS
    • Overview
    • Understanding models and schedulers
    • AutoPipeline
    • Train a diffusion model
  • 🌍USING DIFFUSERS
    • 🌍LOADING & HUB
      • Overview
      • Load pipelines, models, and schedulers
      • Load and compare different schedulers
      • Load community pipelines
      • Load safetensors
      • Load different Stable Diffusion formats
      • Push files to the Hub
    • 🌍TASKS
      • Unconditional image generation
      • Text-to-image
      • Image-to-image
      • Inpainting
      • Depth-to-image
    • 🌍TECHNIQUES
      • Textual inversion
      • Distributed inference with multiple GPUs
      • Improve image quality with deterministic generation
      • Control image brightness
      • Prompt weighting
    • 🌍PIPELINES FOR INFERENCE
      • Overview
      • Stable Diffusion XL
      • ControlNet
      • Shap-E
      • DiffEdit
      • Distilled Stable Diffusion inference
      • Create reproducible pipelines
      • Community pipelines
      • How to contribute a community pipeline
    • 🌍TRAINING
      • Overview
      • Create a dataset for training
      • Adapt a model to a new task
      • Unconditional image generation
      • Textual Inversion
      • DreamBooth
      • Text-to-image
      • Low-Rank Adaptation of Large Language Models (LoRA)
      • ControlNet
      • InstructPix2Pix Training
      • Custom Diffusion
      • T2I-Adapters
    • 🌍TAKING DIFFUSERS BEYOND IMAGES
      • Other Modalities
  • 🌍OPTIMIZATION/SPECIAL HARDWARE
    • Overview
    • Memory and Speed
    • Torch2.0 support
    • Stable Diffusion in JAX/Flax
    • xFormers
    • ONNX
    • OpenVINO
    • Core ML
    • MPS
    • Habana Gaudi
    • Token Merging
  • 🌍CONCEPTUAL GUIDES
    • Philosophy
    • Controlled generation
    • How to contribute?
    • Diffusers' Ethical Guidelines
    • Evaluating Diffusion Models
  • 🌍API
    • 🌍MAIN CLASSES
      • Attention Processor
      • Diffusion Pipeline
      • Logging
      • Configuration
      • Outputs
      • Loaders
      • Utilities
      • VAE Image Processor
    • 🌍MODELS
      • Overview
      • UNet1DModel
      • UNet2DModel
      • UNet2DConditionModel
      • UNet3DConditionModel
      • VQModel
      • AutoencoderKL
      • AsymmetricAutoencoderKL
      • Tiny AutoEncoder
      • Transformer2D
      • Transformer Temporal
      • Prior Transformer
      • ControlNet
    • 🌍PIPELINES
      • Overview
      • AltDiffusion
      • Attend-and-Excite
      • Audio Diffusion
      • AudioLDM
      • AudioLDM 2
      • AutoPipeline
      • Consistency Models
      • ControlNet
      • ControlNet with Stable Diffusion XL
      • Cycle Diffusion
      • Dance Diffusion
      • DDIM
      • DDPM
      • DeepFloyd IF
      • DiffEdit
      • DiT
      • IF
      • PaInstructPix2Pix
      • Kandinsky
      • Kandinsky 2.2
      • Latent Diffusionge
      • MultiDiffusion
      • MusicLDM
      • PaintByExample
      • Parallel Sampling of Diffusion Models
      • Pix2Pix Zero
      • PNDM
      • RePaint
      • Score SDE VE
      • Self-Attention Guidance
      • Semantic Guidance
      • Shap-E
      • Spectrogram Diffusion
      • 🌍STABLE DIFFUSION
        • Overview
        • Text-to-image
        • Image-to-image
        • Inpainting
        • Depth-to-image
        • Image variation
        • Safe Stable Diffusion
        • Stable Diffusion 2
        • Stable Diffusion XL
        • Latent upscaler
        • Super-resolution
        • LDM3D Text-to-(RGB, Depth)
        • Stable Diffusion T2I-adapter
        • GLIGEN (Grounded Language-to-Image Generation)
      • Stable unCLIP
      • Stochastic Karras VE
      • Text-to-image model editing
      • Text-to-video
      • Text2Video-Zero
      • UnCLIP
      • Unconditional Latent Diffusion
      • UniDiffuser
      • Value-guided sampling
      • Versatile Diffusion
      • VQ Diffusion
      • Wuerstchen
    • 🌍SCHEDULERS
      • Overview
      • CMStochasticIterativeScheduler
      • DDIMInverseScheduler
      • DDIMScheduler
      • DDPMScheduler
      • DEISMultistepScheduler
      • DPMSolverMultistepInverse
      • DPMSolverMultistepScheduler
      • DPMSolverSDEScheduler
      • DPMSolverSinglestepScheduler
      • EulerAncestralDiscreteScheduler
      • EulerDiscreteScheduler
      • HeunDiscreteScheduler
      • IPNDMScheduler
      • KarrasVeScheduler
      • KDPM2AncestralDiscreteScheduler
      • KDPM2DiscreteScheduler
      • LMSDiscreteScheduler
      • PNDMScheduler
      • RePaintScheduler
      • ScoreSdeVeScheduler
      • ScoreSdeVpScheduler
      • UniPCMultistepScheduler
      • VQDiffusionScheduler
Powered by GitBook
On this page
  • UniDiffuser
  • Usage Examples
  • UniDiffuserPipeline
  • ImageTextPipelineOutput
  1. API
  2. PIPELINES

UniDiffuser

PreviousUnconditional Latent DiffusionNextValue-guided sampling

Last updated 1 year ago

UniDiffuser

The UniDiffuser model was proposed in by Fan Bao, Shen Nie, Kaiwen Xue, Chongxuan Li, Shi Pu, Yaole Wang, Gang Yue, Yue Cao, Hang Su, Jun Zhu.

The abstract from the is:

This paper proposes a unified diffusion framework (dubbed UniDiffuser) to fit all distributions relevant to a set of multi-modal data in one model. Our key insight is β€” learning diffusion models for marginal, conditional, and joint distributions can be unified as predicting the noise in the perturbed data, where the perturbation levels (i.e. timesteps) can be different for different modalities. Inspired by the unified view, UniDiffuser learns all distributions simultaneously with a minimal modification to the original diffusion model β€” perturbs data in all modalities instead of a single modality, inputs individual timesteps in different modalities, and predicts the noise of all modalities instead of a single modality. UniDiffuser is parameterized by a transformer for diffusion models to handle input types of different modalities. Implemented on large-scale paired image-text data, UniDiffuser is able to perform image, text, text-to-image, image-to-text, and image-text pair generation by setting proper timesteps without additional overhead. In particular, UniDiffuser is able to produce perceptually realistic samples in all tasks and its quantitative results (e.g., the FID and CLIP score) are not only superior to existing general-purpose models but also comparable to the bespoken models (e.g., Stable Diffusion and DALL-E 2) in representative tasks (e.g., text-to-image generation).

You can find the original codebase at and additional checkpoints at .

There is currently an issue on PyTorch 1.X where the output images are all black or the pixel values become NaNs. This issue can be mitigated by switching to PyTorch 2.X.

This pipeline was contributed by . ❀️

Usage Examples

Because the UniDiffuser model is trained to model the joint distribution of (image, text) pairs, it is capable of performing a diverse range of generation tasks:

Unconditional Image and Text Generation

Unconditional generation (where we start from only latents sampled from a standard Gaussian prior) from a will produce a (image, text) pair:

Copied

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Unconditional image and text generation. The generation task is automatically inferred.
sample = pipe(num_inference_steps=20, guidance_scale=8.0)
image = sample.images[0]
text = sample.text[0]
image.save("unidiffuser_joint_sample_image.png")
print(text)

This is also called β€œjoint” generation in the UniDiffusers paper, since we are sampling from the joint image-text distribution.

Copied

# Equivalent to the above.
pipe.set_joint_mode()
sample = pipe(num_inference_steps=20, guidance_scale=8.0)

You can also generate only an image or only text (which the UniDiffuser paper calls β€œmarginal” generation since we sample from the marginal distribution of images and text, respectively):

Copied

# Unlike other generation tasks, image-only and text-only generation don't use classifier-free guidance
# Image-only generation
pipe.set_image_mode()
sample_image = pipe(num_inference_steps=20).images[0]
# Text-only generation
pipe.set_text_mode()
sample_text = pipe(num_inference_steps=20).text[0]

Text-to-Image Generation

UniDiffuser is also capable of sampling from conditional distributions; that is, the distribution of images conditioned on a text prompt or the distribution of texts conditioned on an image. Here is an example of sampling from the conditional image distribution (text-to-image generation or text-conditioned image generation):

Copied

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Text-to-image generation
prompt = "an elephant under the sea"

sample = pipe(prompt=prompt, num_inference_steps=20, guidance_scale=8.0)
t2i_image = sample.images[0]
t2i_image.save("unidiffuser_text2img_sample_image.png")

Image-to-Text Generation

Similarly, UniDiffuser can also produce text samples given an image (image-to-text or image-conditioned text generation):

Copied

import torch

from diffusers import UniDiffuserPipeline
from diffusers.utils import load_image

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Image-to-text generation
image_url = "https://boincai.com/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
init_image = load_image(image_url).resize((512, 512))

sample = pipe(image=init_image, num_inference_steps=20, guidance_scale=8.0)
i2t_text = sample.text[0]
print(i2t_text)

Image Variation

The UniDiffuser authors suggest performing image variation through a β€œround-trip” generation method, where given an input image, we first perform an image-to-text generation, and the perform a text-to-image generation on the outputs of the first generation. This produces a new image which is semantically similar to the input image:

Copied

import torch

from diffusers import UniDiffuserPipeline
from diffusers.utils import load_image

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Image variation can be performed with a image-to-text generation followed by a text-to-image generation:
# 1. Image-to-text generation
image_url = "https://boincai.com/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
init_image = load_image(image_url).resize((512, 512))

sample = pipe(image=init_image, num_inference_steps=20, guidance_scale=8.0)
i2t_text = sample.text[0]
print(i2t_text)

# 2. Text-to-image generation
sample = pipe(prompt=i2t_text, num_inference_steps=20, guidance_scale=8.0)
final_image = sample.images[0]
final_image.save("unidiffuser_image_variation_sample.png")

Text Variation

Similarly, text variation can be performed on an input prompt with a text-to-image generation followed by a image-to-text generation:

Copied

import torch

from diffusers import UniDiffuserPipeline

device = "cuda"
model_id_or_path = "thu-ml/unidiffuser-v1"
pipe = UniDiffuserPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
pipe.to(device)

# Text variation can be performed with a text-to-image generation followed by a image-to-text generation:
# 1. Text-to-image generation
prompt = "an elephant under the sea"

sample = pipe(prompt=prompt, num_inference_steps=20, guidance_scale=8.0)
t2i_image = sample.images[0]
t2i_image.save("unidiffuser_text2img_sample_image.png")

# 2. Image-to-text generation
sample = pipe(image=t2i_image, num_inference_steps=20, guidance_scale=8.0)
final_prompt = sample.text[0]
print(final_prompt)

UniDiffuserPipeline

class diffusers.UniDiffuserPipeline

( vae: AutoencoderKLtext_encoder: CLIPTextModelimage_encoder: CLIPVisionModelWithProjectionimage_processor: CLIPImageProcessorclip_tokenizer: CLIPTokenizertext_decoder: UniDiffuserTextDecodertext_tokenizer: GPT2Tokenizerunet: UniDiffuserModelscheduler: KarrasDiffusionSchedulers )

Parameters

  • image_encoder (CLIPVisionModel) β€” A CLIPVisionModel to encode images as part of its image representation along with the VAE latent representation.

  • image_processor (CLIPImageProcessor) β€” CLIPImageProcessor to preprocess an image before CLIP encoding it with image_encoder.

  • clip_tokenizer (CLIPTokenizer) β€” A CLIPTokenizer to tokenize the prompt before encoding it with text_encoder.

  • text_decoder (UniDiffuserTextDecoder) β€” Frozen text decoder. This is a GPT-style model which is used to generate text from the UniDiffuser embedding.

  • text_tokenizer (GPT2Tokenizer) β€” A GPT2Tokenizer to decode text for text generation; used along with the text_decoder.

Pipeline for a bimodal image-text model which supports unconditional text and image generation, text-conditioned image generation, image-conditioned text generation, and joint image-text generation.

__call__

Parameters

  • prompt (str or List[str], optional) β€” The prompt or prompts to guide image generation. If not defined, you need to pass prompt_embeds. Required for text-conditioned image generation (text2img) mode.

  • image (torch.FloatTensor or PIL.Image.Image, optional) β€” Image or tensor representing an image batch. Required for image-conditioned text generation (img2text) mode.

  • 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 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 8.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). Used in text-conditioned image generation (text2img) mode.

  • num_images_per_prompt (int, optional, defaults to 1) β€” The number of images to generate per prompt. Used in text2img (text-conditioned image generation) and img mode. If the mode is joint and both num_images_per_prompt and num_prompts_per_image are supplied, min(num_images_per_prompt, num_prompts_per_image) samples are generated.

  • num_prompts_per_image (int, optional, defaults to 1) β€” The number of prompts to generate per image. Used in img2text (image-conditioned text generation) and text mode. If the mode is joint and both num_images_per_prompt and num_prompts_per_image are supplied, min(num_images_per_prompt, num_prompts_per_image) samples are generated.

  • latents (torch.FloatTensor, optional) β€” Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for joint image-text 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. This assumes a full set of VAE, CLIP, and text latents, if supplied, overrides the value of prompt_latents, vae_latents, and clip_latents.

  • prompt_latents (torch.FloatTensor, optional) β€” Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for text 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.

  • vae_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.

  • clip_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. Used in text-conditioned image generation (text2img) mode.

  • 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 be generated from the negative_prompt input argument. Used in text-conditioned image generation (text2img) mode.

  • output_type (str, optional, defaults to "pil") β€” The output format of the generated image. Choose between PIL.Image or np.array.

  • 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.

Returns

The call function to the pipeline for generation.

reset_mode

( )

Removes a manually set mode; after calling this, the pipeline will infer the mode from inputs.

set_image_mode

( )

Manually set the generation mode to unconditional (β€œmarginal”) image generation.

set_image_to_text_mode

( )

Manually set the generation mode to image-conditioned text generation.

set_joint_mode

( )

Manually set the generation mode to unconditional joint image-text generation.

set_text_mode

( )

Manually set the generation mode to unconditional (β€œmarginal”) text generation.

set_text_to_image_mode

( )

Manually set the generation mode to text-conditioned image generation.

ImageTextPipelineOutput

class diffusers.ImageTextPipelineOutput

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray, NoneType]text: typing.Union[typing.List[str], typing.List[typing.List[str]], NoneType] )

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).

  • text (List[str] or List[List[str]]) β€” List of generated text strings of length batch_size or a list of list of strings whose outer list has length batch_size.

Output class for joint image-text pipelines.

Note that the generation task is inferred from the inputs used when calling the pipeline. It is also possible to manually specify the unconditional generation task (β€œmode”) manually with :

When the mode is set manually, subsequent calls to the pipeline will use the set mode without attempting the infer the mode. You can reset the mode with , after which the pipeline will once again infer the mode.

The text2img mode requires that either an input prompt or prompt_embeds be supplied. You can set the text2img mode manually with .

The img2text mode requires that an input image be supplied. You can set the img2text mode manually with .

vae () β€” Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations. This is part of the UniDiffuser image representation along with the CLIP vision encoding.

text_encoder (CLIPTextModel) β€” Frozen text-encoder ().

unet (UniDiffuserModel) β€” A model with UNNet-style skip connections between transformer layers to denoise the encoded image latents.

scheduler () β€” A scheduler to be used in combination with unet to denoise the encoded image and/or text latents. The original UniDiffuser paper uses the scheduler.

This model inherits from . Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

( prompt: typing.Union[str, typing.List[str], NoneType] = Noneimage: typing.Union[torch.FloatTensor, PIL.Image.Image, NoneType] = Noneheight: typing.Optional[int] = Nonewidth: typing.Optional[int] = Nonedata_type: typing.Optional[int] = 1num_inference_steps: int = 50guidance_scale: float = 8.0negative_prompt: typing.Union[str, typing.List[str], NoneType] = Nonenum_images_per_prompt: typing.Optional[int] = 1num_prompts_per_image: typing.Optional[int] = 1eta: float = 0.0generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_latents: typing.Optional[torch.FloatTensor] = Nonevae_latents: typing.Optional[torch.FloatTensor] = Noneclip_latents: 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 = 1 ) β†’ or tuple

data_type (int, optional, defaults to 1) β€” The data type (either 0 or 1). Only used if you are loading a checkpoint which supports a data type embedding; this is added for compatibility with the checkpoint.

eta (float, optional, defaults to 0.0) β€” Corresponds to parameter eta (Ξ·) from the paper. Only applies to the , and is ignored in other schedulers.

generator (torch.Generator or List[torch.Generator], optional) β€” A to make generation deterministic.

return_dict (bool, optional, defaults to True) β€” Whether or not to return a instead of a plain tuple.

or tuple

If return_dict is True, is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of generated texts.

🌍
🌍
One Transformer Fits All Distributions in Multi-Modal Diffusion at Scale
paper
thu-ml/unidiffuser
thu-ml
dg845
UniDiffuserPipeline
UniDiffuserPipeline.set_joint_mode()
UniDiffuserPipeline.reset_mode()
UniDiffuserPipeline.set_text_to_image_mode()
UniDiffuserPipeline.set_image_to_text_mode()
<source>
AutoencoderKL
clip-vit-large-patch14
U-ViT
SchedulerMixin
DPMSolverMultistepScheduler
DiffusionPipeline
<source>
ImageTextPipelineOutput
UniDiffuser-v1
DDIM
DDIMScheduler
torch.Generator
ImageTextPipelineOutput
ImageTextPipelineOutput
ImageTextPipelineOutput
<source>
<source>
<source>
<source>
<source>
<source>
<source>