DiT (Scalable Diffusion Models with Transformers) 论文学习笔记

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

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

Classifier-free guidance:使用条件分类器梯度引导无条件生成,得到类别条件生成的梯度,通过梯度信息引导网络生成更加真实的物体,以牺牲样本多样性为代价来提高样本的保真度(真实感),使得Diffusion模型在FID等评价指标上超越GAN。

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

伪代码:

unet = ... # 加载unet去噪模型
clip_model = ...  # 加载CLIP模型

text = "a cat"  # 文本条件
text_embeddings = clip_model.text_encode(text)  # 编码条件文本,cond
empty_embeddings = clip_model.text_encode("")  # 编码空文本,uncond
text_embeddings = torch.cat(empty_embeddings, text_embeddings)  # concat到一起,只做一次forward

input = torch.randn((1, 3, sample_size, sample_size), device="cuda") # 采样初始噪声

for t in scheduler.timesteps:
    # 用 unet 推理,预测噪声
    with torch.no_grad():
        # 这里同时预测出了有文本的和空文本的图像噪声
        noise_pred = unet(input, t, encoder_hidden_states=text_embeddings).sample

    # 拆成无条件和有条件的噪声
    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
    # Classifier-Free Guidance 引导 
    noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
    # 用预测出的 noise_pred 和 x_t 计算得到 x_t-1
    latents = scheduler.step(noise_pred, t, latents).prev_sample

DiT代码实现:

# Create sampling noise:
n = len(class_labels)
z = torch.randn(n, 4, latent_size, latent_size, device=device)
y = torch.tensor(class_labels, device=device)

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

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

Patchify:patch_embedding

代码实现: 

'''
PatchEmbed(
    (proj): Conv2d(4, 1152, kernel_size=(2, 2), stride=(2, 2))
    (norm): Identity()
)
[16, 4, 32, 32] → [16, 256, 1152]
'''
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。

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]
t = self.t_embedder(t)                   # (N, D)   # [16, 1152]
y = self.y_embedder(y, self.training)    # (N, D)   # [16, 1152]
c = t + y                                # (N, D)   # [16, 1152]

位置编码:梯度不更新

# Will use fixed sin-cos embedding:
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)

# Initialize (and freeze) pos_embed by sin-cos embedding:
pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))   # (256, 1152)
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))   # (1, 256, 1152)

def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):
    """
    grid_size: int of the grid height and width  16
    return:
    pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
    """
    grid_h = np.arange(grid_size, dtype=np.float32)
    grid_w = np.arange(grid_size, dtype=np.float32)
    grid = np.meshgrid(grid_w, grid_h)  # here w goes first
    grid = np.stack(grid, axis=0)   # (2, 16, 16)

    grid = grid.reshape([2, 1, grid_size, grid_size])   # (2, 1, 16, 16)
    pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)   # (256, 1152)
    if cls_token and extra_tokens > 0:
        pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
    return pos_embed   # (256, 1152)


def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
    assert embed_dim % 2 == 0
    # embed_dim = 576

    # use half of dimensions to encode grid_h
    emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])  # x坐标, (256, 576)
    emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])  # y坐标, (256, 576)

    pdb.set_trace()
    emb = np.concatenate([emb_h, emb_w], axis=1) # (256, 1152)
    return emb


