Spaces:
Running
on
Zero
Running
on
Zero
# Copyright (c) Meta Platforms, Inc. and affiliates. | |
# All rights reserved. | |
# This source code is licensed under the license found in the | |
# LICENSE file in the root directory of this source tree. | |
# -------------------------------------------------------- | |
# References: | |
# GLIDE: https://github.com/openai/glide-text2im | |
# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py | |
# -------------------------------------------------------- | |
import torch | |
import torch.nn as nn | |
import numpy as np | |
import math | |
from timm.models.vision_transformer import PatchEmbed, Attention, Mlp | |
import xformers.ops | |
def modulate(x, shift, scale): | |
return x * (1 + scale) + shift | |
################################################################################# | |
# Embedding Layers for Timesteps and Class Labels # | |
################################################################################# | |
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 | |
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 | |
freqs = torch.exp( | |
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half | |
).to(device=t.device) | |
args = t[:, None].float() * freqs[None] | |
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) | |
if dim % 2: | |
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) | |
return embedding | |
def forward(self, t): | |
t_freq = self.timestep_embedding(t, self.frequency_embedding_size) | |
t_emb = self.mlp(t_freq) | |
return t_emb | |
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) | |
self.num_classes = num_classes | |
self.dropout_prob = dropout_prob | |
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 | |
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 | |
class MultiHeadCrossAttention(nn.Module): | |
def __init__(self, d_model, num_heads, attn_drop=0., proj_drop=0., **block_kwargs): | |
super(MultiHeadCrossAttention, self).__init__() | |
assert d_model % num_heads == 0, "d_model must be divisible by num_heads" | |
self.d_model = d_model | |
self.num_heads = num_heads | |
self.head_dim = d_model // num_heads | |
self.q_linear = nn.Linear(d_model, d_model) | |
self.kv_linear = nn.Linear(d_model, d_model*2) | |
self.attn_drop = nn.Dropout(attn_drop) | |
self.proj = nn.Linear(d_model, d_model) | |
self.proj_drop = nn.Dropout(proj_drop) | |
def forward(self, x, cond, mask=None): | |
# query: img tokens; key/value: condition; mask: if padding tokens | |
B, N, C = x.shape | |
q = self.q_linear(x).view(1, -1, self.num_heads, self.head_dim) | |
kv = self.kv_linear(cond).view(1, -1, 2, self.num_heads, self.head_dim) | |
k, v = kv.unbind(2) | |
attn_bias = None | |
if mask is not None: | |
attn_bias = xformers.ops.fmha.BlockDiagonalMask.from_seqlens([N] * B, mask) | |
x = xformers.ops.memory_efficient_attention(q, k, v, p=self.attn_drop.p, attn_bias=attn_bias) | |
x = x.view(B, -1, C) | |
x = self.proj(x) | |
x = self.proj_drop(x) | |
return x | |
################################################################################# | |
# Core DiT Model # | |
################################################################################# | |
class DiTBlock(nn.Module): | |
""" | |
A DiT block with cross attention for conditioning. Adapted from PixArt implementation. | |
""" | |
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.cross_attn = MultiHeadCrossAttention(hidden_size, num_heads, **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) | |
#) | |
self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size ** 0.5) | |
def forward(self, x, y, t, mask=None): | |
B, N, C = x.shape | |
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (self.scale_shift_table[None] + t.reshape(B, 6, -1)).chunk(6, dim=1) | |
x = x + gate_msa * self.attn(modulate(self.norm1(x), shift_msa, scale_msa)).reshape(B, N, C) | |
x = x + self.cross_attn(x, y, mask) | |
x = x + gate_mlp * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp)) | |
return x | |
class FinalLayer(nn.Module): | |
""" | |
The final layer of DiT. | |
""" | |
def __init__(self, hidden_size, out_channels): | |
super().__init__() | |
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) | |
self.linear = nn.Linear(hidden_size, out_channels, bias=True) | |
self.scale_shift_table = nn.Parameter(torch.randn(2, hidden_size) / hidden_size ** 0.5) | |
self.out_channels = out_channels | |
def forward(self, x, t): | |
shift, scale = (self.scale_shift_table[None] + t[:, None]).chunk(2, dim=1) | |
x = modulate(self.norm_final(x), shift, scale) | |
x = self.linear(x) | |
return x | |
class DiT(nn.Module): | |
""" | |
Diffusion model with a Transformer backbone. | |
""" | |
def __init__( | |
self, | |
input_size=32, | |
in_channels=1, | |
hidden_size=128, | |
depth=12, | |
num_heads=6, | |
mlp_ratio=4.0, | |
condition_channels=768, | |
learn_sigma=True, | |
): | |
super().__init__() | |
self.learn_sigma = learn_sigma | |
self.input_size = input_size | |
self.in_channels = in_channels | |
self.out_channels = in_channels * 2 if learn_sigma else in_channels | |
self.num_heads = num_heads | |
self.x_embedder = nn.Linear(in_channels, hidden_size, bias=True) | |
self.t_embedder = TimestepEmbedder(hidden_size) | |
approx_gelu = lambda: nn.GELU(approximate="tanh") | |
self.t_block = nn.Sequential( | |
nn.SiLU(), | |
nn.Linear(hidden_size, 6 * hidden_size, bias=True) | |
) | |
self.y_embedder = Mlp(in_features=condition_channels, hidden_features=hidden_size, out_features=hidden_size, act_layer=approx_gelu, drop=0) | |
# Will use fixed sin-cos embedding: | |
self.pos_embed = nn.Parameter(torch.zeros(1, input_size, hidden_size), requires_grad=False) | |
self.blocks = nn.ModuleList([ | |
DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth) | |
]) | |
self.final_layer = FinalLayer(hidden_size, self.out_channels) | |
self.initialize_weights() | |
def initialize_weights(self): | |
# Initialize transformer layers: | |
def _basic_init(module): | |
if isinstance(module, nn.Linear): | |
torch.nn.init.xavier_uniform_(module.weight) | |
if module.bias is not None: | |
nn.init.constant_(module.bias, 0) | |
self.apply(_basic_init) | |
# Initialize (and freeze) pos_embed by sin-cos embedding: | |
grid_1d = np.arange(self.input_size, dtype=np.float32) | |
pos_embed = get_1d_sincos_pos_embed_from_grid(self.pos_embed.shape[-1], grid_1d) | |
self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0)) | |
# Initialize patch_embed like nn.Linear (instead of nn.Conv2d): | |
nn.init.xavier_uniform_(self.x_embedder.weight) | |
nn.init.constant_(self.x_embedder.bias, 0) | |
# Initialize label embedding table: | |
nn.init.normal_(self.y_embedder.fc1.weight, std=0.02) | |
nn.init.normal_(self.y_embedder.fc2.weight, std=0.02) | |
# Initialize timestep embedding MLP: | |
nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) | |
nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) | |
# Zero-out adaLN modulation layers in DiT blocks: | |
for block in self.blocks: | |
nn.init.constant_(block.cross_attn.proj.weight, 0) | |
nn.init.constant_(block.cross_attn.proj.bias, 0) | |
# Zero-out output layers: | |
nn.init.constant_(self.final_layer.linear.weight, 0) | |
nn.init.constant_(self.final_layer.linear.bias, 0) | |
def ckpt_wrapper(self, module): | |
def ckpt_forward(*inputs): | |
outputs = module(*inputs) | |
return outputs | |
return ckpt_forward | |
def forward(self, x, t, y): | |
""" | |
Forward pass of DiT. | |
x: (N, 1, T) tensor of PCG params | |
t: (N,) tensor of diffusion timesteps | |
y: (N, 1, C) or (N, M, C) tensor of condition image features | |
""" | |
x = x.permute(0, 2, 1) | |
x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T is the input token number (params number) | |
t = self.t_embedder(t) # (N, D) | |
t0 = self.t_block(t) | |
y = self.y_embedder(y) # (N, M, D) | |
# mask for batch cross-attention | |
y_lens = [y.shape[1]] * y.shape[0] | |
y = y.view(1, -1, x.shape[-1]) | |
for block in self.blocks: | |
x = torch.utils.checkpoint.checkpoint(self.ckpt_wrapper(block), x, y, t0, y_lens) # (N, T, D) | |
x = self.final_layer(x, t) # (N, T, out_channels) | |
return x.permute(0, 2, 1) | |
################################################################################# | |
# Sine/Cosine Positional Embedding Functions # | |
################################################################################# | |
# https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py | |
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 # (D/2,) | |
pos = pos.reshape(-1) # (M,) | |
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product | |
emb_sin = np.sin(out) # (M, D/2) | |
emb_cos = np.cos(out) # (M, D/2) | |
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D) | |
return emb | |
################################################################################# | |
# DiT Configs # | |
################################################################################# | |
def DiT_S(**kwargs): | |
# 39M | |
return DiT(depth=16, hidden_size=384, num_heads=6, **kwargs) | |
def DiT_mini(**kwargs): | |
# 7.6M | |
return DiT(depth=12, hidden_size=192, num_heads=6, **kwargs) | |
def DiT_tiny(**kwargs): | |
# 1.3M | |
return DiT(depth=8, hidden_size=96, num_heads=6, **kwargs) | |
DiT_models = { | |
'DiT_S': DiT_S, | |
'DiT_mini': DiT_mini, | |
'DiT_tiny': DiT_tiny | |
} | |