Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
7a87110
·
verified ·
1 Parent(s): b6dd6d6

Upload folder using huggingface_hub

Browse files
main/README.md CHANGED
@@ -11,7 +11,7 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
11
  | Example | Description | Code Example | Colab | Author |
12
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
13
  |Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
14
- |Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|NA|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
15
  |Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/exx8/differential-diffusion) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
16
  | HD-Painter | [HD-Painter](https://github.com/Picsart-AI-Research/HD-Painter) enables prompt-faithfull and high resolution (up to 2k) image inpainting upon any diffusion-based image inpainting method. | [HD-Painter](#hd-painter) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/PAIR/HD-Painter) | [Manukyan Hayk](https://github.com/haikmanukyan) and [Sargsyan Andranik](https://github.com/AndranikSargsyan) |
17
  | Marigold Monocular Depth Estimation | A universal monocular depth estimator, utilizing Stable Diffusion, delivering sharp predictions in the wild. (See the [project page](https://marigoldmonodepth.github.io) and [full codebase](https://github.com/prs-eth/marigold) for more details.) | [Marigold Depth Estimation](#marigold-depth-estimation) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/toshas/marigold) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/12G8reD13DdpMie5ZQlaFNo2WCGeNUH-u?usp=sharing) | [Bingxin Ke](https://github.com/markkua) and [Anton Obukhov](https://github.com/toshas) |
@@ -26,7 +26,7 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
26
  | [Composable Stable Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/) | Stable Diffusion Pipeline that supports prompts that contain "|" in prompts (as an AND condition) and weights (separated by "|" as well) to positively / negatively weight prompts. | [Composable Stable Diffusion](#composable-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
27
  | Seed Resizing Stable Diffusion | Stable Diffusion Pipeline that supports resizing an image and retaining the concepts of the 512 by 512 generation. | [Seed Resizing](#seed-resizing) | - | [Mark Rich](https://github.com/MarkRich) |
28
  | Imagic Stable Diffusion | Stable Diffusion Pipeline that enables writing a text prompt to edit an existing image | [Imagic Stable Diffusion](#imagic-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
29
- | Multilingual Stable Diffusion | Stable Diffusion Pipeline that supports prompts in 50 different languages. | [Multilingual Stable Diffusion](#multilingual-stable-diffusion-pipeline) | - | [Juan Carlos Piñeros](https://github.com/juancopi81) |
30
  | GlueGen Stable Diffusion | Stable Diffusion Pipeline that supports prompts in different languages using GlueGen adapter. | [GlueGen Stable Diffusion](#gluegen-stable-diffusion-pipeline) | - | [Phạm Hồng Vinh](https://github.com/rootonchair) |
31
  | Image to Image Inpainting Stable Diffusion | Stable Diffusion Pipeline that enables the overlaying of two images and subsequent inpainting | [Image to Image Inpainting Stable Diffusion](#image-to-image-inpainting-stable-diffusion) | - | [Alex McKinney](https://github.com/vvvm23) |
32
  | Text Based Inpainting Stable Diffusion | Stable Diffusion Inpainting Pipeline that enables passing a text prompt to generate the mask for inpainting | [Text Based Inpainting Stable Diffusion](#text-based-inpainting-stable-diffusion) | - | [Dhruv Karan](https://github.com/unography) |
@@ -41,8 +41,8 @@ Please also check out our [Community Scripts](https://github.com/huggingface/dif
41
  | DDIM Noise Comparative Analysis Pipeline | Investigating how the diffusion models learn visual concepts from each noise level (which is a contribution of [P2 weighting (CVPR 2022)](https://arxiv.org/abs/2204.00227)) | [DDIM Noise Comparative Analysis Pipeline](#ddim-noise-comparative-analysis-pipeline) | - | [Aengus (Duc-Anh)](https://github.com/aengusng8) |
42
  | CLIP Guided Img2Img Stable Diffusion Pipeline | Doing CLIP guidance for image to image generation with Stable Diffusion | [CLIP Guided Img2Img Stable Diffusion](#clip-guided-img2img-stable-diffusion) | - | [Nipun Jindal](https://github.com/nipunjindal/) |
43
  | TensorRT Stable Diffusion Text to Image Pipeline | Accelerates the Stable Diffusion Text2Image Pipeline using TensorRT | [TensorRT Stable Diffusion Text to Image Pipeline](#tensorrt-text2image-stable-diffusion-pipeline) | - | [Asfiya Baig](https://github.com/asfiyab-nvidia) |
44
- | EDICT Image Editing Pipeline | Diffusion pipeline for text-guided image editing | [EDICT Image Editing Pipeline](#edict-image-editing-pipeline) | - | [Joqsan Azocar](https://github.com/Joqsan) |
45
- | Stable Diffusion RePaint | Stable Diffusion pipeline using [RePaint](https://arxiv.org/abs/2201.09865) for inpainting. | [Stable Diffusion RePaint](#stable-diffusion-repaint ) | - | [Markus Pobitzer](https://github.com/Markus-Pobitzer) |
46
  | TensorRT Stable Diffusion Image to Image Pipeline | Accelerates the Stable Diffusion Image2Image Pipeline using TensorRT | [TensorRT Stable Diffusion Image to Image Pipeline](#tensorrt-image2image-stable-diffusion-pipeline) | - | [Asfiya Baig](https://github.com/asfiyab-nvidia) |
47
  | Stable Diffusion IPEX Pipeline | Accelerate Stable Diffusion inference pipeline with BF16/FP32 precision on Intel Xeon CPUs with [IPEX](https://github.com/intel/intel-extension-for-pytorch) | [Stable Diffusion on IPEX](#stable-diffusion-on-ipex) | - | [Yingjie Han](https://github.com/yingjie-han/) |
48
  | CLIP Guided Images Mixing Stable Diffusion Pipeline | Сombine images using usual diffusion models. | [CLIP Guided Images Mixing Using Stable Diffusion](#clip-guided-images-mixing-with-stable-diffusion) | - | [Karachev Denis](https://github.com/TheDenk) |
@@ -251,24 +251,30 @@ Example usage:
251
  from diffusers import DiffusionPipeline
252
  import torch
253
 
 
 
 
 
 
254
  pipeline = DiffusionPipeline.from_pretrained(
255
- "black-forest-labs/FLUX.1-dev",
256
  torch_dtype=torch.bfloat16,
257
  custom_pipeline="pipeline_flux_with_cfg"
258
  )
259
  pipeline.enable_model_cpu_offload()
260
- prompt = "a watercolor painting of a unicorn"
261
- negative_prompt = "pink"
262
 
 
263
  img = pipeline(
264
  prompt=prompt,
265
  negative_prompt=negative_prompt,
266
  true_cfg=1.5,
267
  guidance_scale=3.5,
268
- num_images_per_prompt=1,
269
  generator=torch.manual_seed(0)
270
  ).images[0]
 
 
271
  img.save("cfg_flux.png")
 
272
  ```
273
 
274
  ### Differential Diffusion
 
11
  | Example | Description | Code Example | Colab | Author |
12
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
13
  |Adaptive Mask Inpainting|Adaptive Mask Inpainting algorithm from [Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models](https://github.com/snuvclab/coma) (ECCV '24, Oral) provides a way to insert human inside the scene image without altering the background, by inpainting with adapting mask.|[Adaptive Mask Inpainting](#adaptive-mask-inpainting)|-|[Hyeonwoo Kim](https://sshowbiz.xyz),[Sookwan Han](https://jellyheadandrew.github.io)|
14
+ |Flux with CFG|[Flux with CFG](https://github.com/ToTheBeginning/PuLID/blob/main/docs/pulid_for_flux.md) provides an implementation of using CFG in [Flux](https://blackforestlabs.ai/announcing-black-forest-labs/).|[Flux with CFG](#flux-with-cfg)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/flux_with_cfg.ipynb)|[Linoy Tsaban](https://github.com/linoytsaban), [Apolinário](https://github.com/apolinario), and [Sayak Paul](https://github.com/sayakpaul)|
15
  |Differential Diffusion|[Differential Diffusion](https://github.com/exx8/differential-diffusion) modifies an image according to a text prompt, and according to a map that specifies the amount of change in each region.|[Differential Diffusion](#differential-diffusion)|[![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/exx8/differential-diffusion) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/exx8/differential-diffusion/blob/main/examples/SD2.ipynb)|[Eran Levin](https://github.com/exx8) and [Ohad Fried](https://www.ohadf.com/)|
16
  | HD-Painter | [HD-Painter](https://github.com/Picsart-AI-Research/HD-Painter) enables prompt-faithfull and high resolution (up to 2k) image inpainting upon any diffusion-based image inpainting method. | [HD-Painter](#hd-painter) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/PAIR/HD-Painter) | [Manukyan Hayk](https://github.com/haikmanukyan) and [Sargsyan Andranik](https://github.com/AndranikSargsyan) |
17
  | Marigold Monocular Depth Estimation | A universal monocular depth estimator, utilizing Stable Diffusion, delivering sharp predictions in the wild. (See the [project page](https://marigoldmonodepth.github.io) and [full codebase](https://github.com/prs-eth/marigold) for more details.) | [Marigold Depth Estimation](#marigold-depth-estimation) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/toshas/marigold) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/12G8reD13DdpMie5ZQlaFNo2WCGeNUH-u?usp=sharing) | [Bingxin Ke](https://github.com/markkua) and [Anton Obukhov](https://github.com/toshas) |
 
26
  | [Composable Stable Diffusion](https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/) | Stable Diffusion Pipeline that supports prompts that contain "|" in prompts (as an AND condition) and weights (separated by "|" as well) to positively / negatively weight prompts. | [Composable Stable Diffusion](#composable-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
27
  | Seed Resizing Stable Diffusion | Stable Diffusion Pipeline that supports resizing an image and retaining the concepts of the 512 by 512 generation. | [Seed Resizing](#seed-resizing) | - | [Mark Rich](https://github.com/MarkRich) |
28
  | Imagic Stable Diffusion | Stable Diffusion Pipeline that enables writing a text prompt to edit an existing image | [Imagic Stable Diffusion](#imagic-stable-diffusion) | - | [Mark Rich](https://github.com/MarkRich) |
29
+ | Multilingual Stable Diffusion | Stable Diffusion Pipeline that supports prompts in 50 different languages. | [Multilingual Stable Diffusion](#multilingual-stable-diffusion-pipeline) | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/multilingual_stable_diffusion.ipynb) | [Juan Carlos Piñeros](https://github.com/juancopi81) |
30
  | GlueGen Stable Diffusion | Stable Diffusion Pipeline that supports prompts in different languages using GlueGen adapter. | [GlueGen Stable Diffusion](#gluegen-stable-diffusion-pipeline) | - | [Phạm Hồng Vinh](https://github.com/rootonchair) |
31
  | Image to Image Inpainting Stable Diffusion | Stable Diffusion Pipeline that enables the overlaying of two images and subsequent inpainting | [Image to Image Inpainting Stable Diffusion](#image-to-image-inpainting-stable-diffusion) | - | [Alex McKinney](https://github.com/vvvm23) |
32
  | Text Based Inpainting Stable Diffusion | Stable Diffusion Inpainting Pipeline that enables passing a text prompt to generate the mask for inpainting | [Text Based Inpainting Stable Diffusion](#text-based-inpainting-stable-diffusion) | - | [Dhruv Karan](https://github.com/unography) |
 
41
  | DDIM Noise Comparative Analysis Pipeline | Investigating how the diffusion models learn visual concepts from each noise level (which is a contribution of [P2 weighting (CVPR 2022)](https://arxiv.org/abs/2204.00227)) | [DDIM Noise Comparative Analysis Pipeline](#ddim-noise-comparative-analysis-pipeline) | - | [Aengus (Duc-Anh)](https://github.com/aengusng8) |
42
  | CLIP Guided Img2Img Stable Diffusion Pipeline | Doing CLIP guidance for image to image generation with Stable Diffusion | [CLIP Guided Img2Img Stable Diffusion](#clip-guided-img2img-stable-diffusion) | - | [Nipun Jindal](https://github.com/nipunjindal/) |
43
  | TensorRT Stable Diffusion Text to Image Pipeline | Accelerates the Stable Diffusion Text2Image Pipeline using TensorRT | [TensorRT Stable Diffusion Text to Image Pipeline](#tensorrt-text2image-stable-diffusion-pipeline) | - | [Asfiya Baig](https://github.com/asfiyab-nvidia) |
44
+ | EDICT Image Editing Pipeline | Diffusion pipeline for text-guided image editing | [EDICT Image Editing Pipeline](#edict-image-editing-pipeline) | [Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/edict_image_pipeline.ipynb) | [Joqsan Azocar](https://github.com/Joqsan) |
45
+ | Stable Diffusion RePaint | Stable Diffusion pipeline using [RePaint](https://arxiv.org/abs/2201.09865) for inpainting. | [Stable Diffusion RePaint](#stable-diffusion-repaint )|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/stable_diffusion_repaint.ipynb)| [Markus Pobitzer](https://github.com/Markus-Pobitzer) |
46
  | TensorRT Stable Diffusion Image to Image Pipeline | Accelerates the Stable Diffusion Image2Image Pipeline using TensorRT | [TensorRT Stable Diffusion Image to Image Pipeline](#tensorrt-image2image-stable-diffusion-pipeline) | - | [Asfiya Baig](https://github.com/asfiyab-nvidia) |
47
  | Stable Diffusion IPEX Pipeline | Accelerate Stable Diffusion inference pipeline with BF16/FP32 precision on Intel Xeon CPUs with [IPEX](https://github.com/intel/intel-extension-for-pytorch) | [Stable Diffusion on IPEX](#stable-diffusion-on-ipex) | - | [Yingjie Han](https://github.com/yingjie-han/) |
48
  | CLIP Guided Images Mixing Stable Diffusion Pipeline | Сombine images using usual diffusion models. | [CLIP Guided Images Mixing Using Stable Diffusion](#clip-guided-images-mixing-with-stable-diffusion) | - | [Karachev Denis](https://github.com/TheDenk) |
 
251
  from diffusers import DiffusionPipeline
252
  import torch
253
 
254
+ model_name = "black-forest-labs/FLUX.1-dev"
255
+ prompt = "a watercolor painting of a unicorn"
256
+ negative_prompt = "pink"
257
+
258
+ # Load the diffusion pipeline
259
  pipeline = DiffusionPipeline.from_pretrained(
260
+ model_name,
261
  torch_dtype=torch.bfloat16,
262
  custom_pipeline="pipeline_flux_with_cfg"
263
  )
264
  pipeline.enable_model_cpu_offload()
 
 
265
 
266
+ # Generate the image
267
  img = pipeline(
268
  prompt=prompt,
269
  negative_prompt=negative_prompt,
270
  true_cfg=1.5,
271
  guidance_scale=3.5,
 
272
  generator=torch.manual_seed(0)
273
  ).images[0]
274
+
275
+ # Save the generated image
276
  img.save("cfg_flux.png")
277
+ print("Image generated and saved successfully.")
278
  ```
279
 
280
  ### Differential Diffusion
main/README_community_scripts.md CHANGED
@@ -6,9 +6,9 @@ If a community script doesn't work as expected, please open an issue and ping th
6
 
7
  | Example | Description | Code Example | Colab | Author |
8
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
9
- | Using IP-Adapter with Negative Noise | Using negative noise with IP-adapter to better control the generation (see the [original post](https://github.com/huggingface/diffusers/discussions/7167) on the forum for more details) | [IP-Adapter Negative Noise](#ip-adapter-negative-noise) | https://github.com/huggingface/notebooks/blob/main/diffusers/ip_adapter_negative_noise.ipynb | [Álvaro Somoza](https://github.com/asomoza)|
10
- | Asymmetric Tiling |configure seamless image tiling independently for the X and Y axes | [Asymmetric Tiling](#Asymmetric-Tiling ) |https://github.com/huggingface/notebooks/blob/main/diffusers/asymetric_tiling.ipynb | [alexisrolland](https://github.com/alexisrolland)|
11
- | Prompt Scheduling Callback |Allows changing prompts during a generation | [Prompt Scheduling-Callback](#Prompt-Scheduling-Callback ) |https://github.com/huggingface/notebooks/blob/main/diffusers/prompt_scheduling_callback.ipynb | [hlky](https://github.com/hlky)|
12
 
13
 
14
  ## Example usages
 
6
 
7
  | Example | Description | Code Example | Colab | Author |
8
  |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
9
+ | Using IP-Adapter with Negative Noise | Using negative noise with IP-adapter to better control the generation (see the [original post](https://github.com/huggingface/diffusers/discussions/7167) on the forum for more details) | [IP-Adapter Negative Noise](#ip-adapter-negative-noise) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/ip_adapter_negative_noise.ipynb) | [Álvaro Somoza](https://github.com/asomoza)|
10
+ | Asymmetric Tiling |configure seamless image tiling independently for the X and Y axes | [Asymmetric Tiling](#Asymmetric-Tiling ) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/asymetric_tiling.ipynb) | [alexisrolland](https://github.com/alexisrolland)|
11
+ | Prompt Scheduling Callback |Allows changing prompts during a generation | [Prompt Scheduling-Callback](#Prompt-Scheduling-Callback ) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/prompt_scheduling_callback.ipynb) | [hlky](https://github.com/hlky)|
12
 
13
 
14
  ## Example usages
main/pipeline_flux_rf_inversion.py ADDED
@@ -0,0 +1,1061 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ # modeled after RF Inversion: https://rf-inversion.github.io/, authored by Litu Rout, Yujia Chen, Nataniel Ruiz,
3
+ # Constantine Caramanis, Sanjay Shakkottai and Wen-Sheng Chu.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import inspect
18
+ from typing import Any, Callable, Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
23
+
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
26
+ from diffusers.models.autoencoders import AutoencoderKL
27
+ from diffusers.models.transformers import FluxTransformer2DModel
28
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
31
+ from diffusers.utils import (
32
+ USE_PEFT_BACKEND,
33
+ is_torch_xla_available,
34
+ logging,
35
+ replace_example_docstring,
36
+ scale_lora_layers,
37
+ unscale_lora_layers,
38
+ )
39
+ from diffusers.utils.torch_utils import randn_tensor
40
+
41
+
42
+ if is_torch_xla_available():
43
+ import torch_xla.core.xla_model as xm
44
+
45
+ XLA_AVAILABLE = True
46
+ else:
47
+ XLA_AVAILABLE = False
48
+
49
+
50
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
51
+
52
+ EXAMPLE_DOC_STRING = """
53
+ Examples:
54
+ ```py
55
+ >>> import torch
56
+ >>> from diffusers import FluxPipeline
57
+
58
+ >>> pipe = DiffusionPipeline.from_pretrained(
59
+ ... "black-forest-labs/FLUX.1-dev",
60
+ ... torch_dtype=torch.bfloat16,
61
+ ... custom_pipeline="pipeline_flux_rf_inversion")
62
+ >>> pipe.to("cuda")
63
+
64
+ >>> def download_image(url):
65
+ ... response = requests.get(url)
66
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
67
+
68
+
69
+ >>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
70
+ >>> image = download_image(img_url)
71
+
72
+ >>> inverted_latents, image_latents, latent_image_ids = pipe.invert(image=image, num_inversion_steps=28, gamma=0.5)
73
+
74
+ >>> edited_image = pipe(
75
+ ... prompt="a tomato",
76
+ ... inverted_latents=inverted_latents,
77
+ ... image_latents=image_latents,
78
+ ... latent_image_ids=latent_image_ids,
79
+ ... start_timestep=0,
80
+ ... stop_timestep=.38,
81
+ ... num_inference_steps=28,
82
+ ... eta=0.9,
83
+ ... stop_timestep=.38,
84
+ ... num_inference_steps=28,
85
+ ... eta=0.9,
86
+ ... ).images[0]
87
+ ```
88
+ """
89
+
90
+
91
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
92
+ def calculate_shift(
93
+ image_seq_len,
94
+ base_seq_len: int = 256,
95
+ max_seq_len: int = 4096,
96
+ base_shift: float = 0.5,
97
+ max_shift: float = 1.16,
98
+ ):
99
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
100
+ b = base_shift - m * base_seq_len
101
+ mu = image_seq_len * m + b
102
+ return mu
103
+
104
+
105
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
106
+ def retrieve_timesteps(
107
+ scheduler,
108
+ num_inference_steps: Optional[int] = None,
109
+ device: Optional[Union[str, torch.device]] = None,
110
+ timesteps: Optional[List[int]] = None,
111
+ sigmas: Optional[List[float]] = None,
112
+ **kwargs,
113
+ ):
114
+ r"""
115
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
116
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
117
+
118
+ Args:
119
+ scheduler (`SchedulerMixin`):
120
+ The scheduler to get timesteps from.
121
+ num_inference_steps (`int`):
122
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
123
+ must be `None`.
124
+ device (`str` or `torch.device`, *optional*):
125
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
126
+ timesteps (`List[int]`, *optional*):
127
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
128
+ `num_inference_steps` and `sigmas` must be `None`.
129
+ sigmas (`List[float]`, *optional*):
130
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
131
+ `num_inference_steps` and `timesteps` must be `None`.
132
+
133
+ Returns:
134
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
135
+ second element is the number of inference steps.
136
+ """
137
+ if timesteps is not None and sigmas is not None:
138
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
139
+ if timesteps is not None:
140
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
141
+ if not accepts_timesteps:
142
+ raise ValueError(
143
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
144
+ f" timestep schedules. Please check whether you are using the correct scheduler."
145
+ )
146
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
147
+ timesteps = scheduler.timesteps
148
+ num_inference_steps = len(timesteps)
149
+ elif sigmas is not None:
150
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
151
+ if not accept_sigmas:
152
+ raise ValueError(
153
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
154
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
155
+ )
156
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
157
+ timesteps = scheduler.timesteps
158
+ num_inference_steps = len(timesteps)
159
+ else:
160
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
161
+ timesteps = scheduler.timesteps
162
+ return timesteps, num_inference_steps
163
+
164
+
165
+ class RFInversionFluxPipeline(
166
+ DiffusionPipeline,
167
+ FluxLoraLoaderMixin,
168
+ FromSingleFileMixin,
169
+ TextualInversionLoaderMixin,
170
+ ):
171
+ r"""
172
+ The Flux pipeline for text-to-image generation.
173
+
174
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
175
+
176
+ Args:
177
+ transformer ([`FluxTransformer2DModel`]):
178
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
179
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
180
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
181
+ vae ([`AutoencoderKL`]):
182
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
183
+ text_encoder ([`CLIPTextModel`]):
184
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
185
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
186
+ text_encoder_2 ([`T5EncoderModel`]):
187
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
188
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
189
+ tokenizer (`CLIPTokenizer`):
190
+ Tokenizer of class
191
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
192
+ tokenizer_2 (`T5TokenizerFast`):
193
+ Second Tokenizer of class
194
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
195
+ """
196
+
197
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
198
+ _optional_components = []
199
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
200
+
201
+ def __init__(
202
+ self,
203
+ scheduler: FlowMatchEulerDiscreteScheduler,
204
+ vae: AutoencoderKL,
205
+ text_encoder: CLIPTextModel,
206
+ tokenizer: CLIPTokenizer,
207
+ text_encoder_2: T5EncoderModel,
208
+ tokenizer_2: T5TokenizerFast,
209
+ transformer: FluxTransformer2DModel,
210
+ ):
211
+ super().__init__()
212
+
213
+ self.register_modules(
214
+ vae=vae,
215
+ text_encoder=text_encoder,
216
+ text_encoder_2=text_encoder_2,
217
+ tokenizer=tokenizer,
218
+ tokenizer_2=tokenizer_2,
219
+ transformer=transformer,
220
+ scheduler=scheduler,
221
+ )
222
+ self.vae_scale_factor = (
223
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
224
+ )
225
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
226
+ self.tokenizer_max_length = (
227
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
228
+ )
229
+ self.default_sample_size = 128
230
+
231
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
232
+ def _get_t5_prompt_embeds(
233
+ self,
234
+ prompt: Union[str, List[str]] = None,
235
+ num_images_per_prompt: int = 1,
236
+ max_sequence_length: int = 512,
237
+ device: Optional[torch.device] = None,
238
+ dtype: Optional[torch.dtype] = None,
239
+ ):
240
+ device = device or self._execution_device
241
+ dtype = dtype or self.text_encoder.dtype
242
+
243
+ prompt = [prompt] if isinstance(prompt, str) else prompt
244
+ batch_size = len(prompt)
245
+
246
+ if isinstance(self, TextualInversionLoaderMixin):
247
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
248
+
249
+ text_inputs = self.tokenizer_2(
250
+ prompt,
251
+ padding="max_length",
252
+ max_length=max_sequence_length,
253
+ truncation=True,
254
+ return_length=False,
255
+ return_overflowing_tokens=False,
256
+ return_tensors="pt",
257
+ )
258
+ text_input_ids = text_inputs.input_ids
259
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
260
+
261
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
262
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
263
+ logger.warning(
264
+ "The following part of your input was truncated because `max_sequence_length` is set to "
265
+ f" {max_sequence_length} tokens: {removed_text}"
266
+ )
267
+
268
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
269
+
270
+ dtype = self.text_encoder_2.dtype
271
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
272
+
273
+ _, seq_len, _ = prompt_embeds.shape
274
+
275
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
276
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
277
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
278
+
279
+ return prompt_embeds
280
+
281
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
282
+ def _get_clip_prompt_embeds(
283
+ self,
284
+ prompt: Union[str, List[str]],
285
+ num_images_per_prompt: int = 1,
286
+ device: Optional[torch.device] = None,
287
+ ):
288
+ device = device or self._execution_device
289
+
290
+ prompt = [prompt] if isinstance(prompt, str) else prompt
291
+ batch_size = len(prompt)
292
+
293
+ if isinstance(self, TextualInversionLoaderMixin):
294
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
295
+
296
+ text_inputs = self.tokenizer(
297
+ prompt,
298
+ padding="max_length",
299
+ max_length=self.tokenizer_max_length,
300
+ truncation=True,
301
+ return_overflowing_tokens=False,
302
+ return_length=False,
303
+ return_tensors="pt",
304
+ )
305
+
306
+ text_input_ids = text_inputs.input_ids
307
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
308
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
309
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
310
+ logger.warning(
311
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
312
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
313
+ )
314
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
315
+
316
+ # Use pooled output of CLIPTextModel
317
+ prompt_embeds = prompt_embeds.pooler_output
318
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
319
+
320
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
321
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
322
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
323
+
324
+ return prompt_embeds
325
+
326
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
327
+ def encode_prompt(
328
+ self,
329
+ prompt: Union[str, List[str]],
330
+ prompt_2: Union[str, List[str]],
331
+ device: Optional[torch.device] = None,
332
+ num_images_per_prompt: int = 1,
333
+ prompt_embeds: Optional[torch.FloatTensor] = None,
334
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
335
+ max_sequence_length: int = 512,
336
+ lora_scale: Optional[float] = None,
337
+ ):
338
+ r"""
339
+
340
+ Args:
341
+ prompt (`str` or `List[str]`, *optional*):
342
+ prompt to be encoded
343
+ prompt_2 (`str` or `List[str]`, *optional*):
344
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
345
+ used in all text-encoders
346
+ device: (`torch.device`):
347
+ torch device
348
+ num_images_per_prompt (`int`):
349
+ number of images that should be generated per prompt
350
+ prompt_embeds (`torch.FloatTensor`, *optional*):
351
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
352
+ provided, text embeddings will be generated from `prompt` input argument.
353
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
354
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
355
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
356
+ lora_scale (`float`, *optional*):
357
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
358
+ """
359
+ device = device or self._execution_device
360
+
361
+ # set lora scale so that monkey patched LoRA
362
+ # function of text encoder can correctly access it
363
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
364
+ self._lora_scale = lora_scale
365
+
366
+ # dynamically adjust the LoRA scale
367
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
368
+ scale_lora_layers(self.text_encoder, lora_scale)
369
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
370
+ scale_lora_layers(self.text_encoder_2, lora_scale)
371
+
372
+ prompt = [prompt] if isinstance(prompt, str) else prompt
373
+
374
+ if prompt_embeds is None:
375
+ prompt_2 = prompt_2 or prompt
376
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
377
+
378
+ # We only use the pooled prompt output from the CLIPTextModel
379
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
380
+ prompt=prompt,
381
+ device=device,
382
+ num_images_per_prompt=num_images_per_prompt,
383
+ )
384
+ prompt_embeds = self._get_t5_prompt_embeds(
385
+ prompt=prompt_2,
386
+ num_images_per_prompt=num_images_per_prompt,
387
+ max_sequence_length=max_sequence_length,
388
+ device=device,
389
+ )
390
+
391
+ if self.text_encoder is not None:
392
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
393
+ # Retrieve the original scale by scaling back the LoRA layers
394
+ unscale_lora_layers(self.text_encoder, lora_scale)
395
+
396
+ if self.text_encoder_2 is not None:
397
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
398
+ # Retrieve the original scale by scaling back the LoRA layers
399
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
400
+
401
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
402
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
403
+
404
+ return prompt_embeds, pooled_prompt_embeds, text_ids
405
+
406
+ @torch.no_grad()
407
+ # Modified from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LEditsPPPipelineStableDiffusion.encode_image
408
+ def encode_image(self, image, dtype=None, height=None, width=None, resize_mode="default", crops_coords=None):
409
+ image = self.image_processor.preprocess(
410
+ image=image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
411
+ )
412
+ resized = self.image_processor.postprocess(image=image, output_type="pil")
413
+
414
+ if max(image.shape[-2:]) > self.vae.config["sample_size"] * 1.5:
415
+ logger.warning(
416
+ "Your input images far exceed the default resolution of the underlying diffusion model. "
417
+ "The output images may contain severe artifacts! "
418
+ "Consider down-sampling the input using the `height` and `width` parameters"
419
+ )
420
+ image = image.to(dtype)
421
+
422
+ x0 = self.vae.encode(image.to(self.device)).latent_dist.sample()
423
+ x0 = (x0 - self.vae.config.shift_factor) * self.vae.config.scaling_factor
424
+ x0 = x0.to(dtype)
425
+ return x0, resized
426
+
427
+ def check_inputs(
428
+ self,
429
+ prompt,
430
+ prompt_2,
431
+ inverted_latents,
432
+ image_latents,
433
+ latent_image_ids,
434
+ height,
435
+ width,
436
+ start_timestep,
437
+ stop_timestep,
438
+ prompt_embeds=None,
439
+ pooled_prompt_embeds=None,
440
+ callback_on_step_end_tensor_inputs=None,
441
+ max_sequence_length=None,
442
+ ):
443
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
444
+ raise ValueError(
445
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor} but are {height} and {width}."
446
+ )
447
+
448
+ if callback_on_step_end_tensor_inputs is not None and not all(
449
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
450
+ ):
451
+ raise ValueError(
452
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
453
+ )
454
+
455
+ if prompt is not None and prompt_embeds is not None:
456
+ raise ValueError(
457
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
458
+ " only forward one of the two."
459
+ )
460
+ elif prompt_2 is not None and prompt_embeds is not None:
461
+ raise ValueError(
462
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
463
+ " only forward one of the two."
464
+ )
465
+ elif prompt is None and prompt_embeds is None:
466
+ raise ValueError(
467
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
468
+ )
469
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
470
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
471
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
472
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
473
+
474
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
475
+ raise ValueError(
476
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
477
+ )
478
+
479
+ if max_sequence_length is not None and max_sequence_length > 512:
480
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
481
+
482
+ if inverted_latents is not None and (image_latents is None or latent_image_ids is None):
483
+ raise ValueError(
484
+ "If `inverted_latents` are provided, `image_latents` and `latent_image_ids` also have to be passed. "
485
+ )
486
+ # check start_timestep and stop_timestep
487
+ if start_timestep < 0 or start_timestep > stop_timestep:
488
+ raise ValueError(f"`start_timestep` should be in [0, stop_timestep] but is {start_timestep}")
489
+
490
+ @staticmethod
491
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
492
+ latent_image_ids = torch.zeros(height, width, 3)
493
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
494
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
495
+
496
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
497
+
498
+ latent_image_ids = latent_image_ids.reshape(
499
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
500
+ )
501
+
502
+ return latent_image_ids.to(device=device, dtype=dtype)
503
+
504
+ @staticmethod
505
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
506
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
507
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
508
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
509
+
510
+ return latents
511
+
512
+ @staticmethod
513
+ def _unpack_latents(latents, height, width, vae_scale_factor):
514
+ batch_size, num_patches, channels = latents.shape
515
+
516
+ height = height // vae_scale_factor
517
+ width = width // vae_scale_factor
518
+
519
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
520
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
521
+
522
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
523
+
524
+ return latents
525
+
526
+ def enable_vae_slicing(self):
527
+ r"""
528
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
529
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
530
+ """
531
+ self.vae.enable_slicing()
532
+
533
+ def disable_vae_slicing(self):
534
+ r"""
535
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
536
+ computing decoding in one step.
537
+ """
538
+ self.vae.disable_slicing()
539
+
540
+ def enable_vae_tiling(self):
541
+ r"""
542
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
543
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
544
+ processing larger images.
545
+ """
546
+ self.vae.enable_tiling()
547
+
548
+ def disable_vae_tiling(self):
549
+ r"""
550
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
551
+ computing decoding in one step.
552
+ """
553
+ self.vae.disable_tiling()
554
+
555
+ def prepare_latents_inversion(
556
+ self,
557
+ batch_size,
558
+ num_channels_latents,
559
+ height,
560
+ width,
561
+ dtype,
562
+ device,
563
+ image_latents,
564
+ ):
565
+ height = int(height) // self.vae_scale_factor
566
+ width = int(width) // self.vae_scale_factor
567
+
568
+ latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height, width)
569
+
570
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
571
+
572
+ return latents, latent_image_ids
573
+
574
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_latents
575
+ def prepare_latents(
576
+ self,
577
+ batch_size,
578
+ num_channels_latents,
579
+ height,
580
+ width,
581
+ dtype,
582
+ device,
583
+ generator,
584
+ latents=None,
585
+ ):
586
+ # VAE applies 8x compression on images but we must also account for packing which requires
587
+ # latent height and width to be divisible by 2.
588
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
589
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
590
+
591
+ shape = (batch_size, num_channels_latents, height, width)
592
+
593
+ if latents is not None:
594
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
595
+ return latents.to(device=device, dtype=dtype), latent_image_ids
596
+
597
+ if isinstance(generator, list) and len(generator) != batch_size:
598
+ raise ValueError(
599
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
600
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
601
+ )
602
+
603
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
604
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
605
+
606
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
607
+
608
+ return latents, latent_image_ids
609
+
610
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
611
+ def get_timesteps(self, num_inference_steps, strength=1.0):
612
+ # get the original timestep using init_timestep
613
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
614
+
615
+ t_start = int(max(num_inference_steps - init_timestep, 0))
616
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
617
+ sigmas = self.scheduler.sigmas[t_start * self.scheduler.order :]
618
+ if hasattr(self.scheduler, "set_begin_index"):
619
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
620
+
621
+ return timesteps, sigmas, num_inference_steps - t_start
622
+
623
+ @property
624
+ def guidance_scale(self):
625
+ return self._guidance_scale
626
+
627
+ @property
628
+ def joint_attention_kwargs(self):
629
+ return self._joint_attention_kwargs
630
+
631
+ @property
632
+ def num_timesteps(self):
633
+ return self._num_timesteps
634
+
635
+ @property
636
+ def interrupt(self):
637
+ return self._interrupt
638
+
639
+ @torch.no_grad()
640
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
641
+ def __call__(
642
+ self,
643
+ prompt: Union[str, List[str]] = None,
644
+ prompt_2: Optional[Union[str, List[str]]] = None,
645
+ inverted_latents: Optional[torch.FloatTensor] = None,
646
+ image_latents: Optional[torch.FloatTensor] = None,
647
+ latent_image_ids: Optional[torch.FloatTensor] = None,
648
+ height: Optional[int] = None,
649
+ width: Optional[int] = None,
650
+ eta: float = 1.0,
651
+ strength: float = 1.0,
652
+ start_timestep: float = 0,
653
+ stop_timestep: float = 0.25,
654
+ num_inference_steps: int = 28,
655
+ sigmas: Optional[List[float]] = None,
656
+ timesteps: List[int] = None,
657
+ guidance_scale: float = 3.5,
658
+ num_images_per_prompt: Optional[int] = 1,
659
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
660
+ latents: Optional[torch.FloatTensor] = None,
661
+ prompt_embeds: Optional[torch.FloatTensor] = None,
662
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
663
+ output_type: Optional[str] = "pil",
664
+ return_dict: bool = True,
665
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
666
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
667
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
668
+ max_sequence_length: int = 512,
669
+ ):
670
+ r"""
671
+ Function invoked when calling the pipeline for generation.
672
+
673
+ Args:
674
+ prompt (`str` or `List[str]`, *optional*):
675
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
676
+ instead.
677
+ prompt_2 (`str` or `List[str]`, *optional*):
678
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
679
+ will be used instead
680
+ inverted_latents (`torch.Tensor`, *optional*):
681
+ The inverted latents from `pipe.invert`.
682
+ image_latents (`torch.Tensor`, *optional*):
683
+ The image latents from `pipe.invert`.
684
+ latent_image_ids (`torch.Tensor`, *optional*):
685
+ The latent image ids from `pipe.invert`.
686
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
687
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
688
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
689
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
690
+ eta (`float`, *optional*, defaults to 1.0):
691
+ The controller guidance, balancing faithfulness & editability:
692
+ higher eta - better faithfullness, less editability. For more significant edits, lower the value of eta.
693
+ num_inference_steps (`int`, *optional*, defaults to 50):
694
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
695
+ expense of slower inference.
696
+ timesteps (`List[int]`, *optional*):
697
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
698
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
699
+ passed will be used. Must be in descending order.
700
+ guidance_scale (`float`, *optional*, defaults to 7.0):
701
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
702
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
703
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
704
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
705
+ usually at the expense of lower image quality.
706
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
707
+ The number of images to generate per prompt.
708
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
709
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
710
+ to make generation deterministic.
711
+ latents (`torch.FloatTensor`, *optional*):
712
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
713
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
714
+ tensor will ge generated by sampling using the supplied random `generator`.
715
+ prompt_embeds (`torch.FloatTensor`, *optional*):
716
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
717
+ provided, text embeddings will be generated from `prompt` input argument.
718
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
719
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
720
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
721
+ output_type (`str`, *optional*, defaults to `"pil"`):
722
+ The output format of the generate image. Choose between
723
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
724
+ return_dict (`bool`, *optional*, defaults to `True`):
725
+ Whether to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
726
+ joint_attention_kwargs (`dict`, *optional*):
727
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
728
+ `self.processor` in
729
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
730
+ callback_on_step_end (`Callable`, *optional*):
731
+ A function that calls at the end of each denoising steps during the inference. The function is called
732
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
733
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
734
+ `callback_on_step_end_tensor_inputs`.
735
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
736
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
737
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
738
+ `._callback_tensor_inputs` attribute of your pipeline class.
739
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
740
+
741
+ Examples:
742
+
743
+ Returns:
744
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
745
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
746
+ images.
747
+ """
748
+
749
+ height = height or self.default_sample_size * self.vae_scale_factor
750
+ width = width or self.default_sample_size * self.vae_scale_factor
751
+
752
+ # 1. Check inputs. Raise error if not correct
753
+ self.check_inputs(
754
+ prompt,
755
+ prompt_2,
756
+ inverted_latents,
757
+ image_latents,
758
+ latent_image_ids,
759
+ height,
760
+ width,
761
+ start_timestep,
762
+ stop_timestep,
763
+ prompt_embeds=prompt_embeds,
764
+ pooled_prompt_embeds=pooled_prompt_embeds,
765
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
766
+ max_sequence_length=max_sequence_length,
767
+ )
768
+
769
+ self._guidance_scale = guidance_scale
770
+ self._joint_attention_kwargs = joint_attention_kwargs
771
+ self._interrupt = False
772
+ do_rf_inversion = inverted_latents is not None
773
+
774
+ # 2. Define call parameters
775
+ if prompt is not None and isinstance(prompt, str):
776
+ batch_size = 1
777
+ elif prompt is not None and isinstance(prompt, list):
778
+ batch_size = len(prompt)
779
+ else:
780
+ batch_size = prompt_embeds.shape[0]
781
+
782
+ device = self._execution_device
783
+
784
+ lora_scale = (
785
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
786
+ )
787
+ (
788
+ prompt_embeds,
789
+ pooled_prompt_embeds,
790
+ text_ids,
791
+ ) = self.encode_prompt(
792
+ prompt=prompt,
793
+ prompt_2=prompt_2,
794
+ prompt_embeds=prompt_embeds,
795
+ pooled_prompt_embeds=pooled_prompt_embeds,
796
+ device=device,
797
+ num_images_per_prompt=num_images_per_prompt,
798
+ max_sequence_length=max_sequence_length,
799
+ lora_scale=lora_scale,
800
+ )
801
+
802
+ # 4. Prepare latent variables
803
+ num_channels_latents = self.transformer.config.in_channels // 4
804
+ if do_rf_inversion:
805
+ latents = inverted_latents
806
+ else:
807
+ latents, latent_image_ids = self.prepare_latents(
808
+ batch_size * num_images_per_prompt,
809
+ num_channels_latents,
810
+ height,
811
+ width,
812
+ prompt_embeds.dtype,
813
+ device,
814
+ generator,
815
+ latents,
816
+ )
817
+
818
+ # 5. Prepare timesteps
819
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
820
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
821
+ mu = calculate_shift(
822
+ image_seq_len,
823
+ self.scheduler.config.base_image_seq_len,
824
+ self.scheduler.config.max_image_seq_len,
825
+ self.scheduler.config.base_shift,
826
+ self.scheduler.config.max_shift,
827
+ )
828
+ timesteps, num_inference_steps = retrieve_timesteps(
829
+ self.scheduler,
830
+ num_inference_steps,
831
+ device,
832
+ timesteps,
833
+ sigmas,
834
+ mu=mu,
835
+ )
836
+ if do_rf_inversion:
837
+ start_timestep = int(start_timestep * num_inference_steps)
838
+ stop_timestep = min(int(stop_timestep * num_inference_steps), num_inference_steps)
839
+ timesteps, sigmas, num_inference_steps = self.get_timesteps(num_inference_steps, strength)
840
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
841
+ self._num_timesteps = len(timesteps)
842
+
843
+ # handle guidance
844
+ if self.transformer.config.guidance_embeds:
845
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
846
+ guidance = guidance.expand(latents.shape[0])
847
+ else:
848
+ guidance = None
849
+
850
+ if do_rf_inversion:
851
+ y_0 = image_latents.clone()
852
+ # 6. Denoising loop / Controlled Reverse ODE, Algorithm 2 from: https://arxiv.org/pdf/2410.10792
853
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
854
+ for i, t in enumerate(timesteps):
855
+ if do_rf_inversion:
856
+ # ti (current timestep) as annotated in algorithm 2 - i/num_inference_steps.
857
+ t_i = 1 - t / 1000
858
+ dt = torch.tensor(1 / (len(timesteps) - 1), device=device)
859
+
860
+ if self.interrupt:
861
+ continue
862
+
863
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
864
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
865
+
866
+ noise_pred = self.transformer(
867
+ hidden_states=latents,
868
+ timestep=timestep / 1000,
869
+ guidance=guidance,
870
+ pooled_projections=pooled_prompt_embeds,
871
+ encoder_hidden_states=prompt_embeds,
872
+ txt_ids=text_ids,
873
+ img_ids=latent_image_ids,
874
+ joint_attention_kwargs=self.joint_attention_kwargs,
875
+ return_dict=False,
876
+ )[0]
877
+
878
+ latents_dtype = latents.dtype
879
+ if do_rf_inversion:
880
+ v_t = -noise_pred
881
+ v_t_cond = (y_0 - latents) / (1 - t_i)
882
+ eta_t = eta if start_timestep <= i < stop_timestep else 0.0
883
+ if start_timestep <= i < stop_timestep:
884
+ # controlled vector field
885
+ v_hat_t = v_t + eta * (v_t_cond - v_t)
886
+
887
+ else:
888
+ v_hat_t = v_t
889
+
890
+ # SDE Eq: 17 from https://arxiv.org/pdf/2410.10792
891
+ latents = latents + v_hat_t * (sigmas[i] - sigmas[i + 1])
892
+ else:
893
+ # compute the previous noisy sample x_t -> x_t-1
894
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
895
+
896
+ if latents.dtype != latents_dtype:
897
+ if torch.backends.mps.is_available():
898
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
899
+ latents = latents.to(latents_dtype)
900
+
901
+ if callback_on_step_end is not None:
902
+ callback_kwargs = {}
903
+ for k in callback_on_step_end_tensor_inputs:
904
+ callback_kwargs[k] = locals()[k]
905
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
906
+
907
+ latents = callback_outputs.pop("latents", latents)
908
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
909
+
910
+ # call the callback, if provided
911
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
912
+ progress_bar.update()
913
+
914
+ if XLA_AVAILABLE:
915
+ xm.mark_step()
916
+
917
+ if output_type == "latent":
918
+ image = latents
919
+
920
+ else:
921
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
922
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
923
+ image = self.vae.decode(latents, return_dict=False)[0]
924
+ image = self.image_processor.postprocess(image, output_type=output_type)
925
+
926
+ # Offload all models
927
+ self.maybe_free_model_hooks()
928
+
929
+ if not return_dict:
930
+ return (image,)
931
+
932
+ return FluxPipelineOutput(images=image)
933
+
934
+ @torch.no_grad()
935
+ def invert(
936
+ self,
937
+ image: PipelineImageInput,
938
+ source_prompt: str = "",
939
+ source_guidance_scale=0.0,
940
+ num_inversion_steps: int = 28,
941
+ strength: float = 1.0,
942
+ gamma: float = 0.5,
943
+ height: Optional[int] = None,
944
+ width: Optional[int] = None,
945
+ timesteps: List[int] = None,
946
+ dtype: Optional[torch.dtype] = None,
947
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
948
+ ):
949
+ r"""
950
+ Performs Algorithm 1: Controlled Forward ODE from https://arxiv.org/pdf/2410.10792
951
+ Args:
952
+ image (`PipelineImageInput`):
953
+ Input for the image(s) that are to be edited. Multiple input images have to default to the same aspect
954
+ ratio.
955
+ source_prompt (`str` or `List[str]`, *optional* defaults to an empty prompt as done in the original paper):
956
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
957
+ instead.
958
+ source_guidance_scale (`float`, *optional*, defaults to 0.0):
959
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
960
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
961
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). For this algorithm, it's better to keep it 0.
962
+ num_inversion_steps (`int`, *optional*, defaults to 28):
963
+ The number of discretization steps.
964
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
965
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
966
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
967
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
968
+ gamma (`float`, *optional*, defaults to 0.5):
969
+ The controller guidance for the forward ODE, balancing faithfulness & editability:
970
+ higher eta - better faithfullness, less editability. For more significant edits, lower the value of eta.
971
+ timesteps (`List[int]`, *optional*):
972
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
973
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
974
+ passed will be used. Must be in descending order.
975
+ """
976
+ dtype = dtype or self.text_encoder.dtype
977
+ batch_size = 1
978
+ self._joint_attention_kwargs = joint_attention_kwargs
979
+ num_channels_latents = self.transformer.config.in_channels // 4
980
+
981
+ height = height or self.default_sample_size * self.vae_scale_factor
982
+ width = width or self.default_sample_size * self.vae_scale_factor
983
+ device = self._execution_device
984
+
985
+ # 1. prepare image
986
+ image_latents, _ = self.encode_image(image, height=height, width=width, dtype=dtype)
987
+ image_latents, latent_image_ids = self.prepare_latents_inversion(
988
+ batch_size, num_channels_latents, height, width, dtype, device, image_latents
989
+ )
990
+
991
+ # 2. prepare timesteps
992
+ sigmas = np.linspace(1.0, 1 / num_inversion_steps, num_inversion_steps)
993
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
994
+ mu = calculate_shift(
995
+ image_seq_len,
996
+ self.scheduler.config.base_image_seq_len,
997
+ self.scheduler.config.max_image_seq_len,
998
+ self.scheduler.config.base_shift,
999
+ self.scheduler.config.max_shift,
1000
+ )
1001
+ timesteps, num_inversion_steps = retrieve_timesteps(
1002
+ self.scheduler,
1003
+ num_inversion_steps,
1004
+ device,
1005
+ timesteps,
1006
+ sigmas,
1007
+ mu=mu,
1008
+ )
1009
+ timesteps, sigmas, num_inversion_steps = self.get_timesteps(num_inversion_steps, strength)
1010
+
1011
+ # 3. prepare text embeddings
1012
+ (
1013
+ prompt_embeds,
1014
+ pooled_prompt_embeds,
1015
+ text_ids,
1016
+ ) = self.encode_prompt(
1017
+ prompt=source_prompt,
1018
+ prompt_2=source_prompt,
1019
+ device=device,
1020
+ )
1021
+ # 4. handle guidance
1022
+ if self.transformer.config.guidance_embeds:
1023
+ guidance = torch.full([1], source_guidance_scale, device=device, dtype=torch.float32)
1024
+ else:
1025
+ guidance = None
1026
+
1027
+ # Eq 8 dY_t = [u_t(Y_t) + γ(u_t(Y_t|y_1) - u_t(Y_t))]dt
1028
+ Y_t = image_latents
1029
+ y_1 = torch.randn_like(Y_t)
1030
+ N = len(sigmas)
1031
+
1032
+ # forward ODE loop
1033
+ with self.progress_bar(total=N - 1) as progress_bar:
1034
+ for i in range(N - 1):
1035
+ t_i = torch.tensor(i / (N), dtype=Y_t.dtype, device=device)
1036
+ timestep = torch.tensor(t_i, dtype=Y_t.dtype, device=device).repeat(batch_size)
1037
+
1038
+ # get the unconditional vector field
1039
+ u_t_i = self.transformer(
1040
+ hidden_states=Y_t,
1041
+ timestep=timestep,
1042
+ guidance=guidance,
1043
+ pooled_projections=pooled_prompt_embeds,
1044
+ encoder_hidden_states=prompt_embeds,
1045
+ txt_ids=text_ids,
1046
+ img_ids=latent_image_ids,
1047
+ joint_attention_kwargs=self.joint_attention_kwargs,
1048
+ return_dict=False,
1049
+ )[0]
1050
+
1051
+ # get the conditional vector field
1052
+ u_t_i_cond = (y_1 - Y_t) / (1 - t_i)
1053
+
1054
+ # controlled vector field
1055
+ # Eq 8 dY_t = [u_t(Y_t) + γ(u_t(Y_t|y_1) - u_t(Y_t))]dt
1056
+ u_hat_t_i = u_t_i + gamma * (u_t_i_cond - u_t_i)
1057
+ Y_t = Y_t + u_hat_t_i * (sigmas[i] - sigmas[i + 1])
1058
+ progress_bar.update()
1059
+
1060
+ # return the inverted latents (start point for the denoising loop), encoded image & latent image ids
1061
+ return Y_t, image_latents, latent_image_ids