def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
    """
    embed_dim: output dimension for each position
    pos: a list of positions to be encoded: size (M,)
    out: (M, D)
    """
    assert embed_dim % 2 == 0
    omega = np.arange(embed_dim // 2, dtype=np.float64)
    omega /= embed_dim / 2.
    omega = 1. / 10000**omega  # (288,)

    pos = pos.reshape(-1)  # (256,)
    out = np.einsum('m,d->md', pos, omega)  # (256, 288), outer product

    emb_sin = np.sin(out) # (256, 288)
    emb_cos = np.cos(out) # (256, 288)

    emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (256, 576)
    return emb

TimestepEmbedder:

class TimestepEmbedder(nn.Module):
    """
    Embeds scalar timesteps into vector representations.
    """
    def __init__(self, hidden_size, frequency_embedding_size=256):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(frequency_embedding_size, hidden_size, bias=True),
            nn.SiLU(),
            nn.Linear(hidden_size, hidden_size, bias=True),
        )
        self.frequency_embedding_size = frequency_embedding_size

    @staticmethod
    def timestep_embedding(t, dim, max_period=10000):
        """
        Create sinusoidal timestep embeddings.
        :param t: 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, D) Tensor of positional embeddings.
        """
        # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
        half = dim // 2   # 128
        freqs = torch.exp(
            -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
        ).to(device=t.device)   # 128
        args = t[:, None].float() * freqs[None]   # (16, 1) * (1, 128) = (16, 128)
        embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)   # (16, 256)
        if dim % 2:
            embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
        return embedding   # (16, 256)

    def forward(self, t):
        t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
        t_emb = self.mlp(t_freq)
        return t_emb   # (16, 1152)

LabelEmbedder:

class LabelEmbedder(nn.Module):
    """
    Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
    """
    def __init__(self, num_classes, hidden_size, dropout_prob):
        super().__init__()
        use_cfg_embedding = dropout_prob > 0
        self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)   # 1001 → 1152
        self.num_classes = num_classes   # 1000
        self.dropout_prob = dropout_prob   # 0.1

    def token_drop(self, labels, force_drop_ids=None):
        """
        Drops labels to enable classifier-free guidance.
        """
        if force_drop_ids is None:
            drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
        else:
            drop_ids = force_drop_ids == 1
        labels = torch.where(drop_ids, self.num_classes, labels)
        return labels

    def forward(self, labels, train, force_drop_ids=None):
        use_dropout = self.dropout_prob > 0   # 0.1
        if (train and use_dropout) or (force_drop_ids is not None):
            labels = self.token_drop(labels, force_drop_ids)
        embeddings = self.embedding_table(labels)
        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的嵌入向量之和对它们进行回归。

代码实现:

class DiTBlock(nn.Module):
    """
    A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.
    """
    def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):
        super().__init__()
        self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
        self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)
        self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
        mlp_hidden_dim = int(hidden_size * mlp_ratio)
        approx_gelu = lambda: nn.GELU(approximate="tanh")
        self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)
        self.adaLN_modulation = nn.Sequential(
            nn.SiLU(),
            nn.Linear(hidden_size, 6 * hidden_size, bias=True)   # [16, 6912]
        )

    def forward(self, x, c):
        # β1, γ1, α1, β2, γ2, α2 
        shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)  # 6 * [16, 1152]
        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]
        x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))   # mlp() * scale + x = [16, 256, 1152]
        return x

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

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

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

class FinalLayer(nn.Module):
    """
    The final layer of DiT.
    """
    def __init__(self, hidden_size, patch_size, out_channels):
        super().__init__()
        self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
        self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
        self.adaLN_modulation = nn.Sequential(
            nn.SiLU(),
            nn.Linear(hidden_size, 2 * hidden_size, bias=True)
        )

    def forward(self, x, c):
        shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)   # 2 * [16, 1152]
        x = modulate(self.norm_final(x), shift, scale)   # [16, 256, 1152]
        x = self.linear(x)   # [16, 256, 32]
        return x

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

def unpatchify(self, x):
    """
    x: (N, T, patch_size**2 * C)
    imgs: (N, H, W, C)
    """
    c = self.out_channels   # 8
    p = self.x_embedder.patch_size[0]   # 2
    h = w = int(x.shape[1] ** 0.5)   # 16
    assert h * w == x.shape[1]

    x = x.reshape(shape=(x.shape[0], h, w, p, p, c))   # [16, 16, 16, 2, 2, 8]
    x = torch.einsum('nhwpqc->nchpwq', x)   # [16, 8, 16, 2, 16, 2]
    imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))   # [16, 8, 32, 32]
    return imgs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值