当前位置:   article > 正文

DiT (Scalable Diffusion Models with Transformers) 论文学习笔记_dit结构中的cross-attention

dit结构中的cross-attention

论文:https://arxiv.org/abs/2212.09748

代码:​​​​​​​GitHub - facebookresearch/DiT: Official PyTorch Implementation of "Scalable Diffusion Models with Transformers"

Classifier-free guidance:使用条件分类器梯度引导无条件生成,得到类别条件生成的梯度。

Classifier-Free Guidance 以zero-shot的方式训练额外的分类器,实现各种条件的引导生成。如结合 CLIP 文本编码器提取 prompt 的文本特征 embedding,输入到 diffusion 模型中作为文本条件。

伪代码:

  1. unet = ... # 加载unet去噪模型
  2. clip_model = ... # 加载CLIP模型
  3. text = "a cat" # 文本条件
  4. text_embeddings = clip_model.text_encode(text) # 编码条件文本,cond
  5. empty_embeddings = clip_model.text_encode("") # 编码空文本,uncond
  6. text_embeddings = torch.cat(empty_embeddings, text_embeddings) # concat到一起,只做一次forward
  7. input = torch.randn((1, 3, sample_size, sample_size), device="cuda") # 采样初始噪声
  8. for t in scheduler.timesteps:
  9. # 用 unet 推理,预测噪声
  10. with torch.no_grad():
  11. # 这里同时预测出了有文本的和空文本的图像噪声
  12. noise_pred = unet(input, t, encoder_hidden_states=text_embeddings).sample
  13. # 拆成无条件和有条件的噪声
  14. noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
  15. # Classifier-Free Guidance 引导
  16. noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
  17. # 用预测出的 noise_pred 和 x_t 计算得到 x_t-1
  18. latents = scheduler.step(noise_pred, t, latents).prev_sample

DiT代码实现:

  1. # Create sampling noise:
  2. n = len(class_labels)
  3. z = torch.randn(n, 4, latent_size, latent_size, device=device)
  4. y = torch.tensor(class_labels, device=device)
  5. # Setup classifier-free guidance:
  6. z = torch.cat([z, z], 0)
  7. y_null = torch.tensor([1000] * n, device=device)
  8. y = torch.cat([y, y_null], 0)
  9. model_kwargs = dict(y=y, cfg_scale=args.cfg_scale)
  1. def forward_with_cfg(self, x, t, y, cfg_scale): # x: [16, 4, 32, 32]
  2. """
  3. Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance.
  4. """
  5. # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb
  6. half = x[: len(x) // 2] # [8, 4, 32, 32]
  7. combined = torch.cat([half, half], dim=0) # [16, 4, 32, 32]
  8. model_out = self.forward(combined, t, y) # [16, 8, 32, 32]
  9. # For exact reproducibility reasons, we apply classifier-free guidance on only
  10. # three channels by default. The standard approach to cfg applies it to all channels.
  11. # This can be done by uncommenting the following line and commenting-out the line following that.
  12. # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]
  13. eps, rest = model_out[:, :3], model_out[:, 3:] # [16, 3, 32, 32], [16, 5, 32, 32]
  14. cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0) # [8, 3, 32, 32]
  15. half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps) # [8, 3, 32, 32]
  16. eps = torch.cat([half_eps, half_eps], dim=0) # [16, 3, 32, 32]
  17. return torch.cat([eps, rest], dim=1) # [16, 8, 32, 32]

在训练过程中以一定概率令条件编码=空,得到条件生成和无条件生成的输出,再将其线性组合作为最终的输出。

Patchify:patch_embedding

代码实现: 

  1. '''
  2. PatchEmbed(
  3. (proj): Conv2d(4, 1152, kernel_size=(2, 2), stride=(2, 2))
  4. (norm): Identity()
  5. )
  6. [16, 4, 32, 32] → [16, 256, 1152]
  7. '''
  8. self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)

 DiT结构:

In-context conditioning:将 Timestep t 和 Label y 的 Embedding 作为输入序列中的两个附加条件,类似于ViTs中的cls token。

  1. x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2 [16, 256, 1152] + [1, 256, 1152] = [16, 256, 1152]
  2. t = self.t_embedder(t) # (N, D) # [16, 1152]
  3. y = self.y_embedder(y, self.training) # (N, D) # [16, 1152]
  4. c = t + y # (N, D) # [16, 1152]

