Diffusers documentation
LEDITS++
LEDITS++
LEDITS++는 Manuel Brack, Felix Friedrich, Katharina Kornmeier, Linoy Tsaban, Patrick Schramowski, Kristian Kersting, Apolinário Passos가 LEDITS++: Limitless Image Editing using Text-to-Image Models에서 제안했습니다.
해당 논문의 초록은 다음과 같습니다:
텍스트-이미지 확산 모델은 텍스트 입력만으로 높은 충실도의 이미지를 생성하는 놀라운 능력 덕분에 최근 큰 관심을 받고 있습니다. 후속 연구들은 이러한 기능을 활용하여 실제 이미지 편집에 적용하는 것을 목표로 합니다. 그러나 기존 이미지-이미지 방법은 비효율적이고 부정확하며 범용성이 제한적인 경우가 많습니다. 이들은 시간 소모적인 미세 조정을 요구하거나, 입력 이미지에서 불필요하게 크게 벗어나거나, 여러 개의 동시 편집을 지원하지 못합니다. 이러한 문제를 해결하기 위해, 효율적이면서도 범용적이고 정확한 텍스트 기반 이미지 조작 기법인 LEDITS++를 소개합니다. LEDITS++의 새로운 역전(inversion) 접근법은 튜닝이나 최적화가 필요하지 않으며, 몇 단계의 확산 단계만으로 높은 충실도의 결과를 생성합니다. 두 번째로, 우리의 방법론은 여러 개의 동시 편집을 지원하며 아키텍처에 무관합니다. 세 번째로, 변경 사항을 관련 이미지 영역으로 제한하는 새로운 암시적 마스킹 기법을 사용합니다. 포괄적인 평가의 일부로 새로운 TEdBench++ 벤치마크를 제안합니다. 우리의 결과는 LEDITS++의 기능과 이전 방법들에 비해의 개선점을 보여줍니다. 프로젝트 페이지는 https://leditsplusplus-project.static.hf.space 에서 확인할 수 있습니다.
현재 diffusers의 DPMSolverMultistepScheduler 구현에는 일부 역호환성 문제가 있어, 이 LEdits++ 구현은 더 이상 완벽한 역전(inversion)을 보장할 수 없습니다. 이 문제는 실제 적용 사례에서 눈에 띄는 영향을 미칠 가능성이 낮습니다. 그러나 완벽한 역전을 보장하는 대안 구현을 전용 GitHub repo에서 제공합니다.
…
LEditsPPPipelineStableDiffusion
class diffusers.LEditsPPPipelineStableDiffusion
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulersafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )
매개변수
- vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (CLIPTextModel) — 동결된 텍스트 인코더입니다. Stable Diffusion은 CLIP의 텍스트 부분을 사용하며, 구체적으로는 clip-vit-large-patch14 변형을 사용합니다.
- tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
- unet (UNet2DConditionModel) — 인코딩된 이미지 latents의 노이즈를 제거하기 위한 조건부 U-Net 아키텍처.
- scheduler (DPMSolverMultistepScheduler 또는 DDIMScheduler) —
unet와 함께 사용하여 인코딩된 이미지 latens의 노이즈를 제거하는 데 사용되는 스케줄러입니다. DPMSolverMultistepScheduler 또는 DDIMScheduler 중 하나여야 합니다. 다른 스케줄러가 전달되면 자동으로 DPMSolverMultistepScheduler로 설정됩니다. - safety_checker (
StableDiffusionSafetyChecker) — 생성된 이미지가 offensive 또는 harmful로 간주될 수 있는지 추정하는 분류 모듈입니다. 자세한 내용은 model card를 참고하세요. - feature_extractor (CLIPImageProcessor) —
생성된 이미지에서
safety_checker의 입력으로 사용할 특징을 추출하는 모델입니다.
Stable Diffusion을 사용한 LEDits++ 텍스트 기반 이미지 편집을 위한 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속되며 StableDiffusionPipeline을 기반으로 합니다. 모든 파이프라인에 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( negative_prompt: str | list[str] | None = Nonegenerator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueediting_prompt: str | list[str] | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9user_mask: typing.Optional[torch.Tensor] = Nonesem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Trueattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0clip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple
매개변수
- negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,guidance_scale이1보다 작은 경우 무시됩니다). - generator (
torch.Generator, 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. PIL:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 단순 tuple 대신 LEditsPPDiffusionPipelineOutput를 반환할지 여부. - editing_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하는 프롬프트입니다.editing_prompt = None으로 설정하면 이미지가 재구성됩니다. 프롬프트의 가이드 방향은reverse_editing_direction을 통해 지정해야 합니다. - editing_prompt_embeds (
torch.Tensor>, 선택) — 이미지 생성을 안내하는 데 사용할 사전 계산된 임베딩입니다. 임베딩의 안내 방향은reverse_editing_direction을 통해 지정해야 합니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터negative_prompt_embeds가 생성됩니다. - reverse_editing_direction (
bool또는list[bool], 선택 사항, 기본값False) —editing_prompt의 해당 프롬프트를 증가시킬지 감소시킬지를 결정합니다. - edit_guidance_scale (
float또는list[float], 선택 사항, 기본값 5) — 이미지 생성을 유도하기 위한 guidance scale입니다. 리스트로 제공되는 경우 값은editing_prompt와 대응해야 합니다.edit_guidance_scale는 LEDITS++ Paper의 방정식 12의s_e로 정의됩니다. - edit_warmup_steps (
float또는list[float], 선택 사항, 기본값 10) — 가이던스가 적용되지 않는 확산 단계 수(프롬프트당). - edit_cooldown_steps (
float또는list[float], 선택 사항, 기본값None) — 가이던스가 더 이상 적용되지 않는 시점까지의 확산 단계 수(프롬프트별). - edit_threshold (
float또는list[float], 선택 사항, 기본값 0.9) — 가이던스의 마스킹 임계값입니다. 임계값은 수정되는 이미지 영역에 비례해야 합니다. ‘edit_threshold’는 LEDITS++ Paper의 방정식 12에서 ‘λ’로 정의됩니다. - user_mask (
torch.Tensor, 선택 사항) — 편집 과정에 대한 더 정밀한 제어를 위해 사용자가 직접 제공하는 마스크입니다. LEDITS++의 암시적 마스크가 사용자 선호도에 부합하지 않을 때 유용합니다. - sem_guidance (
list[torch.Tensor], 선택 사항) — 생성 시 적용할 사전 생성된 guidance 벡터의 목록입니다. 목록의 길이는num_inference_steps와 일치해야 합니다. - use_cross_attn_mask (
bool, 기본값False) — cross-attention 마스크를 사용할지 여부입니다. use_intersect_mask가 true로 설정된 경우 cross-attention 마스크는 항상 사용됩니다. cross-attention 마스크는 LEDITS++ paper의 방정식 12의 ‘M^1’로 정의됩니다. - use_intersect_mask (
bool, 기본값True) — 마스킹 항이 크로스 어텐션 마스크와 노이즈 추정에서 파생된 마스크의 교집합으로 계산되는지 여부입니다. 크로스 어텐션 마스크는 LEDITS++ 논문의 방정식 12에서 ‘M^1’로, 노이즈 추정에서 파생된 마스크는 ‘M^2’로 정의됩니다. - attn_store_steps (
list[int], 선택 사항) — AttentionStore에 어텐션 맵을 저장할 스텝입니다. 시각화 목적으로만 사용됩니다. - store_averaged_over_steps (
bool, 기본값True) — ‘attn_store_steps’의 attention maps가 diffusion steps에 걸쳐 평균된 값으로 저장될지 여부입니다. False인 경우 각 step의 attention maps가 별도로 저장됩니다. 시각화 목적입니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - guidance_rescale (
float, 선택 사항, 기본값 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed에서 제시한 guidance rescale 계수입니다. zero terminal SNR을 사용할 때 발생하는 과노출 문제를 수정하기 위해 guidance rescale 계수를 사용해야 합니다. - clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다. - callback_on_step_end (
Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargs에는callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다. - callback_on_step_end_tensor_inputs (
list, 선택 사항) —callback_on_step_end함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는callback_kwargs인수로 전달됩니다. 파이프라인 클래스의._callback_tensor_inputs속성에 나열된 변수만 포함할 수 있습니다.
반환값
LEditsPPDiffusionPipelineOutput 또는 tuple
LEditsPPDiffusionPipelineOutput 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) content, according to the safety_checker`.
편집을 위한 pipeline의 호출 함수. invert() 메서드를 먼저 호출해야 합니다. 편집은 항상 마지막으로 invert된 이미지(들)에 대해 수행됩니다.
예:
>>> import torch
>>> from diffusers import LEditsPPPipelineStableDiffusion
>>> from diffusers.utils import load_image
>>> pipe = LEditsPPPipelineStableDiffusion.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")
>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/cherry_blossom.png"
>>> image = load_image(img_url).resize((512, 512))
>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.1)
>>> edited_image = pipe(
... editing_prompt=["cherry blossom"], edit_guidance_scale=10.0, edit_threshold=0.75
... ).images[0]invert
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale: float = 3.5num_inversion_steps: int = 30skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput
매개변수
- image (
PipelineImageInput) — 편집할 이미지의 입력입니다. 여러 입력 이미지는 동일한 종횡비(aspect ratio)를 가져야 합니다. - source_prompt (
str, 기본값"") — 인버전 과정 중 가이던스에 사용될 입력 이미지를 설명하는 프롬프트입니다.source_prompt가""인 경우 가이던스는 비활성화됩니다. - source_guidance_scale (
float, 기본값3.5) — 인버전 과정에서의 가이던스 강도. - num_inversion_steps (
int, 기본값30) — 초기skip스텝을 제외하고 수행되는 총 inversion 스텝 수입니다. - skip (
float, 기본값0.15) — 인버전 및 후속 생성에서 무시되는 초기 스텝의 비율입니다. 값이 낮을수록 입력 이미지에 더 강한 변화가 적용됩니다.skip은0과1사이여야 합니다. - generator (
torch.Generator, 선택 사항) — 역변환을 결정적으로 만들기 위한torch.Generator. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다. - height (
int, 선택 사항, 기본값None) — 전처리된 이미지의 높이입니다.None인 경우get_default_height_width()를 사용하여 기본 높이를 가져옵니다. - width (
int, optional, defaults toNone) -- The width in preprocessed. IfNone, will use get_default_height_width()to get the default width. - resize_mode (
str, 선택 사항, 기본값default) — 리사이즈 모드로,default또는fill중 하나를 사용할 수 있습니다.default인 경우, 지정된 너비와 높이에 맞게 이미지를 리사이즈하며 원래의 종횡비를 유지하지 않을 수 있습니다.fill인 경우, 종횡비를 유지하면서 지정된 너비와 높이에 맞게 이미지를 리사이즈한 후, 차원 내에서 이미지를 중앙 정렬하고 빈 공간을 이미지 데이터로 채웁니다.crop인 경우, 종횡비를 유지하면서 지정된 너비와 높이에 맞게 이미지를 리사이즈한 후, 차원 내에서 이미지를 중앙 정렬하고 초과 부분을 잘라냅니다.fill및cropresize_mode는 PIL 이미지 입력에서만 지원된다는 점에 유의하세요. - crops_coords (
list[tuple[int, int, int, int]], 선택 사항, 기본값None) — 배치의 각 이미지에 대한 크롭 좌표입니다.None인 경우 이미지를 크롭하지 않습니다.
Output에는 리사이즈된 입력 이미지와 각각의 VAE 재구성이 포함됩니다.
LEDITS++ Paper에 설명된 이미지 반전(pipeline)에 사용되는 함수입니다. 스케줄러가 DDIMScheduler로 설정되어 있으면, edit-friendly DPDM에서 제안한 반전이 대신 수행됩니다.
encode_prompt
< source >( devicenum_images_per_promptenable_edit_guidancenegative_prompt = Noneediting_prompt = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
매개변수
- device — (
torch.device): torch device - num_images_per_prompt (
int) — 프롬프트당 생성할 이미지 수 - enable_edit_guidance (
bool) — 편집을 수행할지, 아니면 입력 이미지를 재구성할지 여부 - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉,guidance_scale이1보다 작으면 무시됩니다). - editing_prompt (
str또는list[str], 선택 사항) — 인코딩할 편집 프롬프트입니다. 정의되지 않은 경우 대신editing_prompt_embeds를 전달해야 합니다. - editing_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 이 인수가 제공되지 않으면prompt입력 인수를 기반으로 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - lora_scale (
float, 선택 사항) — LoRA 레이어가 로드된 경우 텍스트 인코더의 모든 LoRA 레이어에 적용될 LoRA 스케일입니다. - clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
LEditsPPPipelineStableDiffusionXL
class diffusers.LEditsPPPipelineStableDiffusionXL
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: UNet2DConditionModelscheduler: diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler | diffusers.schedulers.scheduling_ddim.DDIMSchedulerimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = Trueadd_watermarker: bool | None = None )
매개변수
- vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (CLIPTextModel) — 동결된 텍스트 인코더입니다. Stable Diffusion XL은 CLIP의 텍스트 부분을 사용하며, 구체적으로는 clip-vit-large-patch14 변형을 사용합니다.
- text_encoder_2 (CLIPTextModelWithProjection) — 두 번째 고정된 텍스트 인코더입니다. Stable Diffusion XL은 CLIP의 텍스트 및 풀링 부분을 사용하며, 구체적으로는 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 변형을 사용합니다.
- tokenizer (CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저.
- tokenizer_2 (CLIPTokenizer) — CLIPTokenizer 클래스의 두 번째 토크나이저.
- unet (UNet2DConditionModel) — 인코딩된 이미지 latents의 노이즈를 제거하기 위한 조건부 U-Net 아키텍처.
- scheduler (DPMSolverMultistepScheduler 또는 DDIMScheduler) —
unet와 함께 사용하여 인코딩된 이미지 latens의 노이즈를 제거하는 데 사용되는 스케줄러입니다. DPMSolverMultistepScheduler 또는 DDIMScheduler 중 하나여야 합니다. 다른 스케줄러가 전달되면 자동으로 DPMSolverMultistepScheduler로 설정됩니다. - force_zeros_for_empty_prompt (
bool, 선택 사항, 기본값"True") — 음성 프롬프트 임베딩을 항상 0으로 설정할지 여부입니다. 또한stabilityai/stable-diffusion-xl-base-1-0의 설정을 참고하세요. - add_watermarker (
bool, 선택) — invisible_watermark library를 사용하여 출력 이미지에 워터마크를 적용할지 여부입니다. 정의되지 않은 경우, 해당 패키지가 설치되어 있으면 기본값이 True가 되고, 그렇지 않으면 워터마커가 사용되지 않습니다.
Stable Diffusion XL을 사용한 LEDits++ 텍스트 기반 이미지 편집을 위한 Pipeline
이 모델은 DiffusionPipeline에서 상속되며 StableDiffusionXLPipeline을 기반으로 합니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
또한 pipeline은 다음 로딩 메서드를 상속합니다:
- LoRA: LEditsPPPipelineStableDiffusionXL.load_lora_weights()
- 체크포인트: loaders.FromSingleFileMixin.from_single_file()
다음과 같은 저장 방법도 있습니다:
- LoRA:
loaders.StableDiffusionXLPipeline.save_lora_weights
__call__
< source >( denoising_end: float | None = Nonenegative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0crops_coords_top_left: tuple = (0, 0)target_size: tuple[int, int] | None = Noneediting_prompt: str | list[str] | None = Noneediting_prompt_embeddings: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonereverse_editing_direction: bool | list[bool] | None = Falseedit_guidance_scale: float | list[float] | None = 5edit_warmup_steps: int | list[int] | None = 0edit_cooldown_steps: int | list[int] | None = Noneedit_threshold: float | list[float] | None = 0.9sem_guidance: list[torch.Tensor] | None = Noneuse_cross_attn_mask: bool = Falseuse_intersect_mask: bool = Falseuser_mask: typing.Optional[torch.Tensor] = Noneattn_store_steps: list[int] | None = []store_averaged_over_steps: bool = Trueclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']**kwargs ) → LEditsPPDiffusionPipelineOutput or tuple
매개변수
- denoising_end (
float, 선택 사항) — 지정된 경우, 전체 디노이징 과정 중 의도적으로 조기 종료되기 전에 완료될 비율(0.0에서 1.0 사이)을 결정합니다. 그 결과, 스케줄러가 선택한 이산 시간 단계에 따라 반환되는 샘플에는 상당한 양의 노이즈가 여전히 남아 있게 됩니다. denoising_end 매개변수는 이 파이프라인이 [**이미지 정제 - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉,guidance_scale이1보다 작으면 무시됩니다). - negative_prompt_2 (
str또는list[str], 선택) —tokenizer_2및text_encoder_2에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우,negative_prompt가 두 텍스트 인코더 모두에 사용됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - negative_pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 pooled negative_prompt_embeds가 생성됩니다. - ip_adapter_image — (
PipelineImageInput, 선택): IP Adapters와 함께 사용할 선택적 이미지 입력입니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. PIL:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput를 반환할지 여부. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - guidance_rescale (
float, optional, defaults to 0.7) — Guidance rescale factor proposed by Common Diffusion Noise Schedules and Sample Steps are Flawedguidance_scaleis defined asφin equation 16. of Common Diffusion Noise Schedules and Sample Steps are Flawed. Guidance rescale factor should fix overexposure when using zero terminal SNR. - crops_coords_top_left (
tuple[int], 선택 사항, 기본값 (0, 0)) —crops_coords_top_left는crops_coords_top_left위치에서 아래쪽으로 “잘라낸” 것처럼 보이는 이미지를 생성하는 데 사용할 수 있습니다.crops_coords_top_left를 (0, 0)으로 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. https://huggingface.co/papers/2307.01952의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. - target_size (
tuple[int], 선택 사항, 기본값 (1024, 1024)) — 대부분의 경우target_size는 생성된 이미지의 원하는 높이와 너비로 설정해야 합니다. 지정하지 않으면 기본값으로(width, height)가 사용됩니다. https://huggingface.co/papers/2307.01952의 2.2절에서 설명된 SDXL의 마이크로 컨디션닝(micro-conditioning)의 일부입니다. - editing_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하는 프롬프트입니다.editing_prompt = None으로 설정하면 이미지가 재구성됩니다. 프롬프트의 가이드 방향은reverse_editing_direction을 통해 지정해야 합니다. - editing_prompt_embeddings (
torch.Tensor, 선택 사항) — 미리 생성된 편집 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면editing_prompt입력 인수로부터 editing_prompt_embeddings가 생성됩니다. - editing_pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 풀링된 편집 텍스트 임베딩입니다. 예를 들어 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면editing_prompt입력 인수에서 editing_prompt_embeddings가 생성됩니다. - reverse_editing_direction (
bool또는list[bool], 선택 사항, 기본값False) —editing_prompt의 해당 프롬프트를 증가시킬지 감소시킬지를 결정합니다. - edit_guidance_scale (
float또는list[float], 선택 사항, 기본값 5) — 이미지 생성을 유도하기 위한 guidance scale입니다. 리스트로 제공되는 경우 값은editing_prompt와 대응해야 합니다.edit_guidance_scale는 LEDITS++ Paper의 방정식 12의s_e로 정의됩니다. - edit_warmup_steps (
float또는list[float], 선택 사항, 기본값 10) — 가이던스가 적용되지 않는 확산 단계 수(프롬프트당). - edit_cooldown_steps (
float또는list[float], 선택 사항, 기본값None) — 가이던스가 더 이상 적용되지 않는 시점까지의 확산 단계 수(프롬프트별). - edit_threshold (
float또는list[float], 선택 사항, 기본값 0.9) — 가이던스의 마스킹 임계값입니다. 임계값은 수정되는 이미지 영역에 비례해야 합니다. ‘edit_threshold’는 LEDITS++ Paper의 방정식 12에서 ‘λ’로 정의됩니다. - sem_guidance (
list[torch.Tensor], 선택 사항) — 생성 시 적용할 사전 생성된 guidance 벡터의 목록입니다. 목록의 길이는num_inference_steps와 일치해야 합니다. - use_cross_attn_mask — 크로스 어텐션 마스크를 사용할지 여부입니다. use_intersect_mask가 true로 설정된 경우 크로스 어텐션 마스크는 항상 사용됩니다. 크로스 어텐션 마스크는 LEDITS++ 논문의 방정식 12의 ‘M^1’로 정의됩니다.
- use_intersect_mask — 마스킹 항이 크로스 어텐션 마스크와 노이즈 추정에서 유도된 마스크의 교집합으로 계산되는지 여부입니다. 크로스 어텐션 마스크는 LEDITS++ 논문의 식 12에서 ‘M^1’로, 노이즈 추정에서 유도된 마스크는 ‘M^2’로 정의됩니다.
- user_mask — 편집 과정에 대한 더 나은 제어를 위해 사용자가 제공하는 마스크입니다. LEDITS++의 암시적 마스크가 사용자 선호도를 충족하지 못할 때 유용합니다.
- attn_store_steps — AttentionStore에 attention map을 저장할 스텝 수입니다. 시각화 목적으로만 사용됩니다.
- store_averaged_over_steps — ‘attn_store_steps’의 어텐션 맵이 디퓨전 스텝에 걸쳐 평균된 상태로 저장될지 여부입니다. False인 경우 각 스텝의 어텐션 맵이 개별적으로 저장됩니다. 시각화 목적으로만 사용됩니다.
- clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다. - callback_on_step_end (
Callable, 선택 사항) — 추론 중 각 디노이징 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict).callback_kwargs에는callback_on_step_end_tensor_inputs로 지정된 모든 텐서 목록이 포함됩니다. - callback_on_step_end_tensor_inputs (
list, 선택 사항) —callback_on_step_end함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는callback_kwargs인수로 전달됩니다. 파이프라인 클래스의._callback_tensor_inputs속성에 나열된 변수만 포함할 수 있습니다.
반환값
LEditsPPDiffusionPipelineOutput 또는 tuple
return_dict가 True인 경우 LEditsPPDiffusionPipelineOutput, 그렇지 않으면 `tuple`입니다. tuple을 반환할 때 첫 번째 요소는 생성된 이미지의 목록입니다.
편집을 위한 pipeline의 호출 함수. invert() 메서드를 먼저 호출해야 합니다. 편집은 항상 마지막으로 invert된 이미지(들)에 대해 수행됩니다.
예:
>>> import torch
>>> from diffusers import LEditsPPPipelineStableDiffusionXL
>>> from diffusers.utils import load_image
>>> pipe = LEditsPPPipelineStableDiffusionXL.from_pretrained(
... "stabilityai/stable-diffusion-xl-base-1.0", variant="fp16", torch_dtype=torch.float16
... )
>>> pipe.vae.enable_tiling()
>>> pipe = pipe.to("cuda")
>>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
>>> image = load_image(img_url).resize((1024, 1024))
>>> _ = pipe.invert(image=image, num_inversion_steps=50, skip=0.2)
>>> edited_image = pipe(
... editing_prompt=["tennis ball", "tomato"],
... reverse_editing_direction=[True, False],
... edit_guidance_scale=[5.0, 10.0],
... edit_threshold=[0.9, 0.85],
... ).images[0]invert
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]source_prompt: str = ''source_guidance_scale = 3.5negative_prompt: str = Nonenegative_prompt_2: str = Nonenum_inversion_steps: int = 50skip: float = 0.15generator: typing.Optional[torch.Generator] = Nonecrops_coords_top_left: tuple = (0, 0)num_zero_noise_steps: int = 3cross_attention_kwargs: dict[str, typing.Any] | None = Noneheight: int | None = Nonewidth: int | None = Noneresize_mode: str | None = 'default'crops_coords: tuple[int, int, int, int] | None = None ) → LEditsPPInversionPipelineOutput
매개변수
- image (
PipelineImageInput) — 편집할 이미지의 입력입니다. 여러 입력 이미지는 동일한 종횡비(aspect ratio)를 가져야 합니다. - source_prompt (
str, 기본값"") — 인버전 과정 중 가이던스에 사용될 입력 이미지를 설명하는 프롬프트입니다.source_prompt가""인 경우 가이던스는 비활성화됩니다. - source_guidance_scale (
float, 기본값3.5) — 인버전 과정에서의 가이던스 강도. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉,guidance_scale이1보다 작으면 무시됩니다). - negative_prompt_2 (
str또는list[str], 선택) —tokenizer_2및text_encoder_2에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우,negative_prompt가 두 텍스트 인코더 모두에 사용됩니다. - num_inversion_steps (
int, 기본값50) — 초기skip스텝을 제외하고 수행되는 총 역전 스텝 수입니다. - skip (
float, 기본값0.15) — 인버전 및 후속 생성에서 무시되는 초기 스텝의 비율입니다. 값이 낮을수록 입력 이미지에 더 강한 변화가 적용됩니다.skip은0과1사이여야 합니다. - generator (
torch.Generator, 선택 사항) — 역변환을 결정적으로 만들기 위한torch.Generator. - crops_coords_top_left (
tuple[int], 선택 사항, 기본값 (0, 0)) —crops_coords_top_left는crops_coords_top_left위치에서 아래쪽으로 “잘라낸” 것처럼 보이는 이미지를 생성하는 데 사용할 수 있습니다.crops_coords_top_left를 (0, 0)으로 설정하면 일반적으로 잘 중앙 정렬된 이미지를 얻을 수 있습니다. https://huggingface.co/papers/2307.01952의 2.2절에서 설명된 SDXL의 micro-conditioning의 일부입니다. - num_zero_noise_steps (
int, 기본값3) — 현재 이미지에 노이즈를 다시 적용하지 않는 마지막 diffusion 단계의 수입니다. 단계가 0으로 설정되지 않으면 DPMSolverMultistepScheduler와 함께 사용된 SD-XL은 노이즈 아티팩트를 생성할 수 있습니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다.
Output에는 리사이즈된 입력 이미지와 각각의 VAE 재구성이 포함됩니다.
LEDITS++ Paper에 설명된 이미지 반전(pipeline)에 사용되는 함수입니다. 스케줄러가 DDIMScheduler로 설정되어 있으면, edit-friendly DPDM에서 제안한 반전이 대신 수행됩니다.
encode_prompt
< source >( device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1negative_prompt: str | None = Nonenegative_prompt_2: str | None = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = Noneenable_edit_guidance: bool = Trueediting_prompt: str | None = Noneediting_prompt_embeds: typing.Optional[torch.Tensor] = Noneediting_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )
매개변수
- device — (
torch.device): torch device - num_images_per_prompt (
int) — 프롬프트당 생성할 이미지 수 - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우, 대신negative_prompt_embeds를 전달해야 합니다. - negative_prompt_2 (
str또는list[str], 선택) —tokenizer_2및text_encoder_2에 전송할 이미지 생성을 유도하지 않을 프롬프트입니다. 정의되지 않은 경우,negative_prompt가 두 텍스트 인코더 모두에 사용됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - negative_pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 pooled negative_prompt_embeds가 생성됩니다. - lora_scale (
float, 선택 사항) — LoRA 레이어가 로드된 경우 텍스트 인코더의 모든 LoRA 레이어에 적용될 LoRA 스케일입니다. - clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다. - enable_edit_guidance (
bool) — 편집 프롬프트를 기준으로 유도할지 여부. - editing_prompt (
str또는list[str], 선택 사항) — 인코딩할 편집 프롬프트입니다. 정의되지 않았고 ‘enable_edit_guidance’가 True인 경우, 대신editing_prompt_embeds를 전달해야 합니다. - editing_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 편집 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 값이 제공되지 않고 ‘enable_edit_guidance’가 True인 경우,editing_prompt입력 인수를 기반으로 editing_prompt_embeds가 생성됩니다. - editing_pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 edit pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면editing_prompt입력 인자로부터 pooled editing_pooled_prompt_embeds가 생성됩니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
get_guidance_scale_embedding
< source >( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor
LEditsPPDiffusionPipelineOutput
class diffusers.pipelines.LEditsPPDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
LEdits++ Diffusion 파이프라인의 출력 클래스입니다.
LEditsPPInversionPipelineOutput
클래스 diffusers.pipelines.LEditsPPInversionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarrayvae_reconstruction_images: list[PIL.Image.Image] | numpy.ndarray )
매개변수
- input_images (
list[PIL.Image.Image]또는np.ndarray) — 길이가batch_size인 PIL 이미지 목록 또는(batch_size, height, width, num_channels)모양의 NumPy 배열로, 잘라서 크기를 조정된 입력 이미지 목록입니다. - vae_reconstruction_images (
list[PIL.Image.Image]또는np.ndarray) —batch_size길이의 PIL 이미지 목록 또는(batch_size, height, width, num_channels)형태의 NumPy 배열로, 모든 입력 이미지의 VAE 재구성을 나타냅니다.
LEdits++ Diffusion 파이프라인의 출력 클래스입니다.