embeddings.py 2.87 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
25
    """
    This matches the implementation in Denoising Diffusion Probabilistic Models:
26
27
28
29
30
31
32
33

    Create sinusoidal timestep embeddings.

    :param timesteps: a 1-D Tensor of N indices, one per batch element.
                      These may be fractional.
    :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
34
    """
35
    assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
Patrick von Platen's avatar
Patrick von Platen committed
36
37

    half_dim = embedding_dim // 2
38

39
40
41
    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)
42
43
    emb = timesteps[:, None].float() * emb[None, :]

44
45
46
    # scale embeddings
    emb = scale * emb

47
    # concat sine and cosine embeddings
48
    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
49

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


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

64
65
66
67
68
69
70
    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)
Patrick von Platen's avatar
Patrick von Platen committed
71
72


73
# unet_rl.py - TODO(need test)
Patrick von Platen's avatar
Patrick von Platen committed
74
75
76
77
78
79
80
81
82
83
84
85
86
class SinusoidalPosEmb(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.dim = dim

    def forward(self, x):
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
        emb = x[:, None] * emb[None, :]
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb