Diffusers documentation
Consistency Models
Consistency Models
Consistency Models는 Yang Song, Prafulla Dhariwal, Mark Chen, Ilya Sutskever가 Consistency Models에서 제안했습니다.
해당 논문의 초록은 다음과 같습니다:
Diffusion models은 이미지, 오디오 및 비디오 생성 분야에서 상당한 발전을 이루었지만, 느린 생성을 초래하는 반복적 샘플링 프로세스에 의존합니다. 이러한 한계를 극복하기 위해, 노이즈를 데이터로 직접 매핑하여 고품질 샘플을 생성하는 새로운 모델 계열인 consistency models를 제안합니다. 이들은 설계상 빠른 1단계 생성을 지원하면서도, 계산 비용을 샘플 품질과 교환할 수 있도록 다단계 샘플링을 허용합니다. 또한, 이러한 작업에 대한 명시적인 학습 없이도 이미지 inpainting, 컬러라이제이션, 초해상도와 같은 zero-shot 데이터 편집을 지원합니다. Consistency models는 사전 학습된 diffusion models를 증류하여 학습하거나, 완전히 독립적인 생성 모델로 학습할 수 있습니다. 광범위한 실험을 통해, 1단계 및 소수 단계 샘플링에서 기존 diffusion models 증류 기법보다 우수한 성능을 보이며, 1단계 생성에서 CIFAR-10의 FID 3.55와 ImageNet 64x64의 FID 6.20이라는 새로운 state-of-the-art를 달성함을 입증했습니다. 독립적으로 학습된 경우, consistency models는 CIFAR-10, ImageNet 64x64 및 LSUN 256x256과 같은 표준 벤치마크에서 기존 1단계, 비적대적 생성 모델보다 우수한 성능을 발휘할 수 있는 새로운 생성 모델 계열이 됩니다.
원본 코드베이스는 openai/consistency_models에서 찾을 수 있으며, 추가 체크포인트는 openai에서 사용할 수 있습니다.
이 파이프라인은 dg845와 ayushtues가 기여했습니다. ❤️
팁
추가 속도 향상을 위해 torch.compile을 사용하여 1초 미만으로 여러 이미지를 생성합니다:
import torch
from diffusers import ConsistencyModelPipeline
device = "cuda" # or "mps", "xpu", "cpu"
# Load the cd_bedroom256_lpips checkpoint.
model_id_or_path = "openai/diffusers-cd_bedroom256_lpips"
pipe = ConsistencyModelPipeline.from_pretrained(model_id_or_path, dtype=torch.float16)
pipe.to(device)
+ pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
# Multistep sampling
# Timesteps can be explicitly specified; the particular timesteps below are from the original GitHub repo:
# https://github.com/openai/consistency_models/blob/main/scripts/launch.sh#L83
for _ in range(10):
image = pipe(timesteps=[17, 0]).images[0]
image.show()ConsistencyModelPipeline
클래스 diffusers.ConsistencyModelPipeline
< source >( unet: UNet2DModelscheduler: CMStochasticIterativeScheduler )
매개변수
- unet (UNet2DModel) —
인코딩된 이미지 latents의 노이즈를 제거하기 위한
UNet2DModel. - scheduler (SchedulerMixin) —
인코딩된 이미지 latents의 노이즈를 제거하기 위해
unet와 함께 사용되는 스케줄러입니다. 현재 CMStochasticIterativeScheduler와만 호환됩니다.
무조건적 또는 클래스 조건부 이미지 생성을 위한 파이프라인.
이 모델은 DiffusionPipeline에서 상속됩니다. 모든 파이프라인에 대해 구현된 일반적 메서드(다운로드, 저장, 특정 디바이스에서 실행 등)에 대해서는 상위 클래스 문서를 확인하세요.
__call__
< source >( batch_size: int = 1class_labels: typing.Union[torch.Tensor, list[int], int, NoneType] = Nonenum_inference_steps: int = 1timesteps: list = Nonegenerator: 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 ) → ImagePipelineOutput or tuple
매개변수
- batch_size (
int, 선택 사항, 기본값 1) — 생성할 이미지의 수입니다. - class_labels (
torch.Tensor또는list[int]또는int, 선택) — 클래스 조건부 일관성 모델의 조건부 생성을 위한 선택적 클래스 라벨입니다. 모델이 클래스 조건부가 아니면 사용되지 않습니다. - num_inference_steps (
int, 선택 사항, 기본값 1) — 디노이징 단계의 수입니다. 디노이징 단계를 늘리면 일반적으로 더 높은 품질의 이미지를 얻을 수 있지만, 추론 속도가 느려집니다. - timesteps (
list[int], 선택 사항) — 노이즈 제거 과정에 사용할 사용자 지정 timesteps입니다. 정의되지 않은 경우, 균등 간격의num_inference_stepstimesteps가 사용됩니다. 내림차순으로 정렬되어 있어야 합니다. - generator (
torch.Generator, 선택 사항) — 생성을 결정적으로 만들기 위한torch.Generator입니다. - latents (
torch.Tensor, 선택 사항) — 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents로, 이미지 생성의 입력으로 사용됩니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서를 생성합니다. - output_type (
str, 선택 사항, 기본값"pil") — 생성된 이미지의 출력 형식입니다.PIL.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 ImagePipelineOutput을 반환할지 여부. - callback (
Callable, 선택 사항) — 추론 중callback_steps스텝마다 호출되는 함수입니다. 이 함수는 다음 인수를 받아 호출됩니다:callback(step: int, timestep: int, latents: torch.Tensor). - callback_steps (
int, 선택 사항, 기본값 1) —callback함수가 호출되는 주기입니다. 지정하지 않으면 모든 단계에서 callback이 호출됩니다.
반환값
ImagePipelineOutput 또는 tuple
return_dict가 True인 경우 ImagePipelineOutput가 반환되고, 그렇지 않으면 첫 번째 요소가 생성된 이미지의 목록인 tuple이 반환됩니다.
예:
>>> import torch
>>> from diffusers import ConsistencyModelPipeline
>>> device = "cuda"
>>> # Load the cd_imagenet64_l2 checkpoint.
>>> model_id_or_path = "openai/diffusers-cd_imagenet64_l2"
>>> pipe = ConsistencyModelPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
>>> pipe.to(device)
>>> # Onestep Sampling
>>> image = pipe(num_inference_steps=1).images[0]
>>> image.save("cd_imagenet64_l2_onestep_sample.png")
>>> # Onestep sampling, class-conditional image generation
>>> # ImageNet-64 class label 145 corresponds to king penguins
>>> image = pipe(num_inference_steps=1, class_labels=145).images[0]
>>> image.save("cd_imagenet64_l2_onestep_sample_penguin.png")
>>> # Multistep sampling, class-conditional image generation
>>> # Timesteps can be explicitly specified; the particular timesteps below are from the original GitHub repo:
>>> # https://github.com/openai/consistency_models/blob/main/scripts/launch.sh#L77
>>> image = pipe(num_inference_steps=None, timesteps=[22, 0], class_labels=145).images[0]
>>> image.save("cd_imagenet64_l2_multistep_sample_penguin.png")ImagePipelineOutput
클래스 diffusers.ImagePipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
이미지 파이프라인의 출력 클래스입니다.