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".
(timesteps, embedding_dim)
| 25 | |
| 26 | |
| 27 | def get_timestep_embedding(timesteps, embedding_dim): |
| 28 | """ |
| 29 | This matches the implementation in Denoising Diffusion Probabilistic Models: |
| 30 | From Fairseq. |
| 31 | Build sinusoidal embeddings. |
| 32 | This matches the implementation in tensor2tensor, but differs slightly |
| 33 | from the description in Section 3.5 of "Attention Is All You Need". |
| 34 | """ |
| 35 | assert len(timesteps.shape) == 1 |
| 36 | |
| 37 | half_dim = embedding_dim // 2 |
| 38 | emb = math.log(10000) / (half_dim - 1) |
| 39 | emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) |
| 40 | emb = emb.to(device=timesteps.device) |
| 41 | emb = timesteps.float()[:, None] * emb[None, :] |
| 42 | emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) |
| 43 | if embedding_dim % 2 == 1: # zero pad |
| 44 | emb = torch.nn.functional.pad(emb, (0,1,0,0)) |
| 45 | return emb |
| 46 | |
| 47 | |
| 48 | def nonlinearity(x): |