Diffusers documentation
슈퍼 레졸루션
슈퍼 레졸루션
Stable Diffusion 업스케일러 diffusion 모델은 CompVis, Stability AI, LAION의 연구자와 엔지니어에 의해 개발되었습니다. 입력 이미지의 해상도를 4배로 향상시키는 데 사용됩니다.
스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion Tips 섹션을 꼭 확인하세요!
특정 작업에 공식 체크포인트 중 하나를 사용하려는 경우, CompVis 및 Stability AI Hub 조직을 탐색해 보세요!
StableDiffusionUpscalePipeline
class diffusers.StableDiffusionUpscalePipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModellow_res_scheduler: DDPMSchedulerscheduler: KarrasDiffusionSchedulerssafety_checker: typing.Any | None = Nonefeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Nonewatermarker: typing.Any | None = Nonemax_noise_level: int = 350 )
매개변수
- vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (CLIPTextModel) — 동결된 텍스트 인코더(clip-vit-large-patch14).
- tokenizer (CLIPTokenizer) —
텍스트를 토큰화하기 위한
CLIPTokenizer입니다. - unet (UNet2DConditionModel) —
인코딩된 이미지 latents의 노이즈를 제거하기 위한
UNet2DConditionModel. - low_res_scheduler (SchedulerMixin) — 저해상도 조건 이미지에 초기 노이즈를 추가하는 데 사용되는 스케줄러입니다. DDPMScheduler의 인스턴스여야 합니다.
- scheduler (SchedulerMixin) —
인코딩된 이미지 잠재를 디노이즈하기 위해
unet와 함께 사용할 스케줄러입니다. DDIMScheduler, LMSDiscreteScheduler, 또는 PNDMScheduler 중 하나일 수 있습니다.
Stable Diffusion 2를 활용한 텍스트 기반 이미지 초해상도 처리를 위한 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
파이프라인은 다음 로딩 메서드도 상속합니다:
- 텍스트 인버전 임베딩을 로드하는 load_textual_inversion()
- LoRA 가중치를 로드하는 load_lora_weights()
- LoRA 가중치를 저장하는 save_lora_weights()
.ckpt파일을 로드하기 위한 from_single_file()
__call__
< source >( prompt: str | list[str] = Noneimage: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = Nonenum_inference_steps: int = 75guidance_scale: float = 9.0noise_level: int = 20negative_prompt: str | list[str] | None = Nonenum_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = 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 = Noneclip_skip: int = None ) → StableDiffusionPipelineOutput or tuple
매개변수
- prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 전달해야 합니다. - image (
torch.Tensor,PIL.Image.Image,np.ndarray,list[torch.Tensor],list[PIL.Image.Image]또는list[np.ndarray]) — 업스케일링할 이미지 배치의Image또는 텐서를 나타냅니다. - num_inference_steps (
int, 선택 사항, 기본값 50) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - guidance_scale (
float, 선택 사항, 기본값 7.5) — guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트prompt와 밀접하게 연결된 이미지를 생성하도록 유도됩니다.guidance_scale > 1일 때 guidance scale이 활성화됩니다. - noise_level (
int, 선택 사항, 기본값 20) — 업스케일된 입력 이미지에 추가할 노이즈의 양입니다.max_noise_level은 스케줄러에 의해 정의되며,[0, max_noise_level]범위에 있어야 합니다.noise_level이 높을수록 입력에 더 많은 노이즈가 추가되어 다양성은 증가하지만 원본 이미지에 대한 충실도는 감소합니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성에 포함하지 않을 내용을 안내하는 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때(guidance_scale < 1)에는 무시됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - eta (
float, 선택 사항, 기본값 0.0) — DDIM 논문에서 정의된 파라미터 eta (η)에 해당합니다. DDIMScheduler에만 적용되며, 다른 스케줄러에서는 무시됩니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한torch.Generator. - latents (
torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서를 생성합니다. - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면prompt입력 인자에서 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터negative_prompt_embeds가 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 생성된 이미지의 출력 형식입니다.PIL.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 StableDiffusionPipelineOutput를 반환할지 여부. - callback (
Callable, 선택 사항) — 추론 중callback_steps스텝마다 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, 선택 사항, 기본값 1) —callback함수가 호출되는 주기입니다. 지정하지 않으면 모든 단계에서 callback이 호출됩니다. - cross_attention_kwargs (
dict, 선택 사항) — 지정된 경우self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - clip_skip (
int, 선택 사항) — 프롬프트 임베딩을 계산할 때 CLIP에서 건너뛸 레이어의 수입니다. 값이 1이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.
반환값
StableDiffusionPipelineOutput 또는 tuple
If return_dict is True, StableDiffusionPipelineOutput is returned,
otherwise a tuple is returned where the first element is a list with the generated images and the
second element is a list of bools indicating whether the corresponding generated image contains
“not-safe-for-work” (nsfw) content.
생성을 위한 pipeline의 호출 함수.
예:
>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> from diffusers import StableDiffusionUpscalePipeline
>>> import torch
>>> # load model and scheduler
>>> model_id = "stabilityai/stable-diffusion-x4-upscaler"
>>> pipeline = StableDiffusionUpscalePipeline.from_pretrained(
... model_id, variant="fp16", torch_dtype=torch.float16
... )
>>> pipeline = pipeline.to("cuda")
>>> # let's download an image
>>> url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale/low_res_cat.png"
>>> response = requests.get(url)
>>> low_res_img = Image.open(BytesIO(response.content)).convert("RGB")
>>> low_res_img = low_res_img.resize((128, 128))
>>> prompt = "a white cat"
>>> upscaled_image = pipeline(prompt=prompt, image=low_res_img).images[0]
>>> upscaled_image.save("upsampled_cat.png")enable_attention_slicing
< source >( slice_size: str | int = 'auto' )
슬라이스된 어텐션 계산을 활성화합니다. 이 옵션이 활성화되면 어텐션 모듈은 입력 텐서를 슬라이스로 나누어 여러 단계에 걸쳐 어텐션을 계산합니다. 어텐션 헤드가 하나 이상인 경우, 각 헤드를 순차적으로 계산합니다. 이는 속도가 약간 감소하는 대신 메모리를 절약하는 데 유용합니다.
> ⚠️ PyTorch > 2.0 또는 xFormers의
scaled_dot_product_attention(SDPA)를 이미 사용 중이라면 attention slicing을 활성화하지 마세요. 이러한 attention 계산은 이미 메모리 효율성이 매우 높아 이 기능을 활성화할 필요가 없습니다. SDPA 또는 xFormers와 함께 attention slicing을 활성화하면 심각한 성능 저하가 발생할 수 있습니다!
예:
>>> import torch
>>> from diffusers import StableDiffusionPipeline
>>> pipe = StableDiffusionPipeline.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5",
... dtype=torch.float16,
... use_safetensors=True,
... )
>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]슬라이스된 어텐션 계산 기능을 비활성화합니다. enable_attention_slicing가 이전에 호출된 경우, 어텐션은 한 번에 계산됩니다.
enable_xformers_memory_efficient_attention
< source >( attention_op: typing.Optional[typing.Callable] = None )
매개변수
- attention_op (
Callable, 선택 사항) — xFormers의memory_efficient_attention()함수의op인수로 사용될None기본 연산자를 재정의합니다.
xFormers에서 메모리 효율적인 어텐션을 활성화합니다. 이 옵션을 활성화하면 추론 시 GPU 메모리 사용량이 감소하고 속도가 향상될 수 있습니다. 학습 시 속도 향상은 보장되지 않습니다.
> ⚠️ memory efficient attention과 sliced attention이 모두 활성화된 경우, memory efficient attention이 > 우선합니다.
예:
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)xFormers에서 메모리 효율적 어텐션을 비활성화합니다.
encode_prompt
< source >( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - device — (
torch.device): torch device - num_images_per_prompt (
int) — 프롬프트당 생성할 이미지 수 - do_classifier_free_guidance (
bool) — classifier free guidance를 사용할지 여부 - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때 무시됩니다(즉,guidance_scale이1보다 작으면 무시됩니다). - 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이면 최종 레이어 바로 이전 레이어의 출력을 프롬프트 임베딩 계산에 사용합니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
StableDiffusionPipelineOutput
클래스 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 파이프라인의 출력 클래스입니다.