Diffusers documentation
이미지 변형
이미지 변형
Stable Diffusion 모델은 입력 이미지로부터 변형된 이미지를 생성할 수도 있습니다. Lambda의 Justin Pinkney가 만든 Stable Diffusion 모델의 fine-tuned 버전을 사용합니다.
원본 코드베이스는 LambdaLabsML/lambda-diffusers에서 찾을 수 있으며, 이미지 변형에 대한 추가 공식 체크포인트는 lambdalabs/sd-image-variations-diffusers에서 찾을 수 있습니다.
스케줄러의 속도와 품질 사이의 트레이드오프를 탐색하는 방법과 파이프라인 구성 요소를 효율적으로 재사용하는 방법을 배우려면 Stable Diffusion Tips 섹션을 꼭 확인하세요!
StableDiffusionImageVariationPipeline
클래스 diffusers.StableDiffusionImageVariationPipeline
< source >( vae: AutoencoderKLimage_encoder: CLIPVisionModelWithProjectionunet: UNet2DConditionModelscheduler: KarrasDiffusionSchedulerssafety_checker: StableDiffusionSafetyCheckerfeature_extractor: CLIPImageProcessorPilrequires_safety_checker: bool = True )
매개변수
- vae (AutoencoderKL) — 이미지를 잠재 표현으로 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델.
- image_encoder (CLIPVisionModelWithProjection) — 동결된 CLIP 이미지 인코더 (clip-vit-large-patch14).
- text_encoder (CLIPTextModel) — 동결된 텍스트 인코더(clip-vit-large-patch14).
- tokenizer (CLIPTokenizer) —
텍스트를 토큰화하기 위한
CLIPTokenizer입니다. - unet (UNet2DConditionModel) —
인코딩된 이미지 latents의 노이즈를 제거하기 위한
UNet2DConditionModel. - scheduler (SchedulerMixin) —
인코딩된 이미지 잠재를 디노이즈하기 위해
unet와 함께 사용할 스케줄러입니다. DDIMScheduler, LMSDiscreteScheduler, 또는 PNDMScheduler 중 하나일 수 있습니다. - safety_checker (
StableDiffusionSafetyChecker) — 생성된 이미지가 offensive 또는 harmful로 간주될 수 있는지 추정하는 분류 모듈입니다. 모델의 잠재적 해악에 대한 자세한 내용은 model card를 참고하세요. - feature_extractor (CLIPImageProcessor) —
생성된 이미지에서 특징을 추출하는
CLIPImageProcessor입니다.safety_checker의 입력으로 사용됩니다.
Stable Diffusion를 사용하여 입력 이미지에서 이미지 변형을 생성하는 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( image: typing.Union[PIL.Image.Image, list[PIL.Image.Image], torch.Tensor]height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5num_images_per_prompt: int | None = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: 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
매개변수
- image (
PIL.Image.Image또는list[PIL.Image.Image]또는torch.Tensor) — 이미지 생성을 안내할 이미지 또는 이미지들입니다. 텐서를 제공하는 경우CLIPImageProcessor와 호환되어야 합니다. - height (
int, 선택 사항, 기본값self.unet.config.sample_size * self.vae_scale_factor) — 생성된 이미지의 픽셀 단위 높이입니다. - width (
int, 선택 사항, 기본값self.unet.config.sample_size * self.vae_scale_factor) — 생성된 이미지의 픽셀 단위 너비입니다. - num_inference_steps (
int, 선택 사항, 기본값 50) — 디노이징 단계 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만 추론 속도는 느려집니다. 이 매개변수는strength에 의해 조절됩니다. - guidance_scale (
float, 선택 사항, 기본값 7.5) — guidance scale 값이 높을수록 모델은 이미지 품질이 낮아지는 대신 텍스트prompt와 밀접하게 연결된 이미지를 생성하도록 유도됩니다.guidance_scale > 1일 때 guidance scale이 활성화됩니다. - 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 텐서를 생성합니다. - 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
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의 호출 함수.
예:
from diffusers import StableDiffusionImageVariationPipeline
from PIL import Image
from io import BytesIO
import requests
pipe = StableDiffusionImageVariationPipeline.from_pretrained(
"lambdalabs/sd-image-variations-diffusers", revision="v2.0"
)
pipe = pipe.to("cuda")
url = "https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200"
response = requests.get(url)
image = Image.open(BytesIO(response.content)).convert("RGB")
out = pipe(image, num_images_per_prompt=3, guidance_scale=15)
out["images"][0].save("result.jpg")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에서 메모리 효율적 어텐션을 비활성화합니다.
StableDiffusionPipelineOutput
클래스 diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarraynsfw_content_detected: list[bool] | None )
Stable Diffusion 파이프라인의 출력 클래스입니다.