Diffusers documentation
DDIMScheduler
DDIMScheduler
Jiaming Song, Chenlin Meng, Stefano Ermon의 Denoising Diffusion Implicit Models(DDIM).
해당 논문의 초록은 다음과 같습니다:
디노이징 확산 확률 모델(DDPM)은 적대적 학습 없이 고품질 이미지 생성을 달성했지만, 샘플을 생성하려면 마르코프 체인을 여러 단계에 걸쳐 시뮬레이션해야 합니다. 샘플링을 가속화하기 위해, 우리는 DDPM과 동일한 학습 절차를 가진 더 효율적인 반복적 암시적 확률 모델 클래스인 디노이징 확산 암시적 모델(DDIM)을 제시합니다. DDPM에서 생성 과정은 마르코프 확산 과정의 역과정으로 정의됩니다. 우리는 동일한 학습 목적 함수를 유도하지만, 그 역과정에서 샘플링을 훨씬 빠르게 수행할 수 있는 비마르코프 확산 과정 클래스를 구성합니다. 우리는 DDIM이 DDPM에 비해 벽시계 시간 기준 10배에서 50배까지 빠르게 고품질 샘플을 생성할 수 있음을 경험적으로 입증했으며, 계산량과 샘플 품질을 트레이드오프할 수 있고, 잠재 공간에서 의미론적으로 의미 있는 이미지 보간을 직접 수행할 수 있음을 보여줍니다.
이 논문의 원래 코드베이스는 ermongroup/ddim에서 찾을 수 있으며, tsong.me를 통해 저자에게 연락할 수 있습니다.
팁
The paper Common Diffusion Noise Schedules and Sample Steps are Flawed claims that a mismatch between the training and inference settings leads to suboptimal inference generation results for Stable Diffusion. To fix this, the authors propose:
🧪 이는 실험적 기능입니다!
- rescale the noise schedule to enforce zero terminal signal-to-noise ratio (SNR)
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config, rescale_betas_zero_snr=True)- train a model with
v_prediction(add the following argument to the train_text_to_image.py or train_text_to_image_lora.py scripts)
--prediction_type="v_prediction"- 샘플러를 항상 마지막 타임스텝에서 시작하도록 변경
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")- 과노출을 방지하기 위해 classifier-free guidance를 rescale
image = pipe(prompt, guidance_rescale=0.7).images[0]예를 들어:
from diffusers import DiffusionPipeline, DDIMScheduler
import torch
pipe = DiffusionPipeline.from_pretrained("ptx0/pseudo-journey-v2", dtype=torch.float16)
pipe.scheduler = DDIMScheduler.from_config(
pipe.scheduler.config, rescale_betas_zero_snr=True, timestep_spacing="trailing"
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
prompt = "A lion in galaxies, spirals, nebulae, stars, smoke, iridescent, intricate detail, octane render, 8k"
image = pipe(prompt, guidance_rescale=0.7).images[0]
imageDDIMScheduler
클래스 diffusers.DDIMScheduler
< source >( num_train_timesteps: int = 1000beta_start: float = 0.0001beta_end: float = 0.02beta_schedule: str = 'linear'trained_betas: numpy.ndarray | list[float] | None = Noneclip_sample: bool = Trueset_alpha_to_one: bool = Truesteps_offset: int = 0prediction_type: typing.Literal['epsilon', 'sample', 'v_prediction'] = 'epsilon'thresholding: bool = Falsedynamic_thresholding_ratio: float = 0.995clip_sample_range: float = 1.0sample_max_value: float = 1.0timestep_spacing: typing.Literal['leading', 'trailing', 'linspace'] = 'leading'rescale_betas_zero_snr: bool = False )
매개변수
- num_train_timesteps (
int, 기본값 1000) — 모델을 학습할 때 사용할 diffusion 단계 수입니다. - beta_start (
float, 기본값 0.0001) — 추론의 시작beta값입니다. - beta_end (
float, 기본값 0.02) — 최종beta값입니다. - beta_schedule (
Literal["linear", "scaled_linear", "squaredcos_cap_v2"], 기본값"linear") — 모델의 스테핑을 위한 베타 범위에서 베타 시퀀스로의 매핑인 베타 스케줄입니다."linear","scaled_linear","squaredcos_cap_v2"중 하나여야 합니다. - trained_betas (
np.ndarray, 선택 사항) —beta_start와beta_end를 우회하여 베타 배열을 생성자에 직접 전달합니다. - clip_sample (
bool, 기본값True) — 수치적 안정성을 위해 예측된 샘플을 클리핑합니다. - clip_sample_range (
float, 기본값 1.0) — 샘플 클리핑의 최대 크기입니다.clip_sample=True일 때만 유효합니다. - set_alpha_to_one (
bool, 기본값True) — 각 diffusion 단계는 해당 단계와 이전 단계의 alphas 곱 값을 사용합니다. 마지막 단계에는 이전 alpha가 없습니다. 이 옵션이True이면 이전 alpha 곱 값은1로 고정되고, 그렇지 않으면 0단계의 alpha 값을 사용합니다. - steps_offset (
int, 기본값 0) — 일부 모델 계열에서 요구하는 추론 단계에 추가되는 오프셋입니다. - prediction_type (
Literal["epsilon", "sample", "v_prediction"], 기본값"epsilon") — 스케줄러 함수의 예측 유형입니다."epsilon"(확산 과정의 노이즈를 예측),"sample"(노이즈가 포함된 샘플을 직접 예측), 또는"v_prediction"(Imagen Video 논문 2.4절 참조) 중 하나여야 합니다. - thresholding (
bool, 기본값False) — “동적 임계값 설정” 방법을 사용할지 여부입니다. Stable Diffusion과 같은 잠재 공간 확산 모델에는 적합하지 않습니다. - dynamic_thresholding_ratio (
float, 기본값 0.995) — 동적 임계값 설정 방법의 비율입니다.thresholding=True일 때만 유효합니다. - sample_max_value (
float, 기본값 1.0) — 동적 임계값 설정을 위한 임계값입니다.thresholding=True일 때만 유효합니다. - timestep_spacing (
Literal["leading", "trailing", "linspace"], defaults to"leading") — The way the timesteps should be scaled. Must be one of"leading","trailing", or"linspace". Refer to Table 2 of the Common Diffusion Noise Schedules and Sample Steps are Flawed for more information. - rescale_betas_zero_snr (
bool, 기본값False) — 베타를 재조정하여 최종 SNR을 0으로 만들지 여부를 지정합니다. 이를 통해 중간 밝기의 샘플로 제한되는 대신 매우 밝고 어두운 샘플을 생성할 수 있습니다.--offset_noise와 느슨하게 관련이 있습니다.
DDIMScheduler는 DDPM(denoising diffusion probabilistic models)에서 도입된 디노이징(denoising) 절차를 비마르코프(non-Markovian) 가이던스로 확장합니다.
이 모델은 SchedulerMixin과 ConfigMixin을 상속합니다. 로딩 및 저장과 같은 모든 스케줄러에 대해 라이브러리가 구현하는 일반적 메서드에 대해서는 상위 클래스 문서를 확인하세요.
add_noise
< source >( original_samples: Tensornoise: Tensortimesteps: IntTensor ) → torch.Tensor
각 timestep의 노이즈 크기에 따라 원래 샘플에 노이즈를 추가합니다(이것은 forward diffusion process입니다).
get_velocity
< source >( sample: Tensornoise: Tensortimesteps: IntTensor ) → torch.Tensor
속도 공식에 따라 샘플과 노이즈로부터 속도 예측을 계산합니다.
scale_model_input
< source >( sample: Tensortimestep: int = None ) → torch.Tensor
현재 timestep에 따라 denoising 모델 입력을 scale해야 하는 scheduler와의 호환성을 보장합니다.
set_timesteps
< source >( num_inference_steps: intdevice: typing.Union[str, torch.device] = None )
추론 실행 전에 실행할 diffusion chain에 사용할 이산 timesteps를 설정합니다.
단계
< source >( model_output: Tensortimestep: intsample: Tensoreta: float = 0.0use_clipped_model_output: bool = Falsegenerator: typing.Optional[torch.Generator] = Nonevariance_noise: typing.Optional[torch.Tensor] = Nonereturn_dict: bool = True ) → DDIMSchedulerOutput or tuple
매개변수
- model_output (
torch.Tensor) — 학습된 diffusion 모델의 직접적인 출력입니다. - timestep (
int) — 확산 체인(diffusion chain)의 현재 이산 시간 단계(discrete timestep)입니다. - sample (
torch.Tensor) — 확산 과정에 의해 생성된 샘플의 현재 인스턴스입니다. - eta (
float, 선택 사항, 기본값 0.0) — 확산 단계에서 추가되는 노이즈의 가중치입니다. 값 0은 DDIM(결정론적)에 해당하고, 1은 DDPM(완전 확률론적)에 해당합니다. - use_clipped_model_output (
bool, 선택 사항, 기본값False) —True인 경우, 클리핑된 예측 원본 샘플로부터 “보정된”model_output를 계산합니다.self.config.clip_sample가True일 때 예측 원본 샘플이 [-1, 1]로 클리핑되므로 필요합니다. 클리핑이 발생하지 않은 경우, “보정된”model_output은 입력으로 제공된 것과 일치하며use_clipped_model_output는 효과가 없습니다. - generator (
torch.Generator, 선택 사항) — 재현 가능한 샘플링을 위한 난수 생성기. - variance_noise (
torch.Tensor, 선택 사항) —generator를 사용하여 노이즈를 생성하는 대신, variance 자체에 대한 노이즈를 직접 제공하는 대안입니다.CycleDiffusion와 같은 방법에 유용합니다. - return_dict (
bool, 선택 사항, 기본값True) — DDIMSchedulerOutput 또는tuple을 반환할지 여부.
반환값
DDIMSchedulerOutput 또는 tuple
return_dict가 True인 경우 DDIMSchedulerOutput이 반환되고, 그렇지 않으면 첫 번째 요소가 샘플 텐서인 튜플이 반환됩니다.
이전 시간 단계의 샘플을 SDE를 역방향으로 적용하여 예측합니다. 이 함수는 학습된 모델의 출력(대부분 예측된 노이즈)으로부터 확산 과정을 전파합니다.
DDIMSchedulerOutput
class diffusers.schedulers.scheduling_ddim.DDIMSchedulerOutput
< source >( prev_sample: Tensorpred_original_sample: typing.Optional[torch.Tensor] = None )
매개변수
- prev_sample (이미지의 경우
torch.Tensor, shape(batch_size, num_channels, height, width)) — 이전 timestep의 계산된 샘플(x_{t-1}).prev_sample은 denoising 루프에서 다음 모델 입력으로 사용해야 합니다. - pred_original_sample (
torch.Tensor, 이미지인 경우 shape(batch_size, num_channels, height, width)) — 현재 timestep의 모델 출력에 기반한 예측된 디노이즈 샘플(x_{0}).pred_original_sample은 진행 상황 미리보기 또는 가이던스에 사용할 수 있습니다.
스케줄러의 step 함수 출력을 위한 출력 클래스입니다.