位置编码:梯度不更新

  1. # Will use fixed sin-cos embedding:
  2. self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)
  3. # Initialize (and freeze) pos_embed by sin-cos embedding:
  4. pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5)) # (256, 1152)
  5. self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) # (1, 256, 1152)
  6. def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
  7. """
  8. grid_size: int of the grid height and width 16
  9. return:
  10. pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
  11. """
  12. grid_h = np.arange(grid_size, dtype=np.float32)
  13. grid_w = np.arange(grid_size, dtype=np.float32)
  14. grid = np.meshgrid(grid_w, grid_h) # here w goes first
  15. grid = np.stack(grid, axis=0) # (2, 16, 16)
  16. grid = grid.reshape([2, 1, grid_size, grid_size]) # (2, 1, 16, 16)
  17. pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid) # (256, 1152)
  18. if cls_token and extra_tokens > 0:
  19. pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
  20. return pos_embed # (256, 1152)
  21. def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
  22. assert embed_dim % 2 == 0
  23. # embed_dim = 576
  24. # use half of dimensions to encode grid_h
  25. emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # x坐标, (256, 576)
  26. emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # y坐标, (256, 576)
  27. pdb.set_trace()
  28. emb = np.concatenate([emb_h, emb_w], axis=1) # (256, 1152)
  29. return emb
  30. def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
  31. """
  32. embed_dim: output dimension for each position
  33. pos: a list of positions to be encoded: size (M,)
  34. out: (M, D)
  35. """
  36. assert embed_dim % 2 == 0
  37. omega = np.arange(embed_dim // 2, dtype=np.float64)
  38. omega /= embed_dim / 2.
  39. omega = 1. / 10000**omega # (288,)
  40. pos = pos.reshape(-1) # (256,)
  41. out = np.einsum('m,d->md', pos, omega) # (256, 288), outer product
  42. emb_sin = np.sin(out) # (256, 288)
  43. emb_cos = np.cos(out) # (256, 288)
  44. emb = np.concatenate([emb_sin, emb_cos], axis=1) # (256, 576)
  45. return emb

TimestepEmbedder:

  1. class TimestepEmbedder(nn.Module):
  2. """
  3. Embeds scalar timesteps into vector representations.
  4. """
  5. def __init__(self, hidden_size, frequency_embedding_size=256):
  6. super().__init__()
  7. self.mlp = nn.Sequential(
  8. nn.Linear(frequency_embedding_size, hidden_size, bias=True),
  9. nn.SiLU(),
  10. nn.Linear(hidden_size, hidden_size, bias=True),
  11. )
  12. self.frequency_embedding_size = frequency_embedding_size
  13. @staticmethod
  14. def timestep_embedding(t, dim, max_period=10000):
  15. """
  16. Create sinusoidal timestep embeddings.
  17. :param t: a 1-D Tensor of N indices, one per batch element.
  18. These may be fractional.
  19. :param dim: the dimension of the output.
  20. :param max_period: controls the minimum frequency of the embeddings.
  21. :return: an (N, D) Tensor of positional embeddings.
  22. """
  23. # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
  24. half = dim // 2 # 128
  25. freqs = torch.exp(
  26. -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
  27. ).to(device=t.device) # 128
  28. args = t[:, None].float() * freqs[None] # (16, 1) * (1, 128) = (16, 128)
  29. embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) # (16, 256)
  30. if dim % 2:
  31. embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
  32. return embedding # (16, 256)
  33. def forward(self, t):
  34. t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
  35. t_emb = self.mlp(t_freq)
  36. return t_emb # (16, 1152)

LabelEmbedder:

  1. class LabelEmbedder(nn.Module):
  2. """
  3. Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
  4. """
  5. def __init__(self, num_classes, hidden_size, dropout_prob):
  6. super().__init__()
  7. use_cfg_embedding = dropout_prob > 0
  8. self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size) # 1001 → 1152
  9. self.num_classes = num_classes # 1000
  10. self.dropout_prob = dropout_prob # 0.1
  11. def token_drop(self, labels, force_drop_ids=None):
  12. """
  13. Drops labels to enable classifier-free guidance.
  14. """
  15. if force_drop_ids is None:
  16. drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
  17. else:
  18. drop_ids = force_drop_ids == 1
  19. labels = torch.where(drop_ids, self.num_classes, labels)
  20. return labels
  21. def forward(self, labels, train, force_drop_ids=None):
  22. use_dropout = self.dropout_prob > 0 # 0.1
  23. if (train and use_dropout) or (force_drop_ids is not None):
  24. labels = self.token_drop(labels, force_drop_ids)
  25. embeddings = self.embedding_table(labels)
  26. return embeddings # [16, 1152]

