Embeds scalar timesteps into vector representations.
| 57 | |
| 58 | |
| 59 | class TimestepEmbedder(nn.Module): |
| 60 | """ |
| 61 | Embeds scalar timesteps into vector representations. |
| 62 | """ |
| 63 | def __init__(self, hidden_size, frequency_embedding_size=256): |
| 64 | super().__init__() |
| 65 | self.mlp = nn.Sequential( |
| 66 | nn.Linear(frequency_embedding_size, hidden_size, bias=True), |
| 67 | nn.SiLU(), |
| 68 | nn.Linear(hidden_size, hidden_size, bias=True), |
| 69 | ) |
| 70 | self.frequency_embedding_size = frequency_embedding_size |
| 71 | |
| 72 | @staticmethod |
| 73 | def timestep_embedding(t, dim, max_period=10000): |
| 74 | """ |
| 75 | Create sinusoidal timestep embeddings. |
| 76 | :param t: a 1-D Tensor of N indices, one per batch element. |
| 77 | These may be fractional. |
| 78 | :param dim: the dimension of the output. |
| 79 | :param max_period: controls the minimum frequency of the embeddings. |
| 80 | :return: an (N, D) Tensor of positional embeddings. |
| 81 | """ |
| 82 | # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py |
| 83 | half = dim // 2 |
| 84 | freqs = torch.exp( |
| 85 | -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half |
| 86 | ).to(device=t.device) |
| 87 | args = t[:, None].float() * freqs[None] |
| 88 | embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) |
| 89 | if dim % 2: |
| 90 | embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) |
| 91 | return embedding |
| 92 | |
| 93 | def forward(self, t): |
| 94 | t_freq = self.timestep_embedding(t, self.frequency_embedding_size) |
| 95 | t_emb = self.mlp(t_freq) |
| 96 | return t_emb |
| 97 | |
| 98 | |
| 99 | class ResBlock(nn.Module): |