"docs/vscode:/vscode.git/clone" did not exist on "a5c86ffacfae67eef76bce73b49c6eee9ee2176b"
embeddings.py 2.4 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# 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.
14
import math
Patrick von Platen's avatar
Patrick von Platen committed
15

16
17
import numpy as np
import torch
18
from torch import nn
Patrick von Platen's avatar
Patrick von Platen committed
19

20

21
22
23
def get_timestep_embedding(
    timesteps, embedding_dim, flip_sin_to_cos=False, downscale_freq_shift=1, scale=1, max_period=10000
):
Patrick von Platen's avatar
Patrick von Platen committed
24
    """
Patrick von Platen's avatar
Patrick von Platen committed
25
    This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
26
27
28

    :param timesteps: a 1-D Tensor of N indices, one per batch element.
                      These may be fractional.
Patrick von Platen's avatar
Patrick von Platen committed
29
30
    :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
    embeddings. :return: an [N x dim] Tensor of positional embeddings.
Patrick von Platen's avatar
Patrick von Platen committed
31
    """
32
    assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
Patrick von Platen's avatar
Patrick von Platen committed
33
34

    half_dim = embedding_dim // 2
35

36
37
38
    emb_coeff = -math.log(max_period) / (half_dim - downscale_freq_shift)
    emb = torch.arange(half_dim, dtype=torch.float32, device=timesteps.device)
    emb = torch.exp(emb * emb_coeff)
39
40
    emb = timesteps[:, None].float() * emb[None, :]

41
42
43
    # scale embeddings
    emb = scale * emb

44
    # concat sine and cosine embeddings
45
    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
46

47
    # flip sine and cosine embeddings
48
49
50
51
52
    if flip_sin_to_cos:
        emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)

    # zero pad
    if embedding_dim % 2 == 1:
Patrick von Platen's avatar
Patrick von Platen committed
53
54
55
56
        emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
    return emb


57
58
59
# unet_sde_score_estimation.py
class GaussianFourierProjection(nn.Module):
    """Gaussian Fourier embeddings for noise levels."""
Patrick von Platen's avatar
Patrick von Platen committed
60

61
62
63
64
65
66
67
    def __init__(self, embedding_size=256, scale=1.0):
        super().__init__()
        self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)

    def forward(self, x):
        x_proj = x[:, None] * self.W[None, :] * 2 * np.pi
        return torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)