Buckets:

mishig's picture
|
download
raw
19.7 kB

Latent 업스케일러

Stable Diffusion latent upscaler 모델은 Katherine Crowson이 Stability AI와 협력하여 만들었습니다. 이 모델은 출력 이미지의 해상도를 2배로 향상시키는 데 사용되며(원래 구현의 데모는 이 notebook을 참고하세요).

스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion Tips 섹션을 꼭 확인하세요!

특정 작업에 공식 체크포인트 중 하나를 사용하려는 경우, CompVis 및 Stability AI Hub 조직을 탐색해 보세요!

StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

diffusers.StableDiffusionLatentUpscalePipeline[[diffusers.StableDiffusionLatentUpscalePipeline]]

diffusers.StableDiffusionLatentUpscalePipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: EulerDiscreteScheduler)

소스

매개변수:

vae (AutoencoderKL) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다.

text_encoder (CLIPTextModel) : 고정된 텍스트 인코더 (clip-vit-large-patch14).

tokenizer (CLIPTokenizer) : 텍스트를 토큰화하기 위한 CLIPTokenizer입니다.

unet (UNet2DConditionModel) : 인코딩된 이미지 latents의 노이즈를 제거하기 위한 UNet2DConditionModel.

scheduler (SchedulerMixin) : unet와 함께 사용되어 인코딩된 이미지 latents의 노이즈를 제거하는 EulerDiscreteScheduler.

Stable Diffusion 출력 이미지의 해상도를 2배로 상향 조정하는 Pipeline입니다.

이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.

파이프라인은 다음 로딩 메서드도 상속합니다:

호출[[diffusers.StableDiffusionLatentUpscalePipeline.call]]

__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, num_inference_steps: int = 75, guidance_scale: float = 9.0, negative_prompt: str | list[str] | None = None, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None, callback_steps: int = 1)

소스

매개변수:

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입니다. 텍스트 입력(프롬프트 가중치)을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면 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 함수가 호출되는 주기입니다. 지정하지 않으면 모든 단계에서 콜백이 호출됩니다.

반환값: 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[[diffusers.StableDiffusionLatentUpscalePipeline.enable_sequential_cpu_offload]]

enable_sequential_cpu_offload(gpu_id: int | None = None, device: typing.Union[torch.device, str] = None)

소스

매개변수:

gpu_id (int, 선택 사항) : 추론에 사용할 accelerator의 ID입니다. 지정하지 않으면 기본값으로 0이 사용됩니다.

device (torch.Device 또는 str, 선택 사항, 기본값 None) : 추론에 사용할 가속기의 PyTorch 장치 유형입니다. 지정하지 않으면 사용 가능한 가속기를 자동으로 감지하여 사용합니다.

🤗 Accelerate를 사용하여 모든 모델을 CPU로 오프로드하여 메모리 사용량을 크게 줄입니다. 호출 시 self._exclude_from_cpu_offload에 포함된 것을 제외한 모든 torch.nn.Module 구성 요소의 상태 딕트가 CPU에 저장된 후 torch.device('meta')로 이동되며, 해당 서브모듈의 forward 메서드가 호출될 때에만 가속기로 로드됩니다. 오프로딩은 서브모듈 단위로 수행됩니다. enable_model_cpu_offload를 사용할 때보다 메모리 절감 효과가 크지만 성능은 낮습니다.

enable_attention_slicing[[diffusers.StableDiffusionLatentUpscalePipeline.enable_attention_slicing]]

enable_attention_slicing(slice_size: str | int = 'auto')

소스

매개변수:

slice_size (str 또는 int, 선택 사항, 기본값 "auto") : "auto"인 경우 attention heads에 전달되는 입력을 절반으로 줄여 attention을 두 단계로 계산합니다. "max"인 경우 한 번에 하나의 슬라이스만 실행하여 최대의 메모리를 절약합니다. 숫자가 제공되면 attention_head_dim // slice_size만큼의 슬라이스를 사용합니다. 이 경우 attention_head_dim은 slice_size의 배수여야 합니다.

슬라이스된 어텐션 계산을 활성화합니다. 이 옵션이 활성화되면 어텐션 모듈은 입력 텐서를 슬라이스로 분할하여 여러 단계에 걸쳐 어텐션을 계산합니다. 어텐션 헤드 하나가 넘는 경우, 각 헤드를 순차적으로 계산합니다. 이는 속도가 약간 감소하는 대신 메모리를 절약하는 데 유용합니다.

> ⚠️ 이미 scaled_dot_product_attention(SDPA)를 사용 중이라면 attention slicing을 활성화하지 마세요 from PyTorch > 2.0 or xFormers. 이러한 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]

disable_attention_slicing[[diffusers.StableDiffusionLatentUpscalePipeline.disable_attention_slicing]]

disable_attention_slicing()

소스

슬라이스된 어텐션 계산 기능을 비활성화합니다. enable_attention_slicing가 이전에 호출된 경우, 어텐션은 한 번에 계산됩니다.

enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionLatentUpscalePipeline.enable_xformers_memory_efficient_attention]]

enable_xformers_memory_efficient_attention(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)

disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionLatentUpscalePipeline.disable_xformers_memory_efficient_attention]]

disable_xformers_memory_efficient_attention()

소스

xFormers에서 메모리 효율적 어텐션을 비활성화합니다.

encode_prompt[[diffusers.StableDiffusionLatentUpscalePipeline.encode_prompt]]

encode_prompt(prompt, device, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, pooled_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None)

소스

매개변수:

prompt (str 또는 list(int)) : 인코딩할 프롬프트

device : (torch.device): torch 디바이스

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, 선택) : 미리 생성된 부정 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면 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]]

diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)

소스

매개변수:

images (list[PIL.Image.Image] 또는 np.ndarray) : batch_size 길이의 노이즈 제거된 PIL 이미지 목록 또는 (batch_size, height, width, num_channels) 모양의 NumPy 배열.

nsfw_content_detected (list[bool]) : 해당 생성된 이미지에 "not-safe-for-work"(nsfw) 콘텐츠가 포함되어 있는지 여부를 나타내는 리스트. 안전 검사를 수행할 수 없는 경우 None.

Stable Diffusion 파이프라인의 출력 클래스입니다.

Xet Storage Details

Size:
19.7 kB
·
Xet hash:
0bbd3e4626a09d0b325d5b880c1780c50eacc6dd42e67a1dea92e52b691a3580

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.