text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
prev_sample = prev_sample + variance
if not return_dict:
return (
prev_sample,
pred_original_sample,
)
return DDIMParallelSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
def batch_step_no_noise(
se... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
Args:
model_output (`torch.Tensor`): direct output from learned diffusion model.
timesteps (`List[int]`):
current discrete timesteps in the diffusion chain. This is now a list of integers.
sample (`torch.Tensor`):
current instance of sample being creat... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
"""
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
)
assert eta == 0.0
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
# 1. compute alphas, betas
self.alphas_cumprod = self.alphas_cumprod.to(model_output.device)
self.final_alpha_cumprod = self.final_alpha_cumprod.to(model_output.device)
alpha_prod_t = self.alphas_cumprod[t]
alpha_prod_t_prev = self.alphas_cumprod[torch.clip(prev_t, min=0)]
alpha_... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
if self.config.prediction_type == "epsilon":
pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
) | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
# 4. Clip or threshold "predicted x_0"
if self.config.thresholding:
pred_original_sample = self._threshold_sample(pred_original_sample)
elif self.config.clip_sample:
pred_original_sample = pred_original_sample.clamp(
-self.config.clip_sample_range, self.config.cli... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
prev_sample... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
def add_noise(
self,
original_samples: torch.Tensor,
noise: torch.Tensor,
timesteps: torch.IntTensor,
) -> torch.Tensor:
# Make sure alphas_cumprod and timestep have same device and dtype as origin... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
noisy_samp... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
while len(sqrt_alpha_prod.shape) < len(sample.shape):
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
sqrt_one_mi... | 1,347 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddim_parallel.py |
class DDPMWuerstchenSchedulerOutput(BaseOutput):
"""
Output class for the scheduler's step function output.
Args:
prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as... | 1,348 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
class DDPMWuerstchenScheduler(SchedulerMixin, ConfigMixin):
"""
Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and
Langevin dynamics sampling.
[`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__i... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
@register_to_config
def __init__(
self,
scaler: float = 1.0,
s: float = 0.008,
):
self.scaler = scaler
self.s = torch.tensor([s])
self._init_alpha_cumprod = torch.cos(self.s / (1 + self.s) * torch.pi * 0.5) ** 2
# standard deviation of the initial noise d... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
Args:
sample (`torch.Tensor`): input sample
timestep (`int`, optional): current timestep
Returns:
`torch.Tensor`: scaled input sample
"""
return sample
def set_timesteps(
self,
num_inference_steps: int = None,
timesteps: Optional[... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
Args:
num_inference_steps (`Dict[float, int]`):
the number of diffusion steps used when generating samples with a pre-trained model. If passed, then
`timesteps` must be `None`.
device (`str` or `torch.device`, optional):
the device to which the tim... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
def step(
self,
model_output: torch.Tensor,
timestep: int,
sample: torch.Tensor,
generator=None,
return_dict: bool = True,
) -> Union[DDPMWuerstchenSchedulerOutput, Tuple]:
"""
Predict the sample at the previous timestep by reversing the SDE. Core func... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
Returns:
[`DDPMWuerstchenSchedulerOutput`] or `tuple`: [`DDPMWuerstchenSchedulerOutput`] if `return_dict` is True,
otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
"""
dtype = model_output.dtype
device = model_output.device
t =... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
std_noise = randn_tensor(mu.shape, generator=generator, device=model_output.device, dtype=model_output.dtype)
std = ((1 - alpha) * (1.0 - alpha_cumprod_prev) / (1.0 - alpha_cumprod)).sqrt() * std_noise
pred = mu + std * (prev_t != 0).float().view(prev_t.size(0), *[1 for _ in sample.shape[1:]])
... | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
def __len__(self):
return self.config.num_train_timesteps
def previous_timestep(self, timestep):
index = (self.timesteps - timestep[0]).abs().argmin().item()
prev_t = self.timesteps[index + 1][None].expand(timestep.shape[0])
return prev_t | 1,349 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ddpm_wuerstchen.py |
class FlaxKarrasDiffusionSchedulers(Enum):
FlaxDDIMScheduler = 1
FlaxDDPMScheduler = 2
FlaxPNDMScheduler = 3
FlaxLMSDiscreteScheduler = 4
FlaxDPMSolverMultistepScheduler = 5
FlaxEulerDiscreteScheduler = 6 | 1,350 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
class FlaxSchedulerOutput(BaseOutput):
"""
Base class for the scheduler's step function output.
Args:
prev_sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)` for images):
Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model i... | 1,351 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
class FlaxSchedulerMixin(PushToHubMixin):
"""
Mixin containing common functions for the schedulers.
Class attributes:
- **_compatibles** (`List[str]`) -- A list of classes that are compatible with the parent class, so that
`from_config` can be used from a class different than the one used... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
- A string, the *model id* of a model repo on huggingface.co. Valid model ids should have an
organization name, like `google/ddpm-celebahq-256`.
- A path to a *directory* containing model weights saved using [`~SchedulerMixin.save_pretrained`],
e.g., `./my... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
cache_dir (`Union[str, os.PathLike]`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to f... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
output_loading_info(`bool`, *optional*, defaults to `False`):
... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git. | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
<Tip>
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
<Tip>
Activate the special ["offline-mode"](https://huggingface.co/transformers/installation.html... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
"""
Save a scheduler configuration object to the directory `save_directory`, so that it can be re-loaded using the
[`~FlaxSchedulerMixin.from_pretrained`] class method. | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
Args:
save_directory (`str` or `os.PathLike`):
Directory where the configuration JSON file will be saved (will be created if it does not exist).
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or not to push your model to the Hugging Face Hub after ... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
Returns:
`List[SchedulerMixin]`: List of compatible schedulers
"""
return self._get_compatibles()
@classmethod
def _get_compatibles(cls):
compatible_classes_str = list(set([cls.__name__] + cls._compatibles))
diffusers_library = importlib.import_module(__name__.split(... | 1,352 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
class CommonSchedulerState:
alphas: jnp.ndarray
betas: jnp.ndarray
alphas_cumprod: jnp.ndarray
@classmethod
def create(cls, scheduler):
config = scheduler.config | 1,353 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
if config.trained_betas is not None:
betas = jnp.asarray(config.trained_betas, dtype=scheduler.dtype)
elif config.beta_schedule == "linear":
betas = jnp.linspace(config.beta_start, config.beta_end, config.num_train_timesteps, dtype=scheduler.dtype)
elif config.beta_schedule == "s... | 1,353 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
alphas = 1.0 - betas
alphas_cumprod = jnp.cumprod(alphas, axis=0)
return cls(
alphas=alphas,
betas=betas,
alphas_cumprod=alphas_cumprod,
) | 1,353 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_utils_flax.py |
class SdeVeOutput(BaseOutput):
"""
Output class for the scheduler's `step` function output.
Args:
prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model in... | 1,354 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
class ScoreSdeVeScheduler(SchedulerMixin, ConfigMixin):
"""
`ScoreSdeVeScheduler` is a variance exploding stochastic differential equation (SDE) scheduler.
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
methods the library implements ... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
Args:
num_train_timesteps (`int`, defaults to 1000):
The number of diffusion steps to train the model.
snr (`float`, defaults to 0.15):
A coefficient weighting the step from the `model_output` sample (from the network) to the random noise.
sigma_min (`float`, defaults to ... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
@register_to_config
def __init__(
self,
num_train_timesteps: int = 2000,
snr: float = 0.15,
sigma_min: float = 0.01,
sigma_max: float = 1348.0,
sampling_eps: float = 1e-5,
correct_steps: int = 1,
):
# standard deviation of the initial noise distrib... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
Returns:
`torch.Tensor`:
A scaled input sample.
"""
return sample
def set_timesteps(
self, num_inference_steps: int, sampling_eps: float = None, device: Union[str, torch.device] = None
):
"""
Sets the continuous timesteps used for the diffusio... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
self.timesteps = torch.linspace(1, sampling_eps, num_inference_steps, device=device)
def set_sigmas(
self, num_inference_steps: int, sigma_min: float = None, sigma_max: float = None, sampling_eps: float = None
):
"""
Sets the noise scales used for the diffusion chain (to be run before i... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
Args:
num_inference_steps (`int`):
The number of diffusion steps used when generating samples with a pre-trained model.
sigma_min (`float`, optional):
The initial noise scale value (overrides value given during scheduler instantiation).
sigma_max (`flo... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
self.sigmas = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
self.discrete_sigmas = torch.exp(torch.linspace(math.log(sigma_min), math.log(sigma_max), num_inference_steps))
self.sigmas = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps])
def get... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
Args:
model_output (`torch.Tensor`):
The direct output from learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusio... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
"""
if self.timesteps is None:
raise ValueError(
"`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
)
timestep = timestep * torch.ones(
sample.shape[0], device=sample.device
) # torch.repeat_interleave... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
# equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
# also equation 47 shows the analog from SDE models to ancestral sampling methods
diffusion = diffusion.flatten()
while len(diffusion.shape) < len(sample.shape):
diffusion = diffusion.unsqueeze(-1)... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
return SdeVeOutput(prev_sample=prev_sample, prev_sample_mean=prev_sample_mean)
def step_correct(
self,
model_output: torch.Tensor,
sample: torch.Tensor,
generator: Optional[torch.Generator] = None,
return_dict: bool = True,
) -> Union[SchedulerOutput, Tuple]:
"""... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
Returns:
[`~schedulers.scheduling_sde_ve.SdeVeOutput`] or `tuple`:
If return_dict is `True`, [`~schedulers.scheduling_sde_ve.SdeVeOutput`] is returned, otherwise a tuple
is returned where the first element is the sample tensor.
"""
if self.timesteps is None:
... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
# compute step size from the model_output, the noise, and the snr
grad_norm = torch.norm(model_output.reshape(model_output.shape[0], -1), dim=-1).mean()
noise_norm = torch.norm(noise.reshape(noise.shape[0], -1), dim=-1).mean()
step_size = (self.config.snr * noise_norm / grad_norm) ** 2 * 2
... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
def add_noise(
self,
original_samples: torch.Tensor,
noise: torch.Tensor,
timesteps: torch.Tensor,
) -> torch.Tensor:
# Make sure sigmas and timesteps have the same device and dtype as original_samples
timesteps = timesteps.to(original_samples.device)
sigmas =... | 1,355 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_sde_ve.py |
class IPNDMScheduler(SchedulerMixin, ConfigMixin):
"""
A fourth-order Improved Pseudo Linear Multistep scheduler.
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
methods the library implements for all schedulers such as loading and sav... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
# For now we only support F-PNDM, i.e. the runge-kutta method
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
# mainly at formula (9), (12), (13) and the Algorithm 2.
self.pndm_order = 4
# running values
self.ets = []... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
def set_begin_index(self, begin_index: int = 0):
"""
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
Args:
begin_... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
Args:
num_inference_steps (`int`):
The number of diffusion steps used when generating samples with a pre-trained model.
device (`str` or `torch.device`, *optional*):
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler.index_for_timestep
def index_for_timestep(self, timestep, schedule_timesteps=None):
if schedule_timesteps is None:
schedule_timesteps = self.timesteps
indices = (schedule_timesteps == timestep).nonzero()... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._init_step_index
def _init_step_index(self, timestep):
if self.begin_index is None:
if isinstance(timestep, torch.Tensor):
timestep = timestep.to(self.timesteps.device)
self._step_inde... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
Args:
model_output (`torch.Tensor`):
The direct output from learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusio... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
Returns:
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
tuple is returned where the first element is the sample tensor.
"""
if self.num_inference_... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
if len(self.ets) == 1:
ets = self.ets[-1]
elif len(self.ets) == 2:
ets = (3 * self.ets[-1] - self.ets[-2]) / 2
elif len(self.ets) == 3:
ets = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
else:
ets = (1 / 24) * (55 * self.ets[-1] ... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
Returns:
`torch.Tensor`:
A scaled input sample.
"""
return sample
def _get_prev_sample(self, sample, timestep_index, prev_timestep_index, ets):
alpha = self.alphas[timestep_index]
sigma = self.betas[timestep_index]
next_alpha = self.alphas[prev_t... | 1,356 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_ipndm.py |
class DEISMultistepScheduler(SchedulerMixin, ConfigMixin):
"""
`DEISMultistepScheduler` is a fast high order solver for diffusion ordinary differential equations (ODEs).
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
methods the libra... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Args:
num_train_timesteps (`int`, defaults to 1000):
The number of diffusion steps to train the model.
beta_start (`float`, defaults to 0.0001):
The starting `beta` value of inference.
beta_end (`float`, defaults to 0.02):
The final `beta` value.
beta_... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
Video](https://imagen.research.google/video/paper.pdf) paper).
thresholding (`bool`, def... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps.
use_karras_sigmas (`bool`, *optional*, defaults to `False`):
Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
the sigmas are determined a... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
steps_offset (`int`, defaults to 0):
An offset added to the inference steps, as required by some ... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
order = 1 | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
@register_to_config
def __init__(
self,
num_train_timesteps: int = 1000,
beta_start: float = 0.0001,
beta_end: float = 0.02,
beta_schedule: str = "linear",
trained_betas: Optional[np.ndarray] = None,
solver_order: int = 2,
prediction_type: str = "epsil... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
raise ImportError("Make sure to install scipy if you want to use beta sigmas.")
if sum([self.config.use_beta_sigmas, self.config.use_exponential_sigmas, self.config.use_karras_sigmas]) > 1:
raise ValueError(
"Only one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `con... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
self.betas = betas_for_alpha_bar(num_train_timesteps)
else:
raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}") | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
self.alphas = 1.0 - self.betas
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
# Currently we only support VP-type noise schedule
self.alpha_t = torch.sqrt(self.alphas_cumprod)
self.sigma_t = torch.sqrt(1 - self.alphas_cumprod)
self.lambda_t = torch.log(self.alpha_t) - to... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if solver_type not in ["logrho"]:
if solver_type in ["midpoint", "heun", "bh1", "bh2"]:
self.register_to_config(solver_type="logrho")
else:
raise NotImplementedError(f"solver type {solver_type} is not implemented for {self.__class__}")
# setable values
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
@property
def begin_index(self):
"""
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
"""
return self._begin_index
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
def... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Args:
num_inference_steps (`int`):
The number of diffusion steps used when generating samples with a pre-trained model.
device (`str` or `torch.device`, *optional*):
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# casting to int to avoid issues when num_inference_step is power of 3
timesteps = (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64)
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
step_ratio... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
log_sigmas = np.log(sigmas)
if self.config.use_karras_sigmas:
sigmas = np.flip(sigmas).copy()
sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
timest... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
sigmas = self._convert_to_beta(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas])
sigmas = np.concatenate([sigmas, sigmas[-1:]]).astype(np.float32)
elif self.config.use_flow_sigmas:
alphas... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
self.sigmas = torch.from_numpy(sigmas)
self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64)
self.num_inference_steps = len(timesteps)
self.model_outputs = [
None,
] * self.config.solver_order
self.lower_order_nums = 0
# add an i... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
"""
"Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
prediction of x_0 at timest... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if dtype not in (torch.float32, torch.float64):
sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
# Flatten sample for doing quantile calculation along each image
sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t
def _sigma_to_t(self, sigma, log_sigmas):
# get log sigma
log_sigma = np.log(np.maximum(sigma, 1e-10))
# get distribution
dists = log_sigma - log_sigmas[:, np.newaxis]
# get sigm... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._sigma_to_alpha_sigma_t
def _sigma_to_alpha_sigma_t(self, sigma):
if self.config.use_flow_sigmas:
alpha_t = 1 - sigma
sigma_t = sigma
else:
alpha_t = 1 / ((sigma**2 + 1) ... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if hasattr(self.config, "sigma_max"):
sigma_max = self.config.sigma_max
else:
sigma_max = None
sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
rho = 7.0 # 7.0 is th... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# Hack to make sure that other schedulers which copy this function don't break
# TODO: Add this logic to the other schedulers
if hasattr(self.config, "sigma_min"):
sigma_min = self.config.sigma_min
else:
sigma_min = None
if hasattr(self.config, "sigma_max"):
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
# Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_beta
def _convert_to_beta(
self, in_sigmas: torch.Tensor, num_inference_steps: int, alpha: float = 0.6, beta: float = 0.6
) -> torch.Tensor:
"""From "Beta Sampling is All You Need" [arXiv:2407.12173] ... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
sigmas = np.array(
[
sigma_min + (ppf * (sigma_max - sigma_min))
for ppf in [
scipy.stats.beta.ppf(timestep, alpha, beta)
for timestep in 1 - np.linspace(0, 1, num_inference_steps)
]
]
)
retur... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Returns:
`torch.Tensor`:
The converted model output.
"""
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
if sample is None:
if len(args) > 1:
sample = args[1]
else:
raise ValueError("missing... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
sigma = self.sigmas[self.step_index]
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
if self.config.prediction_type == "epsilon":
x0_pred = (sample - sigma_t * model_output) / alpha_t
elif self.config.prediction_type == "sample":
x0_pred = model_output
elif... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if self.config.algorithm_type == "deis":
return (sample - alpha_t * x0_pred) / sigma_t
else:
raise NotImplementedError("only support log-rho multistep deis now")
def deis_first_order_update(
self,
model_output: torch.Tensor,
*args,
sample: torch.Tenso... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Returns:
`torch.Tensor`:
The sample tensor at the previous timestep.
"""
timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
if len... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if prev_timestep is not None:
deprecate(
"prev_timestep",
"1.0.0",
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
sigma_t, sigma_s = self.sig... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
def multistep_deis_second_order_update(
self,
model_output_list: List[torch.Tensor],
*args,
sample: torch.Tensor = None,
**kwargs,
) -> torch.Tensor:
"""
One step for the second-order multistep DEIS.
Args:
model_output_list (`List[torch.Te... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Returns:
`torch.Tensor`:
The sample tensor at the previous timestep.
"""
timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
if prev_timestep is not None:
deprecate(
"prev_timestep",
"1.0.0",
"Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
)
sigma_t, sigma_s0, sigma_s1... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
def ind_fn(t, b, c):
# Integrate[(log(t) - log(c)) / (log(b) - log(c)), {t}]
return t * (-np.log(c) + np.log(t) - 1) / (np.log(b) - np.log(c))
coef1 = ind_fn(rho_t, rho_s0, rho_s1) - ind_fn(rho_s0, rho_s0, rho_s1)
coef2 = ind_fn(rho_t, rho_s1, rho_s0) - ind_fn(rh... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Args:
model_output_list (`List[torch.Tensor]`):
The direct outputs from learned diffusion model at current and latter timesteps.
sample (`torch.Tensor`):
A current instance of a sample created by diffusion process.
Returns:
`torch.Tensor`:
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None)
prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None)
if sample is None:
if len(args) > 2:
sample = args[2]
else:
raise ValueError(" missing`s... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
self.sigmas[self.step_index + 1],
self.sigmas[self.step_index],
self.sigmas[self.step_index - 1],
self.sigmas[self.step_index - 2],
)
alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
alpha_s0, sigm... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
def ind_fn(t, b, c, d):
# Integrate[(log(t) - log(c))(log(t) - log(d)) / (log(b) - log(c))(log(b) - log(d)), {t}]
numerator = t * (
np.log(c) * (np.log(d) - np.log(t) + 1)
- np.log(d) * np.log(t)
+ np.log(d)
... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
return x_t
else:
raise NotImplementedError("only support log-rho multistep deis now")
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.index_for_timestep
def index_for_timestep(self, timestep, schedule_timesteps=None):
if schedule_timeste... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
return step_index
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
def _init_step_index(self, timestep):
"""
Initialize the step_index counter for the scheduler.
"""
if self.begin_index is None:
if isinst... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Args:
model_output (`torch.Tensor`):
The direct output from learned diffusion model.
timestep (`int`):
The current discrete timestep in the diffusion chain.
sample (`torch.Tensor`):
A current instance of a sample created by the diffusio... | 1,357 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/schedulers/scheduling_deis_multistep.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.