|
| 1 | +# Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py |
| 2 | +import math |
| 3 | + |
| 4 | +import numpy as np |
| 5 | +import torch |
| 6 | +from einops import rearrange |
| 7 | +from torch import nn |
| 8 | + |
| 9 | + |
| 10 | +def get_timestep_embedding( |
| 11 | + timesteps: torch.Tensor, |
| 12 | + embedding_dim: int, |
| 13 | + flip_sin_to_cos: bool = False, |
| 14 | + downscale_freq_shift: float = 1, |
| 15 | + scale: float = 1, |
| 16 | + max_period: int = 10000, |
| 17 | +): |
| 18 | + """ |
| 19 | + This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings. |
| 20 | +
|
| 21 | + :param timesteps: a 1-D Tensor of N indices, one per batch element. |
| 22 | + These may be fractional. |
| 23 | + :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the |
| 24 | + embeddings. :return: an [N x dim] Tensor of positional embeddings. |
| 25 | + """ |
| 26 | + assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array" |
| 27 | + |
| 28 | + half_dim = embedding_dim // 2 |
| 29 | + exponent = -math.log(max_period) * torch.arange( |
| 30 | + start=0, end=half_dim, dtype=torch.float32, device=timesteps.device |
| 31 | + ) |
| 32 | + exponent = exponent / (half_dim - downscale_freq_shift) |
| 33 | + |
| 34 | + emb = torch.exp(exponent) |
| 35 | + emb = timesteps[:, None].float() * emb[None, :] |
| 36 | + |
| 37 | + # scale embeddings |
| 38 | + emb = scale * emb |
| 39 | + |
| 40 | + # concat sine and cosine embeddings |
| 41 | + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) |
| 42 | + |
| 43 | + # flip sine and cosine embeddings |
| 44 | + if flip_sin_to_cos: |
| 45 | + emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1) |
| 46 | + |
| 47 | + # zero pad |
| 48 | + if embedding_dim % 2 == 1: |
| 49 | + emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) |
| 50 | + return emb |
| 51 | + |
| 52 | + |
| 53 | +def get_3d_sincos_pos_embed(embed_dim, grid, w, h, f): |
| 54 | + """ |
| 55 | + grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or |
| 56 | + [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token) |
| 57 | + """ |
| 58 | + grid = rearrange(grid, "c (f h w) -> c f h w", h=h, w=w) |
| 59 | + grid = rearrange(grid, "c f h w -> c h w f", h=h, w=w) |
| 60 | + grid = grid.reshape([3, 1, w, h, f]) |
| 61 | + pos_embed = get_3d_sincos_pos_embed_from_grid(embed_dim, grid) |
| 62 | + pos_embed = pos_embed.transpose(1, 0, 2, 3) |
| 63 | + return rearrange(pos_embed, "h w f c -> (f h w) c") |
| 64 | + |
| 65 | + |
| 66 | +def get_3d_sincos_pos_embed_from_grid(embed_dim, grid): |
| 67 | + if embed_dim % 3 != 0: |
| 68 | + raise ValueError("embed_dim must be divisible by 3") |
| 69 | + |
| 70 | + # use half of dimensions to encode grid_h |
| 71 | + emb_f = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # (H*W*T, D/3) |
| 72 | + emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (H*W*T, D/3) |
| 73 | + emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2]) # (H*W*T, D/3) |
| 74 | + |
| 75 | + emb = np.concatenate([emb_h, emb_w, emb_f], axis=-1) # (H*W*T, D) |
| 76 | + return emb |
| 77 | + |
| 78 | + |
| 79 | +def get_1d_sincos_pos_embed_from_grid(embed_dim, pos): |
| 80 | + """ |
| 81 | + embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D) |
| 82 | + """ |
| 83 | + if embed_dim % 2 != 0: |
| 84 | + raise ValueError("embed_dim must be divisible by 2") |
| 85 | + |
| 86 | + omega = np.arange(embed_dim // 2, dtype=np.float64) |
| 87 | + omega /= embed_dim / 2.0 |
| 88 | + omega = 1.0 / 10000**omega # (D/2,) |
| 89 | + |
| 90 | + pos_shape = pos.shape |
| 91 | + |
| 92 | + pos = pos.reshape(-1) |
| 93 | + out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product |
| 94 | + out = out.reshape([*pos_shape, -1])[0] |
| 95 | + |
| 96 | + emb_sin = np.sin(out) # (M, D/2) |
| 97 | + emb_cos = np.cos(out) # (M, D/2) |
| 98 | + |
| 99 | + emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (M, D) |
| 100 | + return emb |
| 101 | + |
| 102 | + |
| 103 | +class SinusoidalPositionalEmbedding(nn.Module): |
| 104 | + """Apply positional information to a sequence of embeddings. |
| 105 | +
|
| 106 | + Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to |
| 107 | + them |
| 108 | +
|
| 109 | + Args: |
| 110 | + embed_dim: (int): Dimension of the positional embedding. |
| 111 | + max_seq_length: Maximum sequence length to apply positional embeddings |
| 112 | +
|
| 113 | + """ |
| 114 | + |
| 115 | + def __init__(self, embed_dim: int, max_seq_length: int = 32): |
| 116 | + super().__init__() |
| 117 | + position = torch.arange(max_seq_length).unsqueeze(1) |
| 118 | + div_term = torch.exp( |
| 119 | + torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim) |
| 120 | + ) |
| 121 | + pe = torch.zeros(1, max_seq_length, embed_dim) |
| 122 | + pe[0, :, 0::2] = torch.sin(position * div_term) |
| 123 | + pe[0, :, 1::2] = torch.cos(position * div_term) |
| 124 | + self.register_buffer("pe", pe) |
| 125 | + |
| 126 | + def forward(self, x): |
| 127 | + _, seq_length, _ = x.shape |
| 128 | + x = x + self.pe[:, :seq_length] |
| 129 | + return x |
0 commit comments