Diffusers documentation
Stable Cascade
Stable Cascade
이 모델은 Würstchen 아키텍처를 기반으로 구축되었으며, Stable Diffusion과 같은 다른 모델과의 주요 차이점은 훨씬 더 작은 잠재 공간(latent space)에서 작동한다는 것입니다. 이것이 왜 중요한가요? 잠재 공간이 작을수록 추론을 더 빠르게 실행할 수 있고, 학습 비용이 더 저렴해집니다. 잠재 공간은 얼마나 작은가요? Stable Diffusion은 압축 계수 8을 사용하여 1024x1024 이미지를 128x128로 인코딩합니다. Stable Cascade는 압축 계수 42를 달성하여, 선명한 재구성을 유지하면서 1024x1024 이미지를 24x24로 인코딩할 수 있습니다. 텍스트 조건부 모델은 이 고도로 압축된 잠재 공간에서 학습됩니다. 이 아키텍처의 이전 버전은 Stable Diffusion 1.5 대비 16배의 비용 절감을 달성했습니다.
따라서 이러한 유형의 모델은 효율성이 중요한 사용 사례에 적합합니다. 또한, finetuning, LoRA, ControlNet, IP-Adapter, LCM 등 알려진 모든 확장도 이 방법으로 가능합니다.
원본 코드베이스는 Stability-AI/StableCascade에서 찾을 수 있습니다.
모델 개요
Stable Cascade는 이미지 생성을 위한 캐스케이드를 나타내는 Stage A, Stage B, Stage C의 세 가지 모델로 구성되어 있으며, 이러한 구조에서 “Stable Cascade”라는 이름이 유래했습니다.
Stage A & B는 Stable Diffusion에서 VAE가 수행하는 역할과 유사하게 이미지를 압축하는 데 사용됩니다. 그러나 이 구성을 사용하면 이미지의 압축률이 훨씬 더 높아집니다. Stable Diffusion 모델은 공간 압축 계수 8을 사용하여 1024 x 1024 해상도의 이미지를 128 x 128로 인코딩하는 반면, Stable Cascade는 압축 계수 42를 달성합니다. 이는 1024 x 1024 이미지를 24 x 24로 인코딩하면서도 이미지를 정확하게 디코딩할 수 있게 합니다. 이로 인해 학습과 추론 비용이 저렴해지는 큰 이점이 있습니다. 또한, Stage C는 텍스트 프롬프트가 주어졌을 때 작은 24 x 24 latents를 생성하는 역할을 담당합니다.
Stage C 모델은 작은 24 x 24 latents에서 작동하며 텍스트 프롬프트에 조건부으로 latents의 노이즈를 제거합니다. 이 모델은 Cascade 파이프라인에서 가장 큰 구성 요소이기도 하며 StableCascadePriorPipeline과 함께 사용하도록 설계되었습니다.
Stage B 모델과 Stage A 모델은 StableCascadeDecoderPipeline과 함께 사용되며, 작은 24 x 24 latents를 기반으로 최종 이미지를 생성하는 역할을 합니다.
Stable Cascade 모델에서 사용할 수 있는 데이터 유형에는 몇 가지 제한 사항이 있습니다.
StableCascadePriorPipeline의 공식 체크포인트는torch.float16데이터 유형을 지원하지 않습니다. 대신torch.bfloat16를 사용하세요.
StableCascadeDecoderPipeline에서torch.bfloat16데이터 타입을 사용하려면 PyTorch 2.2.0 이상을 설치해야 합니다. 이는 내부적으로StableCascadeDecoderPipeline를 호출하기 때문에StableCascadeCombinedPipeline에torch.bfloat16를 사용하는 경우에도 PyTorch 2.2.0 이상이 필요함을 의미합니다.환경에서 PyTorch 2.2.0 이상을 설치할 수 없는 경우,
StableCascadeDecoderPipeline을torch.float16데이터 타입과 함께 단독으로 사용할 수 있습니다. 파이프라인의 전체 정밀도 또는bf16변형 가중치를 다운로드한 후 가중치를torch.float16으로 캐스팅할 수 있습니다.
사용 예시
import torch
from diffusers import StableCascadeDecoderPipeline, StableCascadePriorPipeline
prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""
prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", variant="bf16", dtype=torch.bfloat16)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", variant="bf16", dtype=torch.float16)
prior.enable_model_cpu_offload()
prior_output = prior(
prompt=prompt,
height=1024,
width=1024,
negative_prompt=negative_prompt,
guidance_scale=4.0,
num_images_per_prompt=1,
num_inference_steps=20
)
decoder.enable_model_cpu_offload()
decoder_output = decoder(
image_embeddings=prior_output.image_embeddings.to(torch.float16),
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=0.0,
output_type="pil",
num_inference_steps=10
).images[0]
decoder_output.save("cascade.png")Stage B 및 Stage C 모델의 Lite 버전 사용
import torch
from diffusers import (
StableCascadeDecoderPipeline,
StableCascadePriorPipeline,
StableCascadeUNet,
)
prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""
prior_unet = StableCascadeUNet.from_pretrained("stabilityai/stable-cascade-prior", subfolder="prior_lite")
decoder_unet = StableCascadeUNet.from_pretrained("stabilityai/stable-cascade", subfolder="decoder_lite")
prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", prior=prior_unet)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", decoder=decoder_unet)
prior.enable_model_cpu_offload()
prior_output = prior(
prompt=prompt,
height=1024,
width=1024,
negative_prompt=negative_prompt,
guidance_scale=4.0,
num_images_per_prompt=1,
num_inference_steps=20
)
decoder.enable_model_cpu_offload()
decoder_output = decoder(
image_embeddings=prior_output.image_embeddings,
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=0.0,
output_type="pil",
num_inference_steps=10
).images[0]
decoder_output.save("cascade.png")from_single_file로 원래 체크포인트 로드
from_single_file 메서드를 통해 StableCascadeUNet에서 원래 형식의 체크포인트 로딩을 지원합니다.
import torch
from diffusers import (
StableCascadeDecoderPipeline,
StableCascadePriorPipeline,
StableCascadeUNet,
)
prompt = "an image of a shiba inu, donning a spacesuit and helmet"
negative_prompt = ""
prior_unet = StableCascadeUNet.from_single_file(
"https://huggingface.co/stabilityai/stable-cascade/resolve/main/stage_c_bf16.safetensors",
dtype=torch.bfloat16
)
decoder_unet = StableCascadeUNet.from_single_file(
"https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_bf16.safetensors",
dtype=torch.bfloat16
)
prior = StableCascadePriorPipeline.from_pretrained("stabilityai/stable-cascade-prior", prior=prior_unet, dtype=torch.bfloat16)
decoder = StableCascadeDecoderPipeline.from_pretrained("stabilityai/stable-cascade", decoder=decoder_unet, dtype=torch.bfloat16)
prior.enable_model_cpu_offload()
prior_output = prior(
prompt=prompt,
height=1024,
width=1024,
negative_prompt=negative_prompt,
guidance_scale=4.0,
num_images_per_prompt=1,
num_inference_steps=20
)
decoder.enable_model_cpu_offload()
decoder_output = decoder(
image_embeddings=prior_output.image_embeddings,
prompt=prompt,
negative_prompt=negative_prompt,
guidance_scale=0.0,
output_type="pil",
num_inference_steps=10
).images[0]
decoder_output.save("cascade-single-file.png")사용
직접 사용
현재 이 모델은 연구 목적으로 사용됩니다. 가능한 연구 분야 및 작업에는
- 생성 모델에 대한 연구.
- 유해한 콘텐츠를 생성할 가능성이 있는 모델의 안전한 배포.
- 생성형 모델의 한계와 편향을 탐지하고 이해합니다.
- 예술 작품 생성 및 디자인과 기타 예술적 프로세스에서의 활용.
- 교육 또는 창의적 도구에서의 응용.
제외되는 사용 사례는 아래에 설명되어 있습니다.
범위 외 사용
이 모델은 인물이나 사건에 대한 사실적이거나 정확한 표현을 생성하도록 학습되지 않았으며, 따라서 이 모델의 기능 범위 밖에서 이러한 콘텐츠를 생성하는 데 사용하는 것은 적절하지 않습니다. 이 모델은 Stability AI의 허용 사용 정책을 위반하는 방식으로 사용해서는 안 됩니다.
한계 및 편향
한계
- 얼굴과 사람 전반이 제대로 생성되지 않을 수 있습니다.
- 모델의 오토인코딩 부분은 손실이 있습니다.
StableCascadeCombinedPipeline
클래스 diffusers.StableCascadeCombinedPipeline
< source >( tokenizer: CLIPTokenizertext_encoder: CLIPTextModelWithProjectiondecoder: StableCascadeUNetscheduler: DDPMWuerstchenSchedulervqgan: PaellaVQModelprior_prior: StableCascadeUNetprior_text_encoder: CLIPTextModelWithProjectionprior_tokenizer: CLIPTokenizerprior_scheduler: DDPMWuerstchenSchedulerprior_feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Noneprior_image_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None )
매개변수
- tokenizer (
CLIPTokenizer) — 텍스트 입력에 사용할 디코더 토크나이저입니다. - text_encoder (
CLIPTextModelWithProjection) — 텍스트 입력에 사용할 디코더 텍스트 인코더입니다. - decoder (
StableCascadeUNet) — 디코더 이미지 생성 파이프라인에 사용할 디코더 모델. - scheduler (
DDPMWuerstchenScheduler) — 디코더 이미지 생성 파이프라인에 사용할 스케줄러입니다. - vqgan (
PaellaVQModel) — 디코더 이미지 생성 파이프라인에 사용할 VQGAN 모델. - prior_prior (
StableCascadeUNet) — prior 파이프라인에 사용할 prior 모델입니다. - prior_text_encoder (
CLIPTextModelWithProjection) — 텍스트 입력에 사용할 prior text encoder입니다. - prior_tokenizer (
CLIPTokenizer) — 텍스트 입력에 사용할 사전 토크나이저입니다. - prior_scheduler (
DDPMWuerstchenScheduler) — prior 파이프라인에 사용할 스케줄러입니다. - prior_feature_extractor (CLIPImageProcessor) —
생성된 이미지에서
image_encoder의 입력으로 사용할 특징을 추출하는 모델입니다. - prior_image_encoder (
CLIPVisionModelWithProjection) — 동결된 CLIP 이미지 인코더(clip-vit-large-patch14).
Stable Cascade를 사용한 텍스트-이미지 생성을 위한 통합 Pipeline
이 모델은 DiffusionPipeline에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( prompt: str | list[str] | None = Noneimages: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]] = Noneheight: int = 512width: int = 512prior_num_inference_steps: int = 60prior_guidance_scale: float = 4.0num_inference_steps: int = 12decoder_guidance_scale: float = 0.0negative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_pooled: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueprior_callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Noneprior_callback_on_step_end_tensor_inputs: list = ['latents']callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents'] )
매개변수
- prompt (
str또는list[str]) — prior 및 decoder의 이미지 생성을 안내하는 프롬프트입니다. - images (
torch.Tensor,PIL.Image.Image,list[torch.Tensor],list[PIL.Image.Image], 선택 사항) — prior의 이미지 생성을 안내할 이미지입니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,guidance_scale이1보다 작은 경우 무시됩니다). - prompt_embeds (
torch.Tensor, 선택 사항) — 이전 단계에 사용할 사전 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - prompt_embeds_pooled (
torch.Tensor, 선택 사항) — prior에 사용할 사전 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택) — Prior에 사용할 사전 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 prompt 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인수를 기반으로 negative_prompt_embeds가 생성됩니다. - negative_prompt_embeds_pooled (
torch.Tensor, 선택) — Prior에 사용할 사전 생성된 negative text embeddings입니다. 예를 들어 prompt 가중치와 같은 텍스트 입력을 쉽게 조정하는 데 사용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - height (
int, 선택 사항, 기본값 512) — 생성된 이미지의 픽셀 단위 높이입니다. - width (
int, 선택 사항, 기본값 512) — 생성된 이미지의 픽셀 단위 너비입니다. - prior_guidance_scale (
float, 선택 사항, 기본값 4.0) — Classifier-Free Diffusion Guidance에서 정의된 guidance scale입니다.prior_guidance_scale은 Imagen Paper의 2번 식의w로 정의됩니다.prior_guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. - prior_num_inference_steps (
int | dict[float, int], 선택 사항, 기본값 60) — 사전 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 얻을 수 있지만, 추론 속도가 느려집니다. 더 구체적인 타임스텝 간격을 지정하려면 사용자 정의한prior_timesteps를 전달할 수 있습니다. - num_inference_steps (
int, 선택 사항, 기본값 12) — 디코더의 디노이징 단계 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만 추론 속도는 느려집니다. 더 구체적인 타임스텝 간격을 지정하려면 사용자 정의timesteps를 전달할 수 있습니다. - decoder_guidance_scale (
float, 선택 사항, 기본값 0.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.guidance_scale은 Imagen Paper의 방정식 2에서w로 정의됩니다.guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. 다음 중 하나를 선택하세요:"pil"(PIL.Image.Image),"np"(np.array) 또는"pt"(torch.Tensor). - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 ImagePipelineOutput을 반환할지 여부. - prior_callback_on_step_end (
Callable, 선택 사항) — 추론 중 각 denoising 단계의 끝에서 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다:prior_callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). - prior_callback_on_step_end_tensor_inputs (
list, 선택 사항) —prior_callback_on_step_end함수의 텐서 입력 목록입니다. 목록에 지정된 텐서는callback_kwargs인수로 전달됩니다. 파이프라인 클래스의._callback_tensor_inputs속성에 나열된 변수만 포함할 수 있습니다. - 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속성에 나열된 변수만 포함할 수 있습니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import StableCascadeCombinedPipeline
>>> pipe = StableCascadeCombinedPipeline.from_pretrained(
... "stabilityai/stable-cascade", variant="bf16", torch_dtype=torch.bfloat16
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> images = pipe(prompt=prompt)enable_model_cpu_offload
< source >( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )
accelerate를 사용하여 모든 모델을 CPU로 오프로드하여 성능에 미치는 영향은 적으면서 메모리 사용량을 줄입니다. enable_sequential_cpu_offload와 비교하면, 이 메서드는 forward 메서드가 호출될 때 한 번에 하나의 모델을 GPU로 이동하며, 다음 모델이 실행될 때까지 해당 모델은 GPU에 유지됩니다. enable_sequential_cpu_offload를 사용하는 경우보다 메모리 절감 효과는 낮지만, unet의 반복적 실행 덕분에 성능이 훨씬 좋습니다.
enable_sequential_cpu_offload
< source >( gpu_id: int | None = Nonedevice: typing.Union[torch.device, str] = None )
🤗 Accelerate를 사용하여 모든 모델(unet, text_encoder, vae, safety checker 상태 사전)을 CPU로 오프로드하여 메모리 사용량을 크게 줄입니다. 모델은 torch.device('meta')로 이동되며, 해당 서브모듈의 forward 메서드가 호출될 때만 GPU에 로드됩니다. 오프로딩은 서브모듈 단위로 수행됩니다. enable_model_cpu_offload를 사용하는 것보다 메모리 절감 효과가 크지만 성능은 낮습니다.
StableCascadePriorPipeline
클래스 diffusers.StableCascadePriorPipeline
< source >( tokenizer: CLIPTokenizertext_encoder: CLIPTextModelWithProjectionprior: StableCascadeUNetscheduler: DDPMWuerstchenSchedulerresolution_multiple: float = 42.67feature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Noneimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None )
매개변수
- prior (
StableCascadeUNet) — 텍스트 및/또는 이미지 임베딩에서 이미지 임베딩을 근사하기 위한 Stable Cascade prior입니다. - text_encoder (
CLIPTextModelWithProjection) — 동결된 텍스트 인코더 (laion/CLIP-ViT-bigG-14-laion2B-39B-b160k). - feature_extractor (CLIPImageProcessor) —
생성된 이미지에서
image_encoder의 입력으로 사용할 특징을 추출하는 모델입니다. - image_encoder (
CLIPVisionModelWithProjection) — 동결된 CLIP 이미지 인코더(clip-vit-large-patch14). - tokenizer (
CLIPTokenizer) — CLIPTokenizer 클래스의 토크나이저. - scheduler (
DDPMWuerstchenScheduler) —prior와 함께 사용하여 이미지 임베딩을 생성하는 데 사용되는 스케줄러. - resolution_multiple (‘float’, 선택 사항, 기본값 42.67) — 생성된 여러 이미지의 기본 해상도입니다.
Stable Cascade의 이미지 prior를 생성하는 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( prompt: str | list[str] | None = Noneimages: typing.Union[torch.Tensor, list[torch.Tensor], PIL.Image.Image, list[PIL.Image.Image]] = Noneheight: int = 1024width: int = 1024num_inference_steps: int = 20timesteps: list = Noneguidance_scale: float = 4.0negative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_pooled: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = Noneimage_embeds: typing.Optional[torch.Tensor] = Nonenum_images_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pt'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents'] )
매개변수
- prompt (
str또는list[str]) — 이미지 생성을 안내하는 프롬프트 또는 프롬프트 목록입니다. - images (
torch.Tensor,PIL.Image.Image,list[torch.Tensor]또는list[PIL.Image.Image], 선택 사항) — 선행 생성을 조건부로 설정하는 데 사용되는 참조 이미지입니다. 제공되면 이미지에서 임베딩을 추출하여 텍스트 프롬프트와 결합합니다. - height (
int, 선택 사항, 기본값 1024) — 생성된 이미지의 픽셀 단위 높이입니다. - width (
int, 선택 사항, 기본값 1024) — 생성된 이미지의 픽셀 단위 너비입니다. - num_inference_steps (
int, 선택 사항, 기본값 60) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - timesteps (
list[float], 선택 사항) —timesteps인수를 지원하는 스케줄러의set_timesteps메서드에서 디노이징 과정에 사용할 커스텀 timesteps입니다. 정의되지 않은 경우,num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - guidance_scale (
float, 선택 사항, 기본값 8.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.decoder_guidance_scale는 Imagen Paper의 방정식 2의w로 정의됩니다.decoder_guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,decoder_guidance_scale이1보다 작은 경우 무시됩니다). - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - prompt_embeds_pooled (
torch.Tensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - negative_prompt_embeds_pooled (
torch.Tensor, 선택 사항) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds_pooled가 생성됩니다. - image_embeds (
torch.Tensor, 선택) — 미리 생성된 이미지 임베딩입니다. 이미지 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면,image입력 인수가 존재하는 경우 이를 기반으로 이미지 임베딩이 생성됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. 다음 중 하나를 선택하세요:"pil"(PIL.Image.Image),"np"(np.array) 또는"pt"(torch.Tensor). - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 ImagePipelineOutput을 반환할지 여부. - 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속성에 나열된 변수만 포함할 수 있습니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import StableCascadePriorPipeline
>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
... "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
... ).to("cuda")
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> prior_output = pipe(prompt)StableCascadePriorPipelineOutput
class diffusers.pipelines.stable_cascade.pipeline_stable_cascade_prior.StableCascadePriorPipelineOutput
< source >( image_embeddings: typing.Union[torch.Tensor, numpy.ndarray]prompt_embeds: typing.Union[torch.Tensor, numpy.ndarray]prompt_embeds_pooled: typing.Union[torch.Tensor, numpy.ndarray]negative_prompt_embeds: typing.Union[torch.Tensor, numpy.ndarray]negative_prompt_embeds_pooled: typing.Union[torch.Tensor, numpy.ndarray] )
WuerstchenPriorPipeline의 출력 클래스입니다.
StableCascadeDecoderPipeline
클래스 diffusers.StableCascadeDecoderPipeline
< source >( decoder: StableCascadeUNettokenizer: CLIPTokenizertext_encoder: CLIPTextModelWithProjectionscheduler: DDPMWuerstchenSchedulervqgan: PaellaVQModellatent_dim_scale: float = 10.67 )
매개변수
- tokenizer (
CLIPTokenizer) — CLIP 토크나이저입니다. - text_encoder (
CLIPTextModelWithProjection) — CLIP 텍스트 인코더입니다. - decoder (
StableCascadeUNet) — Stable Cascade decoder unet입니다. - vqgan (
PaellaVQModel) — VQGAN 모델입니다. - scheduler (
DDPMWuerstchenScheduler) —prior와 함께 사용하여 이미지 임베딩을 생성하는 데 사용되는 스케줄러. - latent_dim_scale (float,
optional, 기본값 10.67) — 이미지 임베딩으로부터 VQ 잠재 공간 크기를 결정하는 배율입니다. 이미지 임베딩의 높이가 24이고 폭이 24인 경우, 학습 조건과 일치시키기 위해 VQ 잠재 형상은 높이가 int(2410.67)=256이고 폭이 int(2410.67)=256이어야 합니다.
Stable Cascade 모델에서 이미지를 생성하는 Pipeline입니다.
이 모델은 DiffusionPipeline에서 상속됩니다. 라이브러리가 모든 파이프라인에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( image_embeddings: typing.Union[torch.Tensor, list[torch.Tensor]]prompt: str | list[str] = Nonenum_inference_steps: int = 10guidance_scale: float = 0.0negative_prompt: str | list[str] | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_pooled: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_pooled: typing.Optional[torch.Tensor] = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents'] )
매개변수
- image_embeddings (
torch.Tensor또는list[torch.Tensor]) — 이미지에서 추출하거나 Prior Model이 생성한 이미지 임베딩입니다. - prompt (
str또는list[str]) — 이미지 생성을 안내하는 프롬프트 또는 프롬프트 목록입니다. - num_inference_steps (
int, 선택 사항, 기본값 12) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - guidance_scale (
float, 선택 사항, 기본값 0.0) — Classifier-Free Diffusion Guidance에서 정의한 guidance scale입니다.decoder_guidance_scale는 Imagen Paper의 방정식 2의w로 정의됩니다.decoder_guidance_scale > 1로 설정하면 guidance scale이 활성화됩니다. guidance scale이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 유도하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다. 가이던스를 사용하지 않는 경우 무시됩니다(즉,decoder_guidance_scale이1보다 작은 경우 무시됩니다). - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - prompt_embeds_pooled (
torch.Tensor, 선택) — 미리 생성된 풀링된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 풀링된 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 negative text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds가 생성됩니다. - negative_prompt_embeds_pooled (
torch.Tensor, 선택 사항) — 미리 생성된 negative pooled text embeddings입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면negative_prompt입력 인자로부터 negative_prompt_embeds_pooled가 생성됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. 다음 중 하나를 선택하세요:"pil"(PIL.Image.Image),"np"(np.array) 또는"pt"(torch.Tensor). - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 ImagePipelineOutput을 반환할지 여부. - 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속성에 나열된 변수만 포함할 수 있습니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import StableCascadePriorPipeline, StableCascadeDecoderPipeline
>>> prior_pipe = StableCascadePriorPipeline.from_pretrained(
... "stabilityai/stable-cascade-prior", torch_dtype=torch.bfloat16
... ).to("cuda")
>>> gen_pipe = StableCascadeDecoderPipeline.from_pretrain(
... "stabilityai/stable-cascade", torch_dtype=torch.float16
... ).to("cuda")
>>> prompt = "an image of a shiba inu, donning a spacesuit and helmet"
>>> prior_output = pipe(prompt)
>>> images = gen_pipe(prior_output.image_embeddings, prompt=prompt)