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
(timesteps, dim, max_period=10000)
| 4 | |
| 5 | |
| 6 | def timestep_embedding(timesteps, dim, max_period=10000): |
| 7 | """ |
| 8 | Create sinusoidal timestep embeddings. |
| 9 | :param timesteps: a 1-D Tensor of N indices, one per batch element. |
| 10 | These may be fractional. |
| 11 | :param dim: the dimension of the output. |
| 12 | :param max_period: controls the minimum frequency of the embeddings. |
| 13 | :return: an [N x dim] Tensor of positional embeddings. |
| 14 | """ |
| 15 | half = dim // 2 |
| 16 | freqs = torch.exp( |
| 17 | -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half |
| 18 | ).to(device=timesteps.device) |
| 19 | args = timesteps[:, None].to(timesteps.dtype) * freqs[None] |
| 20 | embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) |
| 21 | if dim % 2: |
| 22 | embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) |
| 23 | return embedding |