token_drop 函数实现了标签的随机丢弃,以实现Classifier-free guidance。在这个函数中,labels参数表示输入的标签,force_drop_ids用于指定哪些标签需要被强制丢弃,dropout_prob表示丢弃的概率,函数使用 torch.where函数根据 drop_ids是否=1将需要丢弃的标签替换为 self.num_classes,此时共有num_classes+1个类别。

Cross-attention:DiT结构与Condition交互的方式,与原来U-Net结构类似;将两个embeddings拼接成一个数量为2的序列,在transformer block中插入一个cross attention,条件embeddings作为cross attention的key和value;这种方式也是目前文生图模型所采用的方式,它需要额外引入15%的Gflops。

Adaptive layer norm (adaLN) block:不直接学习scale参数γ和shift参数β,而是根据t和y的嵌入向量之和对它们进行回归。

代码实现:

  1. class DiTBlock(nn.Module):
  2. """
  3. A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.
  4. """
  5. def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):
  6. super().__init__()
  7. self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
  8. self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)
  9. self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
  10. mlp_hidden_dim = int(hidden_size * mlp_ratio)
  11. approx_gelu = lambda: nn.GELU(approximate="tanh")
  12. self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)
  13. self.adaLN_modulation = nn.Sequential(
  14. nn.SiLU(),
  15. nn.Linear(hidden_size, 6 * hidden_size, bias=True) # [16, 6912]
  16. )
  17. def forward(self, x, c):
  18. # β1, γ1, α1, β2, γ2, α2
  19. shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1) # 6 * [16, 1152]
  20. x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)) # x * scale + shift = [16, 256, 1152] attn() * scale + x = [16, 256, 1152]
  21. x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) # mlp() * scale + x = [16, 256, 1152]
  22. return x

adaLN-Zero block:除了回归γ和β之外,还回归了维度缩放参数α;在残差连接之前对每个块中的linear层进行零初始化,这样网络初始化时transformer block的残差模块就是一个identity函数。

  1. # Zero-out adaLN modulation layers in DiT blocks:
  2. for block in self.blocks:
  3. nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
  4. nn.init.constant_(block.adaLN_modulation[-1].bias, 0)

Transformer decoder:将图像tokens序列解码为输出噪声预测和输出对角协方差预测。这两个输出的形状都等于原始空间输入。首先应用最终层norm(如果使用adaLN则为自适应),并将每个token线性解码为p×p×2C张量,其中C是DiT的输入通道数。

  1. class FinalLayer(nn.Module):
  2. """
  3. The final layer of DiT.
  4. """
  5. def __init__(self, hidden_size, patch_size, out_channels):
  6. super().__init__()
  7. self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
  8. self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
  9. self.adaLN_modulation = nn.Sequential(
  10. nn.SiLU(),
  11. nn.Linear(hidden_size, 2 * hidden_size, bias=True)
  12. )
  13. def forward(self, x, c):
  14. shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) # 2 * [16, 1152]
  15. x = modulate(self.norm_final(x), shift, scale) # [16, 256, 1152]
  16. x = self.linear(x) # [16, 256, 32]
  17. return x

最后,我们将解码后的标记重新排列为其原始空间布局,以获得预测的噪声和协方差。

  1. def unpatchify(self, x):
  2. """
  3. x: (N, T, patch_size**2 * C)
  4. imgs: (N, H, W, C)
  5. """
  6. c = self.out_channels # 8
  7. p = self.x_embedder.patch_size[0] # 2
  8. h = w = int(x.shape[1] ** 0.5) # 16
  9. assert h * w == x.shape[1]
  10. x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) # [16, 16, 16, 2, 2, 8]
  11. x = torch.einsum('nhwpqc->nchpwq', x) # [16, 8, 16, 2, 16, 2]
  12. imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p)) # [16, 8, 32, 32]
  13. return imgs
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号