"hip/vscode:/vscode.git/clone" did not exist on "ac6a172dcfff8e47686db830f023f365f983b439"
scheduling_sde_vp.py 4.19 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
# Copyright 2023 Google Brain and The HuggingFace Team. All rights reserved.
Patrick von Platen's avatar
Patrick von Platen committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch

17
import math
18
from typing import Union
19

Patrick von Platen's avatar
Patrick von Platen committed
20
21
import torch

22
from ..configuration_utils import ConfigMixin, register_to_config
Dhruv Nair's avatar
Dhruv Nair committed
23
from ..utils.torch_utils import randn_tensor
Patrick von Platen's avatar
Patrick von Platen committed
24
25
26
27
from .scheduling_utils import SchedulerMixin


class ScoreSdeVpScheduler(SchedulerMixin, ConfigMixin):
28
    """
29
    `ScoreSdeVpScheduler` is a variance preserving stochastic differential equation (SDE) scheduler.
30

31
32
    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 saving.
33

34
35
36
37
38
39
40
    Args:
        num_train_timesteps (`int`, defaults to 2000):
            The number of diffusion steps to train the model.
        beta_min (`int`, defaults to 0.1):
        beta_max (`int`, defaults to 20):
        sampling_eps (`int`, defaults to 1e-3):
            The end value of sampling where timesteps decrease progressively from 1 to epsilon.
41
42
    """

43
44
    order = 1

45
    @register_to_config
Anton Lozhkov's avatar
Anton Lozhkov committed
46
    def __init__(self, num_train_timesteps=2000, beta_min=0.1, beta_max=20, sampling_eps=1e-3):
Patrick von Platen's avatar
Patrick von Platen committed
47
48
49
50
        self.sigmas = None
        self.discrete_sigmas = None
        self.timesteps = None

51
    def set_timesteps(self, num_inference_steps, device: Union[str, torch.device] = None):
52
53
54
55
56
57
58
59
60
        """
        Sets the continuous timesteps used for the diffusion chain (to be run before inference).

        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.
        """
61
        self.timesteps = torch.linspace(1, self.config.sampling_eps, num_inference_steps, device=device)
Patrick von Platen's avatar
Patrick von Platen committed
62

63
    def step_pred(self, score, x, t, generator=None):
64
65
66
67
68
69
70
71
72
73
74
        """
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
        process from the learned model outputs (most often the predicted noise).

        Args:
            score ():
            x ():
            t ():
            generator (`torch.Generator`, *optional*):
                A random number generator.
        """
75
76
77
78
79
        if self.timesteps is None:
            raise ValueError(
                "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler"
            )

Patrick von Platen's avatar
Patrick von Platen committed
80
        # TODO(Patrick) better comments + non-PyTorch
Nathan Lambert's avatar
Nathan Lambert committed
81
        # postprocess model score
82
        log_mean_coeff = -0.25 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min
Patrick von Platen's avatar
Patrick von Platen committed
83
        std = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff))
84
85
86
87
        std = std.flatten()
        while len(std.shape) < len(score.shape):
            std = std.unsqueeze(-1)
        score = -score / std
Patrick von Platen's avatar
Patrick von Platen committed
88

Patrick von Platen's avatar
Patrick von Platen committed
89
90
91
92
        # compute
        dt = -1.0 / len(self.timesteps)

        beta_t = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min)
93
94
95
96
97
        beta_t = beta_t.flatten()
        while len(beta_t.shape) < len(x.shape):
            beta_t = beta_t.unsqueeze(-1)
        drift = -0.5 * beta_t * x

Patrick von Platen's avatar
Patrick von Platen committed
98
        diffusion = torch.sqrt(beta_t)
99
        drift = drift - diffusion**2 * score
Patrick von Platen's avatar
Patrick von Platen committed
100
        x_mean = x + drift * dt
Patrick von Platen's avatar
Patrick von Platen committed
101
102

        # add noise
103
        noise = randn_tensor(x.shape, layout=x.layout, generator=generator, device=x.device, dtype=x.dtype)
104
        x = x_mean + diffusion * math.sqrt(-dt) * noise
Patrick von Platen's avatar
Patrick von Platen committed
105
106

        return x, x_mean
Nathan Lambert's avatar
Nathan Lambert committed
107
108
109

    def __len__(self):
        return self.config.num_train_timesteps