embeddings.py 5.75 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
15
16
import torch
import math
import numpy as np
Patrick von Platen's avatar
Patrick von Platen committed
17

18
19
from torch import nn
import torch.nn.functional as F
Patrick von Platen's avatar
Patrick von Platen committed
20

21
22

def get_timestep_embedding(timesteps, embedding_dim, flip_sin_to_cos=False, downscale_freq_shift=1, max_period=10000):
Patrick von Platen's avatar
Patrick von Platen committed
23
24
    """
    This matches the implementation in Denoising Diffusion Probabilistic Models:
25
26
27
28
29
30
31
32

    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
33
34
35
36
    """
    assert len(timesteps.shape) == 1

    half_dim = embedding_dim // 2
37
38
    emb = torch.exp(-math.log(max_period) * torch.arange(half_dim, dtype=torch.float32) / (embedding_dim // 2 - downscale_freq_shift))

Patrick von Platen's avatar
Patrick von Platen committed
39
    emb = emb.to(device=timesteps.device)
40
41
42
    emb = timesteps[:, None].float() * emb[None, :]

    # concat sine and cosine embeddings
Patrick von Platen's avatar
Patrick von Platen committed
43
    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
44
45
46
47
48
49
50

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


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#def get_timestep_embedding(timesteps, embedding_dim):
#    """
#    This matches the implementation in Denoising Diffusion Probabilistic Models:
#    From Fairseq.
#    Build sinusoidal embeddings.
#    This matches the implementation in tensor2tensor, but differs slightly
#    from the description in Section 3.5 of "Attention Is All You Need".
#    """
#    assert len(timesteps.shape) == 1
#
#    half_dim = embedding_dim // 2
#    emb = math.log(10000) / (half_dim - 1)
#    emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
#    emb = emb.to(device=timesteps.device)
#    emb = timesteps.float()[:, None] * emb[None, :]
#    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
#    if embedding_dim % 2 == 1:  # zero pad
#        emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))


#def timestep_embedding(timesteps, dim, max_period=10000):
#    """
#    Create sinusoidal timestep embeddings.
#
#    :param timesteps: a 1-D Tensor of N indices, one per batch element.
#                      These may be fractional.
#    :param 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.
#    """
#    half = dim // 2
#    freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
#        device=timesteps.device
#    )
#    args = timesteps[:, None].float() * freqs[None, :]
#    embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
#    if dim % 2:
#        embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
#    return embedding


#def a_get_timestep_embedding(timesteps, embedding_dim, max_positions=10000):
#    assert len(timesteps.shape) == 1  # and timesteps.dtype == tf.int32
#    half_dim = embedding_dim // 2
    # magic number 10000 is from transformers
#    emb = math.log(max_positions) / (half_dim - 1)
    # emb = math.log(2.) / (half_dim - 1)
#    emb = torch.exp(torch.arange(half_dim, dtype=torch.float32, device=timesteps.device) * -emb)
    # emb = tf.range(num_embeddings, dtype=jnp.float32)[:, None] * emb[None, :]
    # emb = tf.cast(timesteps, dtype=jnp.float32)[:, None] * emb[None, :]
#    emb = timesteps.float()[:, None] * emb[None, :]
#    emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
#    if embedding_dim % 2 == 1:  # zero pad
#        emb = F.pad(emb, (0, 1), mode="constant")
#    assert emb.shape == (timesteps.shape[0], embedding_dim)
#    return emb

Patrick von Platen's avatar
Patrick von Platen committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

# unet_grad_tts.py
class SinusoidalPosEmb(torch.nn.Module):
    def __init__(self, dim):
        super(SinusoidalPosEmb, self).__init__()
        self.dim = dim

    def forward(self, x, scale=1000):
        device = x.device
        half_dim = self.dim // 2
        emb = math.log(10000) / (half_dim - 1)
        emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
        emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
        emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
        return emb


# unet_rl.py
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


# unet_sde_score_estimation.py
class GaussianFourierProjection(nn.Module):
    """Gaussian Fourier embeddings for noise levels."""

    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)