Buckets:
UniDiffuser
The UniDiffuser model was proposed in One Transformer Fits All Distributions in Multi-Modal Diffusion at Scale 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 paper 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 thu-ml/unidiffuser and additional checkpoints at thu-ml.
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 dg845. ❤️
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 UniDiffuserPipeline will produce a (image, text) pair:
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 UniDiffuser paper, since we are sampling from the joint image-text distribution.
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 UniDiffuserPipeline.set_joint_mode():
# Equivalent to the above.
pipe.set_joint_mode()
sample = pipe(num_inference_steps=20, guidance_scale=8.0)
When the mode is set manually, subsequent calls to the pipeline will use the set mode without attempting to infer the mode. You can reset the mode with UniDiffuserPipeline.reset_mode(), after which the pipeline will once again infer the mode.
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):
# 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):
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
The text2img mode requires that either an input prompt or prompt_embeds be supplied. You can set the text2img mode manually with UniDiffuserPipeline.set_text_to_image_mode().
Image-to-Text Generation
Similarly, UniDiffuser can also produce text samples given an image (image-to-text or image-conditioned text generation):
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://huggingface.co/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)
The img2text mode requires that an input image be supplied. You can set the img2text mode manually with UniDiffuserPipeline.set_image_to_text_mode().
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 then 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:
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 an image-to-text generation followed by a text-to-image generation:
# 1. Image-to-text generation
image_url = "https://huggingface.co/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:
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)
Make sure to check out the Schedulers guide to learn how to explore the tradeoff between scheduler speed and quality, and see the reuse components across pipelines section to learn how to efficiently load the same components into multiple pipelines.
UniDiffuserPipeline[[diffusers.UniDiffuserPipeline]]
diffusers.UniDiffuserPipeline[[diffusers.UniDiffuserPipeline]]
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.
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__diffusers.UniDiffuserPipeline.__call__https://github.com/huggingface/diffusers/blob/vr_12849/src/diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py#L1119[{"name": "prompt", "val": ": typing.Union[str, typing.List[str], NoneType] = None"}, {"name": "image", "val": ": typing.Union[torch.Tensor, PIL.Image.Image, NoneType] = None"}, {"name": "height", "val": ": typing.Optional[int] = None"}, {"name": "width", "val": ": typing.Optional[int] = None"}, {"name": "data_type", "val": ": typing.Optional[int] = 1"}, {"name": "num_inference_steps", "val": ": int = 50"}, {"name": "guidance_scale", "val": ": float = 8.0"}, {"name": "negative_prompt", "val": ": typing.Union[str, typing.List[str], NoneType] = None"}, {"name": "num_images_per_prompt", "val": ": typing.Optional[int] = 1"}, {"name": "num_prompts_per_image", "val": ": typing.Optional[int] = 1"}, {"name": "eta", "val": ": float = 0.0"}, {"name": "generator", "val": ": typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None"}, {"name": "latents", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "prompt_latents", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "vae_latents", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "clip_latents", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "prompt_embeds", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "negative_prompt_embeds", "val": ": typing.Optional[torch.Tensor] = None"}, {"name": "output_type", "val": ": typing.Optional[str] = 'pil'"}, {"name": "return_dict", "val": ": bool = True"}, {"name": "callback", "val": ": typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None"}, {"name": "callback_steps", "val": ": int = 1"}]- 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.TensororPIL.Image.Image, optional) --Imageor tensor representing an image batch. Required for image-conditioned text generation (img2text) mode. - 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. - 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 UniDiffuser-v1 checkpoint. - 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 textpromptat the expense of lower image quality. Guidance scale is enabled whenguidance_scale > 1. - negative_prompt (
strorList[str], optional) -- The prompt or prompts to guide what to not include in image generation. If not defined, you need to passnegative_prompt_embedsinstead. Ignored when not using guidance (guidance_scale 0[ImageTextPipelineOutput](/docs/diffusers/pr_12849/en/api/pipelines/unidiffuser#diffusers.ImageTextPipelineOutput) ortupleIfreturn_dictisTrue, [ImageTextPipelineOutput](/docs/diffusers/pr_12849/en/api/pipelines/unidiffuser#diffusers.ImageTextPipelineOutput) is returned, otherwise atuple` is returned where the first element is a list with the generated images and the second element is a list of generated texts.
The call function to the pipeline for generation.
Parameters:
vae (AutoencoderKL) : 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 (clip-vit-large-patch14).
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.
unet (UniDiffuserModel) : A U-ViT model with UNNet-style skip connections between transformer layers to denoise the encoded image latents.
scheduler (SchedulerMixin) : A scheduler to be used in combination with unet to denoise the encoded image and/or text latents. The original UniDiffuser paper uses the DPMSolverMultistepScheduler scheduler.
Returns:
[ImageTextPipelineOutput](/docs/diffusers/pr_12849/en/api/pipelines/unidiffuser#diffusers.ImageTextPipelineOutput) or tuple``
If return_dict is True, ImageTextPipelineOutput 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.
disable_vae_slicing[[diffusers.UniDiffuserPipeline.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.
disable_vae_tiling[[diffusers.UniDiffuserPipeline.disable_vae_tiling]]
Disable tiled VAE decoding. If enable_vae_tiling was previously enabled, this method will go back to
computing decoding in one step.
enable_vae_slicing[[diffusers.UniDiffuserPipeline.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.
enable_vae_tiling[[diffusers.UniDiffuserPipeline.enable_vae_tiling]]
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow processing larger images.
encode_prompt[[diffusers.UniDiffuserPipeline.encode_prompt]]
Encodes the prompt into text encoder hidden states.
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.Tensor, 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.Tensor, 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.
clip_skip (int, optional) : Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that the output of the pre-final layer will be used for computing the prompt embeddings.
reset_mode[[diffusers.UniDiffuserPipeline.reset_mode]]
Removes a manually set mode; after calling this, the pipeline will infer the mode from inputs.
set_image_mode[[diffusers.UniDiffuserPipeline.set_image_mode]]
Manually set the generation mode to unconditional ("marginal") image generation.
set_image_to_text_mode[[diffusers.UniDiffuserPipeline.set_image_to_text_mode]]
Manually set the generation mode to image-conditioned text generation.
set_joint_mode[[diffusers.UniDiffuserPipeline.set_joint_mode]]
Manually set the generation mode to unconditional joint image-text generation.
set_text_mode[[diffusers.UniDiffuserPipeline.set_text_mode]]
Manually set the generation mode to unconditional ("marginal") text generation.
set_text_to_image_mode[[diffusers.UniDiffuserPipeline.set_text_to_image_mode]]
Manually set the generation mode to text-conditioned image generation.
ImageTextPipelineOutput[[diffusers.ImageTextPipelineOutput]]
diffusers.ImageTextPipelineOutput[[diffusers.ImageTextPipelineOutput]]
Output class for joint image-text pipelines.
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.
Xet Storage Details
- Size:
- 21.9 kB
- Xet hash:
- 103b18b0cd1ae4aecc1747fb34d8f609891df87bf8d5faa4ce23339fafba3489
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.