Diffusers documentation
Latent 업스케일러
Latent 업스케일러
Stable Diffusion latent upscaler 모델은 Katherine Crowson이 Stability AI와 협력하여 만들었습니다. 이 모델은 출력 이미지의 해상도를 2배로 향상시키는 데 사용되며(원래 구현의 데모는 이 notebook을 참고하세요).
스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion Tips 섹션을 꼭 확인하세요!
특정 작업에 공식 체크포인트 중 하나를 사용하려는 경우, CompVis 및 Stability AI Hub 조직을 탐색해 보세요!
StableDiffusionLatentUpscalePipeline
클래스 diffusers.StableDiffusionLatentUpscalePipeline
< source >( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: UNet2DConditionModelscheduler: EulerDiscreteScheduler )
매개변수
- vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- text_encoder (CLIPTextModel) — 동결된 텍스트 인코더(clip-vit-large-patch14).
- tokenizer (CLIPTokenizer) —
텍스트를 토큰화하기 위한
CLIPTokenizer입니다. - unet (UNet2DConditionModel) —
인코딩된 이미지 latents의 노이즈를 제거하기 위한
UNet2DConditionModel. - scheduler (SchedulerMixin) —
인코딩된 이미지 latents의 노이즈를 제거하기 위해
unet와 함께 사용할 EulerDiscreteScheduler.
Stable Diffusion 출력 이미지의 해상도를 2배로 상향 조정하는 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
파이프라인은 다음 로딩 메서드도 상속합니다:
.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.0negative_prompt: str | list[str] | None = Nonegenerator: 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] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_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 = 1 ) → StableDiffusionPipelineOutput or tuple
매개변수
- prompt (
str또는list[str]) — 이미지 업스케일링을 안내할 프롬프트입니다. - image (
torch.Tensor,PIL.Image.Image,np.ndarray,list[torch.Tensor],list[PIL.Image.Image]또는list[np.ndarray]) — 업스케일링할 이미지 배치의Image또는 텐서를 나타냅니다. 텐서인 경우, Stable Diffusion 모델의 latent 출력 또는[-1, 1]범위의 이미지 텐서일 수 있습니다.image.shape[1]이4인 경우latent로 간주하고, 그렇지 않으면 이미지 표현으로 간주하여 이 파이프라인의vae인코더를 사용하여 인코딩합니다. - num_inference_steps (
int, 선택 사항, 기본값 50) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - guidance_scale (
float, 선택 사항, 기본값 7.5) — guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트prompt와 밀접하게 연결된 이미지를 생성하도록 유도됩니다.guidance_scale > 1일 때 guidance scale이 활성화됩니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성에 포함하지 않을 내용을 안내하는 프롬프트입니다. 정의되지 않은 경우negative_prompt_embeds를 대신 전달해야 합니다. 가이던스를 사용하지 않을 때(guidance_scale < 1)에는 무시됩니다. - 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가 생성됩니다. - pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다. - negative_pooled_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력(prompt weighting)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 poolednegative_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이 호출됩니다.
반환값
StableDiffusionPipelineOutput 또는 tuple
return_dict가 True인 경우 StableDiffusionPipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록인 tuple이 반환됩니다.
생성을 위한 pipeline의 호출 함수.
예:
>>> from diffusers import StableDiffusionLatentUpscalePipeline, StableDiffusionPipeline
>>> import torch
>>> pipeline = StableDiffusionPipeline.from_pretrained(
... "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16
... )
>>> pipeline.to("cuda")
>>> model_id = "stabilityai/sd-x2-latent-upscaler"
>>> upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(model_id, torch_dtype=torch.float16)
>>> upscaler.to("cuda")
>>> prompt = "a photo of an astronaut high resolution, unreal engine, ultra realistic"
>>> generator = torch.manual_seed(33)
>>> low_res_latents = pipeline(prompt, generator=generator, output_type="latent").images
>>> with torch.no_grad():
... image = pipeline.decode_latents(low_res_latents)
>>> image = pipeline.numpy_to_pil(image)[0]
>>> image.save("../images/a1.png")
>>> upscaled_image = upscaler(
... prompt=prompt,
... image=low_res_latents,
... num_inference_steps=20,
... guidance_scale=0,
... generator=generator,
... ).images[0]
>>> upscaled_image.save("../images/a2.png")enable_sequential_cpu_offload
< source >( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )
🤗 Accelerate를 사용하여 모든 모델을 CPU로 오프로드하여 메모리 사용량을 크게 줄입니다. 호출 시 self._exclude_from_cpu_offload에 포함된 것을 제외한 모든 torch.nn.Module 구성 요소의 상태 딕트가 CPU에 저장된 후 torch.device('meta')로 이동되며, 해당 서브모듈의 forward 메서드가 호출될 때에만 가속기로 로드됩니다. 오프로딩은 서브모듈 단위로 수행됩니다. enable_model_cpu_offload를 사용할 때보다 메모리 절감 효과가 크지만 성능은 낮습니다.
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 >( promptdevicedo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None )
매개변수
- prompt (
str또는list(int)) — 인코딩할 프롬프트 - device — (
torch.device): torch device - do_classifier_free_guidance (
bool) — classifier free guidance를 사용할지 여부 - negative_prompt (
str또는list[str]) — 이미지 생성을 안내하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,guidance_scale이1보다 작은 경우 무시됩니다). - prompt_embeds (
torch.FloatTensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.FloatTensor, optional) — 미리 생성된 부정 텍스트 임베딩입니다. 프롬프트 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. e.g. 제공되지 않으면negative_prompt입력 인수에서 negative_prompt_embeds가 생성됩니다. - pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다. - negative_pooled_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 pooled negative_prompt_embeds가 생성됩니다.
프롬프트를 텍스트 인코더의 히든 상태로 인코딩합니다.
StableDiffusionPipelineOutput
클래스 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 파이프라인의 출력 클래스입니다.