Diffusers 文件
DeepFloyd IF
並獲得增強的文件體驗
開始使用
DeepFloyd IF
概述
DeepFloyd IF 是一個新穎的、最先進的開源文字到影像模型,具有高度的真實感和語言理解能力。該模型是一個模組化結構,由一個凍結的文字編碼器和三個級聯畫素擴散模組組成:
- 第一階段:一個基於文字提示生成 64x64 畫素影像的基礎模型;
- 第二階段:一個 64x64 畫素 => 256x256 畫素的超解析度模型;以及
- 第三階段:一個 256x256 畫素 => 1024x1024 畫素的超解析度模型。第一階段和第二階段利用基於 T5 變換器的凍結文字編碼器來提取文字嵌入,然後將其饋送到透過交叉注意力和注意力池化增強的 UNet 架構中。第三階段是 Stability AI 的 x4 Upscaling 模型。結果是一個高效的模型,效能優於當前最先進的模型,在 COCO 資料集上實現了 6.66 的零樣本 FID 分數。我們的工作強調了在級聯擴散模型第一階段中使用更大 UNet 架構的潛力,並描繪了文字到影像合成的 promising 未來。
用法
在使用 IF 之前,您需要接受其使用條件。為此:
- 確保擁有 Hugging Face 賬戶並已登入。
- 接受 DeepFloyd/IF-I-XL-v1.0 模型卡上的許可。在第一階段模型卡上接受許可將自動接受其他 IF 模型的許可。
- 確保在本地登入。安裝
huggingface_hub
pip install huggingface_hub --upgrade
在 Python shell 中執行登入函式
from huggingface_hub import login
login()
並輸入您的 Hugging Face Hub 訪問令牌。
接下來我們安裝 diffusers
和依賴項
pip install -q diffusers accelerate transformers
以下章節將更詳細地介紹如何使用 IF。具體來說:
可用檢查點
階段 1
階段 2
階段 3
文字到影像生成
預設情況下,Diffusers 利用模型 CPU 解除安裝功能,以低至 14 GB 的 VRAM 執行整個 IF 管道。
from diffusers import DiffusionPipeline
from diffusers.utils import pt_to_pil, make_image_grid
import torch
# stage 1
stage_1 = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator, output_type="pt"
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, noise_level=100, generator=generator).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=3)
文字引導影像到影像生成
相同的 IF 模型權重可用於文字引導的影像到影像轉換或影像變體。在這種情況下,只需確保使用 IFImg2ImgPipeline 和 IFImg2ImgSuperResolutionPipeline 管道載入權重。
注意:您還可以透過利用 components 引數直接將文字到影像管道的權重移動到影像到影像管道,而無需重複載入,如此處所述。
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
original_image = load_image(url)
original_image = original_image.resize((768, 512))
# stage 1
stage_1 = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFImg2ImgSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "A fantasy landscape in style minecraft"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=4)
文字引導影像修復生成
相同的 IF 模型權重可用於文字引導的影像到影像轉換或影像變體。在這種情況下,只需確保使用 IFInpaintingPipeline 和 IFInpaintingSuperResolutionPipeline 管道載入權重。
注意:您還可以透過利用 ~DiffusionPipeline.components()
函式直接將文字到影像管道的權重移動到影像到影像管道,而無需重複載入,如此處所述。
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
from diffusers.utils import pt_to_pil, load_image, make_image_grid
import torch
# download image
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
original_image = load_image(url)
# download mask
url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
mask_image = load_image(url)
# stage 1
stage_1 = IFInpaintingPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
stage_1.enable_model_cpu_offload()
# stage 2
stage_2 = IFInpaintingSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
)
stage_2.enable_model_cpu_offload()
# stage 3
safety_modules = {
"feature_extractor": stage_1.feature_extractor,
"safety_checker": stage_1.safety_checker,
"watermarker": stage_1.watermarker,
}
stage_3 = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
)
stage_3.enable_model_cpu_offload()
prompt = "blue sunglasses"
generator = torch.manual_seed(1)
# text embeds
prompt_embeds, negative_embeds = stage_1.encode_prompt(prompt)
# stage 1
stage_1_output = stage_1(
image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# stage 2
stage_2_output = stage_2(
image=stage_1_output,
original_image=original_image,
mask_image=mask_image,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
generator=generator,
output_type="pt",
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_II.png")
# stage 3
stage_3_output = stage_3(prompt=prompt, image=stage_2_output, generator=generator, noise_level=100).images
#stage_3_output[0].save("./if_stage_III.png")
make_image_grid([original_image, mask_image, pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0], stage_3_output[0]], rows=1, rows=5)
在不同管道之間轉換
除了使用 from_pretrained
載入外,管道還可以直接從彼此載入。
from diffusers import IFPipeline, IFSuperResolutionPipeline
pipe_1 = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0")
pipe_2 = IFSuperResolutionPipeline.from_pretrained("DeepFloyd/IF-II-L-v1.0")
from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline
pipe_1 = IFImg2ImgPipeline(**pipe_1.components)
pipe_2 = IFImg2ImgSuperResolutionPipeline(**pipe_2.components)
from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline
pipe_1 = IFInpaintingPipeline(**pipe_1.components)
pipe_2 = IFInpaintingSuperResolutionPipeline(**pipe_2.components)
速度最佳化
執行 IF 最簡單的最佳化是將其所有模型元件移動到 GPU。
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
pipe.to("cuda")
您還可以縮短擴散過程的步數。
這可以透過 num_inference_steps
引數完成。
pipe("<prompt>", num_inference_steps=30)
或者使用 timesteps
引數
from diffusers.pipelines.deepfloyd_if import fast27_timesteps
pipe("<prompt>", timesteps=fast27_timesteps)
在進行影像變體或影像修復時,您還可以透過強度引數減少時間步數。強度引數是要新增到輸入影像中的噪聲量,它還決定了去噪過程中要執行的步數。較小的值會減少影像的變化,但執行速度會更快。
pipe = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
pipe.to("cuda")
image = pipe(image=image, prompt="<prompt>", strength=0.3).images
您還可以使用 torch.compile
。請注意,我們尚未對 IF 進行窮盡測試 torch.compile
,它可能無法提供預期結果。
from diffusers import DiffusionPipeline
import torch
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
pipe.to("cuda")
pipe.text_encoder = torch.compile(pipe.text_encoder, mode="reduce-overhead", fullgraph=True)
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
記憶體最佳化
在最佳化 GPU 記憶體時,我們可以使用標準的 Diffusers CPU 解除安裝 API。
無論是基於模型的 CPU 解除安裝,
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
pipe.enable_model_cpu_offload()
還是更積極的基於層的 CPU 解除安裝。
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
pipe.enable_sequential_cpu_offload()
此外,T5 可以以 8 位精度載入
from transformers import T5EncoderModel
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
from diffusers import DiffusionPipeline
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt_embeds, negative_embeds = pipe.encode_prompt("<prompt>")
對於像 Google Colab 免費版這樣受限於 CPU RAM 的機器,我們無法一次性將所有模型元件載入到 CPU,因此我們可以在需要時手動載入帶有文字編碼器或 UNet 的管道。
from diffusers import IFPipeline, IFSuperResolutionPipeline
import torch
import gc
from transformers import T5EncoderModel
from diffusers.utils import pt_to_pil, make_image_grid
text_encoder = T5EncoderModel.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", subfolder="text_encoder", device_map="auto", load_in_8bit=True, variant="8bit"
)
# text to image
pipe = DiffusionPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0",
text_encoder=text_encoder, # pass the previously instantiated 8bit text encoder
unet=None,
device_map="auto",
)
prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
# Remove the pipeline so we can re-load the pipeline with the unet
del text_encoder
del pipe
gc.collect()
torch.cuda.empty_cache()
pipe = IFPipeline.from_pretrained(
"DeepFloyd/IF-I-XL-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_1_output = pipe(
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_1_output)[0].save("./if_stage_I.png")
# Remove the pipeline so we can load the super-resolution pipeline
del pipe
gc.collect()
torch.cuda.empty_cache()
# First super resolution
pipe = IFSuperResolutionPipeline.from_pretrained(
"DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16, device_map="auto"
)
generator = torch.Generator().manual_seed(0)
stage_2_output = pipe(
image=stage_1_output,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_embeds,
output_type="pt",
generator=generator,
).images
#pt_to_pil(stage_2_output)[0].save("./if_stage_II.png")
make_image_grid([pt_to_pil(stage_1_output)[0], pt_to_pil(stage_2_output)[0]], rows=1, rows=2)
可用管道:
流水線 | 任務 | Colab |
---|---|---|
pipeline_if.py | 文字到影像生成 | - |
pipeline_if_superresolution.py | 文字到影像生成 | - |
pipeline_if_img2img.py | 影像到影像生成 | - |
pipeline_if_img2img_superresolution.py | 影像到影像生成 | - |
pipeline_if_inpainting.py | 影像到影像生成 | - |
pipeline_if_inpainting_superresolution.py | 影像到影像生成 | - |
IFPipeline
class diffusers.IFPipeline
< 來源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 100 timesteps: typing.List[int] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 height: typing.Optional[int] = None width: typing.Optional[int] = None eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 clean_caption: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞prompt_embeds
。 - num_inference_steps (
int
, 可選, 預設為 100) — 去噪步數。更多的去噪步數通常會帶來更高的影像質量,但推理速度會變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,則使用等間距的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 7.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
在 Imagen Paper 的公式 2 中定義為w
。透過設定guidance_scale > 1
啟用引導比例。較高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞negative_prompt_embeds
。在不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示要生成的影像數量。 - height (
int
, 可選, 預設為 self.unet.config.sample_size) — 生成影像的畫素高度。 - width (
int
, 可選, 預設為 self.unet.config.sample_size) — 生成影像的畫素寬度。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成過程具有確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如 提示加權。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如 提示加權。如果未提供,負文字嵌入將從negative_prompt
輸入引數生成。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。在 PIL:PIL.Image.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 在推理過程中,每callback_steps
步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,回撥將在每一步呼叫。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理標題。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,嵌入將從原始提示建立。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,它將作為引數傳遞給AttentionProcessor
,其定義位於 diffusers.models.attention_processor 中的self.processor
。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt"
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> safety_modules = {
... "feature_extractor": pipe.feature_extractor,
... "safety_checker": pipe.safety_checker,
... "watermarker": pipe.watermarker,
... }
>>> super_res_2_pipe = DiffusionPipeline.from_pretrained(
... "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16
... )
>>> super_res_2_pipe.enable_model_cpu_offload()
>>> image = super_res_2_pipe(
... prompt=prompt,
... image=image,
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< 來源 >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用無分類器引導 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞應生成的影像數量 - device — (
torch.device
, 可選): 用於放置結果嵌入的 torch 裝置 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞negative_prompt_embeds
。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,負面提示詞嵌入將從negative_prompt
輸入引數生成。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前對提供的標題進行預處理和清理。
將提示編碼為文字編碼器隱藏狀態。
IFSuperResolutionPipeline
class diffusers.IFSuperResolutionPipeline
< 來源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None height: int = None width: int = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 4.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 250 clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 引導影像生成的提示詞。如果未定義,則必須傳遞prompt_embeds
。 - height (
int
, 可選, 預設為 None) — 生成影像的畫素高度。 - width (
int
, 可選, 預設為 None) — 生成影像的畫素寬度。 - image (
PIL.Image.Image
,np.ndarray
,torch.Tensor
) — 待放大的影像。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常能生成更高質量的影像,但會以較慢的推理速度為代價。 - timesteps (
List[int]
, 可選, 預設為 None) — 用於去噪過程的自定義時間步。如果未定義,則使用等間隔的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 4.0) — 如 無分類器擴散引導 中定義的引導比例。guidance_scale
定義為 Imagen 論文 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。較高的引導比例鼓勵生成與文字prompt
緊密相關的影像,但通常會以較低的影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,使生成具有確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,負面提示詞嵌入將從negative_prompt
輸入引數生成。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 一個函式,將在推理過程中每隔callback_steps
步被呼叫。該函式將使用以下引數被呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,將在每一步呼叫回撥函式。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,它將作為引數傳遞給AttentionProcessor
,其定義位於 diffusers.models.attention_processor 中的self.processor
。 - noise_level (
int
, 可選, 預設為 250) — 新增到放大影像中的噪聲量。必須在[0, 1000)
範圍內。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理標題。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,嵌入將從原始提示詞建立。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFPipeline, IFSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
>>> pipe.enable_model_cpu_offload()
>>> prompt = 'a photo of a kangaroo wearing an orange hoodie and blue sunglasses standing in front of the eiffel tower holding a sign that says "very deep learning"'
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, output_type="pt").images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< 來源 >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用無分類器引導 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞應生成的影像數量 - device — (
torch.device
, 可選): 用於放置結果嵌入的 torch 裝置 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞negative_prompt_embeds
。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,負面提示詞嵌入將從negative_prompt
輸入引數生成。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前對提供的標題進行預處理和清理。
將提示編碼為文字編碼器隱藏狀態。
IFImg2ImgPipeline
class diffusers.IFImg2ImgPipeline
< 來源 >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.7 num_inference_steps: int = 80 timesteps: typing.List[int] = None guidance_scale: float = 10.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 clean_caption: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳遞prompt_embeds
。 - image (
torch.Tensor
或PIL.Image.Image
) —Image
,或表示影像批次的張量,將用作過程的起點。 - strength (
float
, 可選, 預設為 0.7) — 概念上,表示對參考image
的轉換程度。必須在 0 到 1 之間。image
將用作起點,strength
越大,新增的噪聲越多。去噪步數取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲將最大,去噪過程將執行num_inference_steps
中指定的所有迭代次數。因此,值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 80) — 去噪步數。更多的去噪步數通常能生成更高質量的影像,但會以較慢的推理速度為代價。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,將使用等間隔的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 10.0) — 如 無分類器擴散引導 中定義的引導比例。guidance_scale
定義為 Imagen 論文 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。較高的引導比例鼓勵生成與文字prompt
緊密相關的影像,但通常會以較低的影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 在推理過程中,每callback_steps
步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,則在每個步驟都將呼叫回撥函式。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理字幕。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,嵌入將從原始提示詞建立。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為self.processor
中定義的AttentionProcessor
的引數傳遞給 diffusers.models.attention_processor。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用分類器自由引導。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞應生成的影像數量。 - device — (
torch.device
, 可選): 放置結果嵌入的 torch 裝置。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前對提供的字幕進行預處理和清理。
將提示編碼為文字編碼器隱藏狀態。
IFImg2ImgSuperResolutionPipeline
class diffusers.IFImg2ImgSuperResolutionPipeline
< source >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.8 prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 4.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 250 clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- image (
torch.Tensor
或PIL.Image.Image
) — 將用作過程起點的影像或表示影像批次的張量。 - original_image (
torch.Tensor
或PIL.Image.Image
) —image
派生自的原始影像。 - strength (
float
, 可選, 預設為 0.8) — 概念上,表示轉換參考image
的程度。必須介於 0 和 1 之間。image
將用作起始點,strength
越大,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲將最大,去噪過程將執行num_inference_steps
中指定的完整迭代次數。因此,值為 1 基本上會忽略image
。 - prompt (
str
或List[str]
, 可選) — 引導影像生成的提示詞。如果未定義,則必須傳入prompt_embeds
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但會以較慢的推理速度為代價。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,將使用等間距的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 4.0) — Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成具有確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 在推理過程中,每callback_steps
步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,則在每個步驟都將呼叫回撥函式。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為self.processor
中定義的AttentionProcessor
的引數傳遞給 diffusers.models.attention_processor。 - noise_level (
int
, 可選, 預設為 250) — 新增到升級影像中的噪聲量。必須在[0, 1000)
範圍內。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理字幕。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,嵌入將從原始提示詞建立。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFImg2ImgPipeline, IFImg2ImgSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image.resize((768, 512))
>>> pipe = IFImg2ImgPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0",
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "A fantasy landscape in style minecraft"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0",
... text_encoder=None,
... variant="fp16",
... torch_dtype=torch.float16,
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用分類器自由引導。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞應生成的影像數量。 - device — (
torch.device
, 可選): 放置結果嵌入的 torch 裝置。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前對提供的字幕進行預處理和清理。
將提示編碼為文字編碼器隱藏狀態。
IFInpaintingPipeline
class diffusers.IFInpaintingPipeline
< source >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 1.0 num_inference_steps: int = 50 timesteps: typing.List[int] = None guidance_scale: float = 7.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 clean_caption: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳入prompt_embeds
。 - image (
torch.Tensor
或PIL.Image.Image
) —Image
,或表示影像批次的張量,將用作過程的起始點。 - mask_image (
PIL.Image.Image
) —Image
,或表示影像批次的張量,用於遮蓋image
。遮罩中的白色畫素將被重新繪製,而黑色畫素將保留。如果mask_image
是 PIL 影像,它在使用前將被轉換為單通道(亮度)。如果是張量,它應該包含一個顏色通道 (L) 而不是 3 個,因此預期形狀為(B, H, W, 1)
。 - strength (
float
, 可選, 預設為 1.0) — 概念上表示要轉換參考image
的程度。必須介於 0 和 1 之間。image
將用作起始點,strength
越大,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲將達到最大值,去噪過程將執行num_inference_steps
中指定的所有迭代次數。因此,值為 1 基本上會忽略image
。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,將使用等間距的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 7.0) — 如 Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略此引數。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成負面提示詞嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 在推理過程中每callback_steps
步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,回撥將在每個步驟中呼叫。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理標題。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,則將從原始提示詞建立嵌入。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,則傳遞給 diffusers.models.attention_processor 中self.processor
下定義的AttentionProcessor
。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用無分類器引導 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞應生成的影像數量 - device — (
torch.device
, 可選): 放置結果嵌入的 torch 裝置 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略此引數。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成負面提示詞嵌入。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前對提供的標題進行預處理和清理。
將提示編碼為文字編碼器隱藏狀態。
IFInpaintingSuperResolutionPipeline
class diffusers.IFInpaintingSuperResolutionPipeline
< source >( tokenizer: T5Tokenizer text_encoder: T5EncoderModel unet: UNet2DConditionModel scheduler: DDPMScheduler image_noising_scheduler: DDPMScheduler safety_checker: typing.Optional[diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker] feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] watermarker: typing.Optional[diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker] requires_safety_checker: bool = True )
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] original_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None mask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, typing.List[PIL.Image.Image], typing.List[torch.Tensor], typing.List[numpy.ndarray]] = None strength: float = 0.8 prompt: typing.Union[str, typing.List[str]] = None num_inference_steps: int = 100 timesteps: typing.List[int] = None guidance_scale: float = 4.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None noise_level: int = 0 clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
引數
- image (
torch.Tensor
或PIL.Image.Image
) —Image
,或表示影像批次的張量,將用作過程的起始點。 - original_image (
torch.Tensor
或PIL.Image.Image
) —image
變體自的原始影像。 - mask_image (
PIL.Image.Image
) —Image
,或表示影像批次的張量,用於遮蓋image
。遮罩中的白色畫素將被重新繪製,而黑色畫素將保留。如果mask_image
是 PIL 影像,它在使用前將被轉換為單通道(亮度)。如果是張量,它應該包含一個顏色通道 (L) 而不是 3 個,因此預期形狀為(B, H, W, 1)
。 - strength (
float
, 可選, 預設為 0.8) — 概念上表示要轉換參考image
的程度。必須介於 0 和 1 之間。image
將用作起始點,strength
越大,新增的噪聲越多。去噪步驟的數量取決於最初新增的噪聲量。當strength
為 1 時,新增的噪聲將達到最大值,去噪過程將執行num_inference_steps
中指定的所有迭代次數。因此,值為 1 基本上會忽略image
。 - prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則必須傳入prompt_embeds
。 - num_inference_steps (
int
, 可選, 預設為 100) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步。如果未定義,將使用等間距的num_inference_steps
時間步。必須按降序排列。 - guidance_scale (
float
, 可選, 預設為 4.0) — 如 Classifier-Free Diffusion Guidance 中定義的引導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用引導比例。更高的引導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影像質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
),則忽略此引數。 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示詞生成的影像數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η): https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch 生成器,用於使生成確定性。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞權重。如果未提供,將從negative_prompt
輸入引數生成負面提示詞嵌入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影像的輸出格式。選擇 PIL:PIL.Image.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion.IFPipelineOutput
而不是普通元組。 - callback (
Callable
, 可選) — 在推理過程中每callback_steps
步都會呼叫的函式。該函式將使用以下引數呼叫:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可選, 預設為 1) — 呼叫callback
函式的頻率。如果未指定,回撥將在每個步驟中呼叫。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,則傳遞給 diffusers.models.attention_processor 中self.processor
下定義的AttentionProcessor
。 - noise_level (
int
, 可選, 預設為 0) — 要新增到放大影像的噪聲量。必須在[0, 1000)
範圍內。 - clean_caption (
bool
, 可選, 預設為True
) — 是否在建立嵌入之前清理標題。需要安裝beautifulsoup4
和ftfy
。如果未安裝依賴項,則將從原始提示詞建立嵌入。
返回
~pipelines.stable_diffusion.IFPipelineOutput
或 tuple
如果 return_dict
為 True,則返回 ~pipelines.stable_diffusion.IFPipelineOutput
,否則返回一個 tuple
。返回元組時,第一個元素是生成的影像列表,第二個元素是布林值列表,根據 safety_checker
指示相應生成的影像是否可能表示“不適合工作”(nsfw) 或帶有水印的內容。
呼叫管道進行生成時呼叫的函式。
示例
>>> from diffusers import IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, DiffusionPipeline
>>> from diffusers.utils import pt_to_pil
>>> import torch
>>> from PIL import Image
>>> import requests
>>> from io import BytesIO
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/person.png"
>>> response = requests.get(url)
>>> original_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> original_image = original_image
>>> url = "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/if/glasses_mask.png"
>>> response = requests.get(url)
>>> mask_image = Image.open(BytesIO(response.content))
>>> mask_image = mask_image
>>> pipe = IFInpaintingPipeline.from_pretrained(
... "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "blue sunglasses"
>>> prompt_embeds, negative_embeds = pipe.encode_prompt(prompt)
>>> image = pipe(
... image=original_image,
... mask_image=mask_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... output_type="pt",
... ).images
>>> # save intermediate image
>>> pil_image = pt_to_pil(image)
>>> pil_image[0].save("./if_stage_I.png")
>>> super_res_1_pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
... "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16
... )
>>> super_res_1_pipe.enable_model_cpu_offload()
>>> image = super_res_1_pipe(
... image=image,
... mask_image=mask_image,
... original_image=original_image,
... prompt_embeds=prompt_embeds,
... negative_prompt_embeds=negative_embeds,
... ).images
>>> image[0].save("./if_stage_II.png")
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] do_classifier_free_guidance: bool = True num_images_per_prompt: int = 1 device: typing.Optional[torch.device] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None clean_caption: bool = False )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示詞 - do_classifier_free_guidance (
bool
, 可選, 預設為True
) — 是否使用分類器自由引導 - num_images_per_prompt (
int
, 可選, 預設為 1) — 每個提示應生成的影像數量 - device — (
torch.device
, 可選): 放置結果嵌入的 torch 裝置 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳入negative_prompt_embeds
。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
則忽略),此引數將被忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - clean_caption (bool, 預設為
False
) — 如果為True
,函式將在編碼前預處理並清理提供的標題。
將提示編碼為文字編碼器隱藏狀態。