Upload folder using huggingface_hub
Browse files- added_tokens.json +3 -0
- config.json +19 -0
- configuration_dit.py +25 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_dit.py +391 -0
- special_tokens_map.json +37 -0
- tokenizer.json +0 -0
- tokenizer_config.json +30 -0
- vocab.json +0 -0
added_tokens.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"[MASK]": 50257
|
| 3 |
+
}
|
config.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"DIT"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_dit.DITConfig",
|
| 8 |
+
"AutoModelForMaskedLM": "modeling_dit.DIT"
|
| 9 |
+
},
|
| 10 |
+
"hidden_size": 768,
|
| 11 |
+
"max_seq_len": 512,
|
| 12 |
+
"model_type": "dit",
|
| 13 |
+
"num_attention_heads": 12,
|
| 14 |
+
"num_hidden_layers": 12,
|
| 15 |
+
"timestep_cond_dim": 128,
|
| 16 |
+
"torch_dtype": "float32",
|
| 17 |
+
"transformers_version": "4.49.0",
|
| 18 |
+
"vocab_size": 50258
|
| 19 |
+
}
|
configuration_dit.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class DITConfig(PretrainedConfig):
|
| 5 |
+
model_type = "dit"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
vocab_size: int = 50258,
|
| 10 |
+
max_seq_len: int = 1024,
|
| 11 |
+
hidden_size: int = 768,
|
| 12 |
+
timestep_cond_dim: int = 128,
|
| 13 |
+
num_hidden_layers: int = 12,
|
| 14 |
+
num_attention_heads: int = 12,
|
| 15 |
+
attention_dropout: float = 0.0,
|
| 16 |
+
**kwargs
|
| 17 |
+
):
|
| 18 |
+
super().__init__(**kwargs)
|
| 19 |
+
self.vocab_size = vocab_size
|
| 20 |
+
self.max_seq_len = max_seq_len
|
| 21 |
+
self.hidden_size = hidden_size
|
| 22 |
+
self.timestep_cond_dim = timestep_cond_dim
|
| 23 |
+
self.num_hidden_layers = num_hidden_layers
|
| 24 |
+
self.num_attention_heads = num_attention_heads
|
| 25 |
+
self.attention_dropout = attention_dropout
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1a28915d92e35fa1b41f130fab3e84d23de79be478dc0f8fc40e5d60c9fbb97
|
| 3 |
+
size 679307960
|
modeling_dit.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# from: https://github.com/kuleshov-group/mdlm/blob/master/models/dit.py
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
import omegaconf
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from transformers import PreTrainedModel
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
|
| 13 |
+
from .configuration_dit import DITConfig
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
import flash_attn
|
| 17 |
+
import flash_attn.layers.rotary
|
| 18 |
+
has_flash_attn = True
|
| 19 |
+
except ImportError:
|
| 20 |
+
torch.backends.cuda.enable_flash_sdp(enabled=True)
|
| 21 |
+
has_flash_attn = False
|
| 22 |
+
|
| 23 |
+
# Flags required to enable jit fusion kernels
|
| 24 |
+
torch._C._jit_set_profiling_mode(False)
|
| 25 |
+
torch._C._jit_set_profiling_executor(False)
|
| 26 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
| 27 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def bias_dropout_add_scale(
|
| 31 |
+
x: torch.Tensor,
|
| 32 |
+
bias: typing.Optional[torch.Tensor],
|
| 33 |
+
scale: torch.Tensor,
|
| 34 |
+
residual: typing.Optional[torch.Tensor],
|
| 35 |
+
prob: float,
|
| 36 |
+
training: bool) -> torch.Tensor:
|
| 37 |
+
if bias is not None:
|
| 38 |
+
out = scale * F.dropout(x + bias, p=prob, training=training)
|
| 39 |
+
else:
|
| 40 |
+
out = scale * F.dropout(x, p=prob, training=training)
|
| 41 |
+
|
| 42 |
+
if residual is not None:
|
| 43 |
+
out = residual + out
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_bias_dropout_add_scale(training):
|
| 48 |
+
def _bias_dropout_add(x, bias, scale, residual, prob):
|
| 49 |
+
return bias_dropout_add_scale(
|
| 50 |
+
x, bias, scale, residual, prob, training)
|
| 51 |
+
|
| 52 |
+
return _bias_dropout_add
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# function overload
|
| 56 |
+
def modulate(x: torch.Tensor,
|
| 57 |
+
shift: torch.Tensor,
|
| 58 |
+
scale: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
return x * (1 + scale) + shift
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# @torch.jit.script
|
| 63 |
+
def bias_dropout_add_scale_fused_train(
|
| 64 |
+
x: torch.Tensor,
|
| 65 |
+
bias: typing.Optional[torch.Tensor],
|
| 66 |
+
scale: torch.Tensor,
|
| 67 |
+
residual: typing.Optional[torch.Tensor],
|
| 68 |
+
prob: float) -> torch.Tensor:
|
| 69 |
+
return bias_dropout_add_scale(
|
| 70 |
+
x, bias, scale, residual, prob, True)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# @torch.jit.script
|
| 74 |
+
def bias_dropout_add_scale_fused_inference(
|
| 75 |
+
x: torch.Tensor,
|
| 76 |
+
bias: typing.Optional[torch.Tensor],
|
| 77 |
+
scale: torch.Tensor,
|
| 78 |
+
residual: typing.Optional[torch.Tensor],
|
| 79 |
+
prob: float) -> torch.Tensor:
|
| 80 |
+
return bias_dropout_add_scale(
|
| 81 |
+
x, bias, scale, residual, prob, False)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# @torch.jit.script
|
| 85 |
+
def modulate_fused(x: torch.Tensor,
|
| 86 |
+
shift: torch.Tensor,
|
| 87 |
+
scale: torch.Tensor) -> torch.Tensor:
|
| 88 |
+
return modulate(x, shift, scale)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class Rotary(torch.nn.Module):
|
| 92 |
+
def __init__(self, dim, base=10_000, max_seq_len=512):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.dim = dim
|
| 95 |
+
self.base = base
|
| 96 |
+
self.max_seq_len = max_seq_len
|
| 97 |
+
self.precompute()
|
| 98 |
+
|
| 99 |
+
def precompute(self):
|
| 100 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))
|
| 101 |
+
t = torch.arange(self.max_seq_len).type_as(inv_freq)
|
| 102 |
+
freqs = torch.einsum("i,j->ij", t, inv_freq.clone())
|
| 103 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 104 |
+
# dims are: batch, seq_len, qkv, head, dim
|
| 105 |
+
cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
|
| 106 |
+
sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
|
| 107 |
+
# This makes the transformation on v an identity.
|
| 108 |
+
cos_cached[:,:,2,:,:].fill_(1.)
|
| 109 |
+
sin_cached[:,:,2,:,:].fill_(0.)
|
| 110 |
+
|
| 111 |
+
self.register_buffer('cos_cached', cos_cached)
|
| 112 |
+
self.register_buffer('sin_cached', sin_cached)
|
| 113 |
+
|
| 114 |
+
def forward(self, x, seq_dim=1):
|
| 115 |
+
seq_len = x.shape[seq_dim]
|
| 116 |
+
return self.cos_cached[:, :, :seq_len], self.sin_cached[:, :, :seq_len]
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def rotate_half(x):
|
| 120 |
+
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
| 121 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def apply_rotary_pos_emb(qkv, cos, sin):
|
| 125 |
+
if has_flash_attn:
|
| 126 |
+
cos = cos[0,:,0,0,:cos.shape[-1]//2]
|
| 127 |
+
sin = sin[0,:,0,0,:sin.shape[-1]//2]
|
| 128 |
+
return flash_attn.layers.rotary.apply_rotary_emb_qkv_(qkv, cos, sin)
|
| 129 |
+
else:
|
| 130 |
+
return (qkv * cos) + (rotate_half(qkv) * sin)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# function overload
|
| 134 |
+
def modulate(x, shift, scale):
|
| 135 |
+
return x * (1 + scale) + shift
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
#################################################################################
|
| 139 |
+
# Layers #
|
| 140 |
+
#################################################################################
|
| 141 |
+
class LayerNorm(nn.Module):
|
| 142 |
+
def __init__(self, dim):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.weight = nn.Parameter(torch.ones([dim]))
|
| 145 |
+
self.dim = dim
|
| 146 |
+
def forward(self, x):
|
| 147 |
+
x = F.layer_norm(x.float(), [self.dim])
|
| 148 |
+
return x * self.weight[None,None,:]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def residual_linear(x, W, x_skip, residual_scale):
|
| 152 |
+
"""x_skip + residual_scale * W @ x"""
|
| 153 |
+
dim_out, dim_in = W.shape[0], W.shape[1]
|
| 154 |
+
return torch.addmm(
|
| 155 |
+
x_skip.view(-1, dim_out),
|
| 156 |
+
x.view(-1, dim_in),
|
| 157 |
+
W.T,
|
| 158 |
+
alpha=residual_scale).view(*x.shape[:-1], dim_out)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
#################################################################################
|
| 162 |
+
# Embedding Layers for Timesteps and Class Labels #
|
| 163 |
+
#################################################################################
|
| 164 |
+
class TimestepEmbedder(nn.Module):
|
| 165 |
+
"""
|
| 166 |
+
Embeds scalar timesteps into vector representations.
|
| 167 |
+
"""
|
| 168 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
| 169 |
+
super().__init__()
|
| 170 |
+
self.mlp = nn.Sequential(
|
| 171 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
| 172 |
+
nn.SiLU(),
|
| 173 |
+
nn.Linear(hidden_size, hidden_size, bias=True))
|
| 174 |
+
self.frequency_embedding_size = frequency_embedding_size
|
| 175 |
+
|
| 176 |
+
@staticmethod
|
| 177 |
+
def timestep_embedding(t, dim, max_period=10000):
|
| 178 |
+
"""
|
| 179 |
+
Create sinusoidal timestep embeddings.
|
| 180 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
| 181 |
+
These may be fractional.
|
| 182 |
+
:param dim: the dimension of the output.
|
| 183 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 184 |
+
:return: an (N, D) Tensor of positional embeddings.
|
| 185 |
+
"""
|
| 186 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
| 187 |
+
half = dim // 2
|
| 188 |
+
freqs = torch.exp(
|
| 189 |
+
- math.log(max_period)
|
| 190 |
+
* torch.arange(start=0, end=half, dtype=torch.float32)
|
| 191 |
+
/ half).to(device=t.device)
|
| 192 |
+
args = t[:, None].float() * freqs[None]
|
| 193 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 194 |
+
if dim % 2:
|
| 195 |
+
embedding = torch.cat(
|
| 196 |
+
[embedding,
|
| 197 |
+
torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 198 |
+
return embedding
|
| 199 |
+
|
| 200 |
+
def forward(self, t):
|
| 201 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
| 202 |
+
t_emb = self.mlp(t_freq)
|
| 203 |
+
return t_emb
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class LabelEmbedder(nn.Module):
|
| 207 |
+
"""Embeds class labels into vector representations.
|
| 208 |
+
|
| 209 |
+
Also handles label dropout for classifier-free guidance.
|
| 210 |
+
"""
|
| 211 |
+
def __init__(self, num_classes, cond_size):
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
|
| 214 |
+
self.num_classes = num_classes
|
| 215 |
+
|
| 216 |
+
# TODO think of initializing with 0.02 std deviation like in original DiT paper
|
| 217 |
+
|
| 218 |
+
def forward(self, labels):
|
| 219 |
+
embeddings = self.embedding_table(labels)
|
| 220 |
+
return embeddings
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
#################################################################################
|
| 224 |
+
# Core Model #
|
| 225 |
+
#################################################################################
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class DDiTBlock(nn.Module):
|
| 229 |
+
def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
|
| 230 |
+
super().__init__()
|
| 231 |
+
self.n_heads = n_heads
|
| 232 |
+
self.dim = dim
|
| 233 |
+
self.cond_dim = cond_dim
|
| 234 |
+
self.mlp_ratio = mlp_ratio
|
| 235 |
+
|
| 236 |
+
self.norm1 = LayerNorm(dim)
|
| 237 |
+
self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
|
| 238 |
+
self.attn_out = nn.Linear(dim, dim, bias=False)
|
| 239 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 240 |
+
|
| 241 |
+
self.norm2 = LayerNorm(dim)
|
| 242 |
+
self.mlp = nn.Sequential(
|
| 243 |
+
nn.Linear(dim, mlp_ratio * dim, bias=True),
|
| 244 |
+
nn.GELU(approximate='tanh'),
|
| 245 |
+
nn.Linear(mlp_ratio * dim, dim, bias=True))
|
| 246 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 247 |
+
self.dropout = dropout
|
| 248 |
+
|
| 249 |
+
self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
|
| 250 |
+
self.adaLN_modulation.weight.data.zero_()
|
| 251 |
+
self.adaLN_modulation.bias.data.zero_()
|
| 252 |
+
|
| 253 |
+
def _get_bias_dropout_scale(self):
|
| 254 |
+
if self.training:
|
| 255 |
+
return bias_dropout_add_scale_fused_train
|
| 256 |
+
else:
|
| 257 |
+
return bias_dropout_add_scale_fused_inference
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def forward(self, x, rotary_cos_sin, c, seqlens=None):
|
| 261 |
+
batch_size, seq_len = x.shape[0], x.shape[1]
|
| 262 |
+
|
| 263 |
+
bias_dropout_scale_fn = self._get_bias_dropout_scale()
|
| 264 |
+
|
| 265 |
+
(shift_msa, scale_msa, gate_msa, shift_mlp,
|
| 266 |
+
scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
|
| 267 |
+
|
| 268 |
+
# attention operation
|
| 269 |
+
x_skip = x
|
| 270 |
+
x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
|
| 271 |
+
|
| 272 |
+
qkv = self.attn_qkv(x)
|
| 273 |
+
qkv = rearrange(qkv,
|
| 274 |
+
'b s (three h d) -> b s three h d',
|
| 275 |
+
three=3,
|
| 276 |
+
h=self.n_heads)
|
| 277 |
+
cos, sin = rotary_cos_sin
|
| 278 |
+
qkv = apply_rotary_pos_emb(
|
| 279 |
+
qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
|
| 280 |
+
|
| 281 |
+
if has_flash_attn:
|
| 282 |
+
qkv = rearrange(qkv, 'b s ... -> (b s) ...')
|
| 283 |
+
if seqlens is None:
|
| 284 |
+
cu_seqlens = torch.arange(
|
| 285 |
+
0, (batch_size + 1) * seq_len, step=seq_len,
|
| 286 |
+
dtype=torch.int32, device=qkv.device)
|
| 287 |
+
else:
|
| 288 |
+
cu_seqlens = seqlens.cumsum(-1)
|
| 289 |
+
x = flash_attn.flash_attn_interface.flash_attn_varlen_qkvpacked_func(
|
| 290 |
+
qkv, cu_seqlens, seq_len, 0., causal=False)
|
| 291 |
+
x = rearrange(x, '(b s) h d -> b s (h d)', b=batch_size)
|
| 292 |
+
else:
|
| 293 |
+
q, k, v = qkv[:, :, 0].transpose(1, 2), qkv[:, :, 1].transpose(1, 2), qkv[:, :, 2].transpose(1, 2)
|
| 294 |
+
x = F.scaled_dot_product_attention(q, k, v)
|
| 295 |
+
|
| 296 |
+
x = rearrange(x, 'b h s d -> b s (h d)', b=batch_size)
|
| 297 |
+
|
| 298 |
+
x = bias_dropout_scale_fn(self.attn_out(x),
|
| 299 |
+
None,
|
| 300 |
+
gate_msa,
|
| 301 |
+
x_skip,
|
| 302 |
+
self.dropout)
|
| 303 |
+
|
| 304 |
+
# mlp operation
|
| 305 |
+
x = bias_dropout_scale_fn(
|
| 306 |
+
self.mlp(modulate_fused(
|
| 307 |
+
self.norm2(x), shift_mlp, scale_mlp)),
|
| 308 |
+
None, gate_mlp, x, self.dropout)
|
| 309 |
+
return x
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class EmbeddingLayer(nn.Module):
|
| 314 |
+
def __init__(self, dim, vocab_dim):
|
| 315 |
+
super().__init__()
|
| 316 |
+
self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
|
| 317 |
+
torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
|
| 318 |
+
|
| 319 |
+
def forward(self, x):
|
| 320 |
+
return self.embedding[x]
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class DDitFinalLayer(nn.Module):
|
| 324 |
+
def __init__(self, hidden_size, out_channels, cond_dim):
|
| 325 |
+
super().__init__()
|
| 326 |
+
self.norm_final = LayerNorm(hidden_size)
|
| 327 |
+
self.linear = nn.Linear(hidden_size, out_channels)
|
| 328 |
+
self.linear.weight.data.zero_()
|
| 329 |
+
self.linear.bias.data.zero_()
|
| 330 |
+
|
| 331 |
+
self.adaLN_modulation = nn.Linear(cond_dim,
|
| 332 |
+
2 * hidden_size,
|
| 333 |
+
bias=True)
|
| 334 |
+
self.adaLN_modulation.weight.data.zero_()
|
| 335 |
+
self.adaLN_modulation.bias.data.zero_()
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def forward(self, x, c):
|
| 339 |
+
shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
|
| 340 |
+
x = modulate_fused(self.norm_final(x), shift, scale)
|
| 341 |
+
x = self.linear(x)
|
| 342 |
+
return x
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
class DIT(PreTrainedModel):
|
| 346 |
+
config_class = DITConfig
|
| 347 |
+
base_model_prefix = "dit"
|
| 348 |
+
|
| 349 |
+
def __init__(self, config: DITConfig):
|
| 350 |
+
super().__init__(config)
|
| 351 |
+
|
| 352 |
+
self.config = config
|
| 353 |
+
self.vocab_size = config.vocab_size
|
| 354 |
+
|
| 355 |
+
self.vocab_embed = EmbeddingLayer(config.hidden_size, config.vocab_size)
|
| 356 |
+
self.sigma_map = TimestepEmbedder(config.timestep_cond_dim)
|
| 357 |
+
self.rotary_emb = Rotary(
|
| 358 |
+
config.hidden_size // config.num_attention_heads,
|
| 359 |
+
max_seq_len=config.max_seq_len,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
blocks = []
|
| 363 |
+
for _ in range(config.num_hidden_layers):
|
| 364 |
+
blocks.append(DDiTBlock(config.hidden_size,
|
| 365 |
+
config.num_attention_heads,
|
| 366 |
+
config.timestep_cond_dim,
|
| 367 |
+
dropout=config.attention_dropout))
|
| 368 |
+
self.blocks = nn.ModuleList(blocks)
|
| 369 |
+
|
| 370 |
+
self.output_layer = DDitFinalLayer(
|
| 371 |
+
config.hidden_size,
|
| 372 |
+
config.vocab_size,
|
| 373 |
+
config.timestep_cond_dim)
|
| 374 |
+
|
| 375 |
+
def _get_bias_dropout_scale(self):
|
| 376 |
+
if self.training:
|
| 377 |
+
return bias_dropout_add_scale_fused_train
|
| 378 |
+
else:
|
| 379 |
+
return bias_dropout_add_scale_fused_inference
|
| 380 |
+
|
| 381 |
+
def forward(self, input_ids, timesteps):
|
| 382 |
+
x = self.vocab_embed(input_ids)
|
| 383 |
+
c = F.silu(self.sigma_map(timesteps))
|
| 384 |
+
|
| 385 |
+
rotary_cos_sin = self.rotary_emb(x)
|
| 386 |
+
|
| 387 |
+
for i in range(len(self.blocks)):
|
| 388 |
+
x = self.blocks[i](x, rotary_cos_sin, c, seqlens=None)
|
| 389 |
+
x = self.output_layer(x, c)
|
| 390 |
+
|
| 391 |
+
return x
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<|endoftext|>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": true,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"eos_token": {
|
| 10 |
+
"content": "<|endoftext|>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": true,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"mask_token": {
|
| 17 |
+
"content": "[MASK]",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"content": "<|endoftext|>",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": true,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
},
|
| 30 |
+
"unk_token": {
|
| 31 |
+
"content": "<|endoftext|>",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": true,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false
|
| 36 |
+
}
|
| 37 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"added_tokens_decoder": {
|
| 4 |
+
"50256": {
|
| 5 |
+
"content": "<|endoftext|>",
|
| 6 |
+
"lstrip": false,
|
| 7 |
+
"normalized": true,
|
| 8 |
+
"rstrip": false,
|
| 9 |
+
"single_word": false,
|
| 10 |
+
"special": true
|
| 11 |
+
},
|
| 12 |
+
"50257": {
|
| 13 |
+
"content": "[MASK]",
|
| 14 |
+
"lstrip": false,
|
| 15 |
+
"normalized": false,
|
| 16 |
+
"rstrip": false,
|
| 17 |
+
"single_word": false,
|
| 18 |
+
"special": true
|
| 19 |
+
}
|
| 20 |
+
},
|
| 21 |
+
"bos_token": "<|endoftext|>",
|
| 22 |
+
"clean_up_tokenization_spaces": false,
|
| 23 |
+
"eos_token": "<|endoftext|>",
|
| 24 |
+
"extra_special_tokens": {},
|
| 25 |
+
"mask_token": "[MASK]",
|
| 26 |
+
"model_max_length": 512,
|
| 27 |
+
"pad_token": "<|endoftext|>",
|
| 28 |
+
"tokenizer_class": "GPT2Tokenizer",
|
| 29 |
+
"unk_token": "<|endoftext|>"
|
| 30 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|