embeddings.py 3.79 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
def get_timestep_embedding(
Kashif Rasul's avatar
Kashif Rasul committed
22
23
24
25
26
27
    timesteps: torch.Tensor,
    embedding_dim: int,
    flip_sin_to_cos: bool = False,
    downscale_freq_shift: float = 1,
    scale: float = 1,
    max_period: int = 10000,
28
):
Patrick von Platen's avatar
Patrick von Platen committed
29
    """
Patrick von Platen's avatar
Patrick von Platen committed
30
    This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
31
32
33

    :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
34
35
    :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
36
    """
37
    assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
Patrick von Platen's avatar
Patrick von Platen committed
38
39

    half_dim = embedding_dim // 2
40
41
42
    exponent = -math.log(max_period) * torch.arange(
        start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
    )
43
    exponent = exponent / (half_dim - downscale_freq_shift)
44

45
    emb = torch.exp(exponent)
46
47
    emb = timesteps[:, None].float() * emb[None, :]

48
49
50
    # scale embeddings
    emb = scale * emb

51
    # concat sine and cosine embeddings
52
    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
53

54
    # flip sine and cosine embeddings
55
56
57
58
59
    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
60
61
62
63
        emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
    return emb


64
class TimestepEmbedding(nn.Module):
Kashif Rasul's avatar
Kashif Rasul committed
65
    def __init__(self, channel: int, time_embed_dim: int, act_fn: str = "silu"):
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        super().__init__()

        self.linear_1 = nn.Linear(channel, time_embed_dim)
        self.act = None
        if act_fn == "silu":
            self.act = nn.SiLU()
        self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim)

    def forward(self, sample):
        sample = self.linear_1(sample)

        if self.act is not None:
            sample = self.act(sample)

        sample = self.linear_2(sample)
        return sample


class Timesteps(nn.Module):
Kashif Rasul's avatar
Kashif Rasul committed
85
    def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float):
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        super().__init__()
        self.num_channels = num_channels
        self.flip_sin_to_cos = flip_sin_to_cos
        self.downscale_freq_shift = downscale_freq_shift

    def forward(self, timesteps):
        t_emb = get_timestep_embedding(
            timesteps,
            self.num_channels,
            flip_sin_to_cos=self.flip_sin_to_cos,
            downscale_freq_shift=self.downscale_freq_shift,
        )
        return t_emb


101
102
class GaussianFourierProjection(nn.Module):
    """Gaussian Fourier embeddings for noise levels."""
Patrick von Platen's avatar
Patrick von Platen committed
103

Kashif Rasul's avatar
Kashif Rasul committed
104
    def __init__(self, embedding_size: int = 256, scale: float = 1.0):
105
        super().__init__()
106
107
108
        self.weight = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)

        # to delete later
109
110
        self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)

111
112
        self.weight = self.W

113
    def forward(self, x):
114
115
116
117
        x = torch.log(x)
        x_proj = x[:, None] * self.weight[None, :] * 2 * np.pi
        out = torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
        return out