Diffusers documentation
DeepFloyd IF
DeepFloyd IF
개요
DeepFloyd IF는 사진 같은 사실성과 언어 이해도가 높은 최신 오픈소스 텍스트-이미지 생성 모델입니다. 이 모델은 동결된 텍스트 인코더와 세 개의 연쇄된 픽셀 디퓨전 모듈로 구성된 모듈형 아키텍처입니다:
- Stage 1: 텍스트 프롬프트를 기반으로 64x64 px 이미지를 생성하는 베이스 모델,
- Stage 2: 64x64 px => 256x256 px 초해상도 모델, 그리고
- Stage 3: 256x256 px => 1024x1024 px 초해상도 모델 Stage 1과 Stage 2는 T5 transformer 기반의 동결된 텍스트 인코더를 사용하여 텍스트 임베딩을 추출한 후, 크로스 어텐션과 어텐션 풀링으로 강화된 UNet 아키텍처에 입력합니다. Stage 3은 Stability AI의 x4 업스케일링 모델입니다. 그 결과, COCO 데이터셋에서 제로샷 FID 점수 6.66을 달성하여 현재 최첨단 모델보다 우수한 성능을 보이는 매우 효율적인 모델이 탄생했습니다. 우리의 연구는 캐스케이드 확산 모델의 첫 번째 단계에서 더 큰 UNet 아키텍처의 잠재력을 강조하며, 텍스트-이미지 합성의 유망한 미래를 보여줍니다.
사용
IF를 사용하기 전에 사용 조건을 수락해야 합니다. 이를 위해:
- Hugging Face 계정이 있고 로그인되어 있는지 확인하세요.
- DeepFloyd/IF-I-XL-v1.0 모델 카드에서 라이선스를 수락하세요. Stage I 모델 카드에서 라이선스를 수락하면 다른 IF 모델에 대해서도 자동으로 수락됩니다.
- 로컬에서 로그인했는지 확인하세요.
huggingface_hub를 설치합니다:
pip install huggingface_hub --upgrade
Python 셸에서 로그인 함수를 실행합니다:
from huggingface_hub import login
login()그리고 Hugging Face Hub 액세스 토큰을 입력하세요.
다음으로 diffusers와 종속성을 설치합니다:
pip install -q diffusers accelerate transformers
다음 섹션에서는 IF를 사용하는 방법에 대한 더 자세한 예시를 제공합니다. 구체적으로:
사용 가능한 체크포인트
1단계
2단계
Stage-3
텍스트-이미지 생성
기본적으로 diffusers는 model cpu offloading을 사용하여 VRAM 14 GB만으로 전체 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", 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", 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, 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", 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", 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, 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", 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", 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, 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를 통해 로드하는 것 외에도, Pipelines는 서로 직접 로드할 수도 있습니다.
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", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"더 적은 수의 timesteps로 diffusion 프로세스를 실행할 수도 있습니다.
num_inference_steps 인수를 사용하여 수행할 수 있습니다:
pipe("<prompt>", num_inference_steps=30)또는 timesteps 인수를 사용하여:
from diffusers.pipelines.deepfloyd_if import fast27_timesteps
pipe("<prompt>", timesteps=fast27_timesteps)이미지 변형 또는 inpainting을 수행할 때 strength 인수를 사용하여 timestep 수를 줄일 수도 있습니다. strength 인수는 입력 이미지에 추가할 노이즈의 양을 나타내며, 이는 노이즈 제거 과정에서 실행할 단계 수를 결정합니다. 값이 작을수록 이미지가 덜 변형되지만 실행 속도는 빨라집니다.
pipe = IFImg2ImgPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(image=image, prompt="<prompt>", strength=0.3).imagestorch.compile도 사용할 수 있습니다. IF와 torch.compile을 포괄적으로 테스트하지 않았으며, 예상된 결과를 제공하지 못할 수 있습니다.
from diffusers import DiffusionPipeline
import torch
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
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", dtype=torch.float16)
pipe.enable_model_cpu_offload()또는 보다 공격적인 레이어 기반 CPU 오프로딩
pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", dtype=torch.float16)
pipe.enable_sequential_cpu_offload()또한, T5는 8bit 정밀도로 로드할 수 있습니다
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", 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", 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)사용 가능한 파이프라인:
| Pipeline | 작업 | 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
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1height: int | None = Nonewidth: int | None = Noneeta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple
매개변수
- prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 대신 전달해야 합니다. - num_inference_steps (
int, 선택 사항, 기본값 100) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - timesteps (
list[int], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - guidance_scale (
float, 선택 사항, 기본값 7.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 방정식 2의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
IFSuperResolutionPipeline
class diffusers.IFSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneheight: int = Nonewidth: int = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or 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) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - 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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - noise_level (
int, 선택 사항, 기본값 250) — 업스케일된 이미지에 추가할 노이즈의 양입니다.[0, 1000)범위에 있어야 합니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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
< source >( prompt: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
IFImg2ImgPipeline
클래스 diffusers.IFImg2ImgPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.7num_inference_steps: int = 80timesteps: list = Noneguidance_scale: float = 10.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or 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], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - guidance_scale (
float, 선택 사항, 기본값 10.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 방정식 2의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
IFImg2ImgSuperResolutionPipeline
class diffusers.IFImg2ImgSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_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, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 250clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple
매개변수
- image (
torch.Tensor또는PIL.Image.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], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - 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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - noise_level (
int, 선택 사항, 기본값 250) — 업스케일된 이미지에 추가할 노이즈의 양입니다.[0, 1000)범위에 있어야 합니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
IFInpaintingPipeline
class diffusers.IFInpaintingPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_safety_checker: bool = True )
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 1.0num_inference_steps: int = 50timesteps: list = Noneguidance_scale: float = 7.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1clean_caption: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = None ) → ~pipelines.stable_diffusion.IFPipelineOutput or tuple
매개변수
- prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 대신 전달해야 합니다. - image (
torch.Tensor또는PIL.Image.Image) — 프로세스의 시작점으로 사용될Image또는 이미지 배치 텐서. - mask_image (
PIL.Image.Image) —Image또는 이미지 배치 텐서로,image에 마스킹할 대상입니다. 마스크의 흰색 픽셀은 다시 채워지고, 검은색 픽셀은 유지됩니다.mask_image가 PIL 이미지인 경우, 사용 전에 단일 채널(휘도)로 변환됩니다. 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, 예상되는 형태는(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], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - guidance_scale (
float, 선택 사항, 기본값 7.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 방정식 2의w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
IFInpaintingSuperResolutionPipeline
class diffusers.IFInpaintingSuperResolutionPipeline
< source >( tokenizer: T5Tokenizertext_encoder: T5EncoderModelunet: UNet2DConditionModelscheduler: DDPMSchedulerimage_noising_scheduler: DDPMSchedulersafety_checker: diffusers.pipelines.deepfloyd_if.safety_checker.IFSafetyChecker | Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | Nonewatermarker: diffusers.pipelines.deepfloyd_if.watermark.IFWatermarker | Nonerequires_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, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonemask_image: typing.Union[PIL.Image.Image, torch.Tensor, numpy.ndarray, list[PIL.Image.Image], list[torch.Tensor], list[numpy.ndarray]] = Nonestrength: float = 0.8prompt: str | list[str] = Nonenum_inference_steps: int = 100timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = Nonecallback_steps: int = 1cross_attention_kwargs: dict[str, typing.Any] | None = Nonenoise_level: int = 0clean_caption: bool = True ) → ~pipelines.stable_diffusion.IFPipelineOutput or 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 이미지인 경우, 사용 전에 단일 채널(휘도)로 변환됩니다. 텐서인 경우 3개 대신 하나의 색상 채널(L)을 포함해야 하므로, 예상되는 형태는(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], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - 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 generator 하나 또는 목록 - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면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함수가 호출되는 주기입니다. 지정하지 않으면 callback은 모든 단계에서 호출됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - noise_level (
int, 선택 사항, 기본값 0) — 업스케일된 이미지에 추가할 노이즈의 양입니다.[0, 1000)범위에 있어야 합니다. - clean_caption (
bool, 선택 사항, 기본값True) — 임베딩을 생성하기 전에 캡션을 정리할지 여부입니다.beautifulsoup4와ftfy가 설치되어 있어야 합니다. 의존성이 설치되지 않은 경우, 임베딩은 원본 프롬프트에서 생성됩니다.
반환값
~pipelines.stable_diffusion.IFPipelineOutput 또는 tuple
~pipelines.stable_diffusion.IFPipelineOutput if return_dict is True, otherwise a tuple. When returning a tuple, the first element is a list with the generated images, and the second element is a list of bools denoting whether the corresponding generated image likely represents "not-safe-for-work" (nsfw) or watermarked content, according to the safety_checker`.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> 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: str | list[str]do_classifier_free_guidance: bool = Truenum_images_per_prompt: int = 1device: typing.Optional[torch.device] = Nonenegative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneclean_caption: bool = False )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - do_classifier_free_guidance (
bool, 선택 사항, 기본값True) — classifier free guidance를 사용할지 여부 - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지 수 - device — (
torch.device, 선택 사항): 결과 임베딩을 배치할 torch device - 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 text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - clean_caption (bool, 기본값
False) —True인 경우, 인코딩 전에 제공된 캡션을 전처리하고 정리합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.